No Description

RNFetchBlobFS.java 43KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. package com.RNFetchBlob;
  2. import android.content.res.AssetFileDescriptor;
  3. import android.media.MediaScannerConnection;
  4. import android.net.Uri;
  5. import android.os.AsyncTask;
  6. import android.os.Build;
  7. import android.os.Environment;
  8. import android.os.StatFs;
  9. import android.os.SystemClock;
  10. import android.util.Base64;
  11. import com.RNFetchBlob.Utils.PathResolver;
  12. import com.facebook.react.bridge.Arguments;
  13. import com.facebook.react.bridge.Callback;
  14. import com.facebook.react.bridge.Promise;
  15. import com.facebook.react.bridge.ReactApplicationContext;
  16. import com.facebook.react.bridge.ReadableArray;
  17. import com.facebook.react.bridge.WritableArray;
  18. import com.facebook.react.bridge.WritableMap;
  19. import com.facebook.react.modules.core.DeviceEventManagerModule;
  20. import java.io.*;
  21. import java.nio.ByteBuffer;
  22. import java.nio.charset.Charset;
  23. import java.nio.charset.CharsetEncoder;
  24. import java.security.MessageDigest;
  25. import java.util.ArrayList;
  26. import java.util.HashMap;
  27. import java.util.Map;
  28. import java.util.UUID;
  29. class RNFetchBlobFS {
  30. private ReactApplicationContext mCtx;
  31. private DeviceEventManagerModule.RCTDeviceEventEmitter emitter;
  32. private String encoding = "base64";
  33. private OutputStream writeStreamInstance = null;
  34. private static HashMap<String, RNFetchBlobFS> fileStreams = new HashMap<>();
  35. RNFetchBlobFS(ReactApplicationContext ctx) {
  36. this.mCtx = ctx;
  37. this.emitter = ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
  38. }
  39. /**
  40. * Write string with encoding to file
  41. * @param path Destination file path.
  42. * @param encoding Encoding of the string.
  43. * @param data Array passed from JS context.
  44. * @param promise RCT Promise
  45. */
  46. static void writeFile(String path, String encoding, String data, final boolean append, final Promise promise) {
  47. try {
  48. int written;
  49. File f = new File(path);
  50. File dir = f.getParentFile();
  51. if(!f.exists()) {
  52. if(dir != null && !dir.exists()) {
  53. if (!dir.mkdirs()) {
  54. promise.reject("EUNSPECIFIED", "Failed to create parent directory of '" + path + "'");
  55. return;
  56. }
  57. }
  58. if(!f.createNewFile()) {
  59. promise.reject("ENOENT", "File '" + path + "' does not exist and could not be created");
  60. return;
  61. }
  62. }
  63. FileOutputStream fout = new FileOutputStream(f, append);
  64. // write data from a file
  65. if(encoding.equalsIgnoreCase(RNFetchBlobConst.DATA_ENCODE_URI)) {
  66. String normalizedData = normalizePath(data);
  67. File src = new File(normalizedData);
  68. if (!src.exists()) {
  69. promise.reject("ENOENT", "No such file '" + path + "' " + "('" + normalizedData + "')");
  70. fout.close();
  71. return;
  72. }
  73. FileInputStream fin = new FileInputStream(src);
  74. byte[] buffer = new byte [10240];
  75. int read;
  76. written = 0;
  77. while((read = fin.read(buffer)) > 0) {
  78. fout.write(buffer, 0, read);
  79. written += read;
  80. }
  81. fin.close();
  82. }
  83. else {
  84. byte[] bytes = stringToBytes(data, encoding);
  85. fout.write(bytes);
  86. written = bytes.length;
  87. }
  88. fout.close();
  89. promise.resolve(written);
  90. } catch (FileNotFoundException e) {
  91. // According to https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html
  92. promise.reject("ENOENT", "File '" + path + "' does not exist and could not be created, or it is a directory");
  93. } catch (Exception e) {
  94. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  95. }
  96. }
  97. /**
  98. * Write array of bytes into file
  99. * @param path Destination file path.
  100. * @param data Array passed from JS context.
  101. * @param promise RCT Promise
  102. */
  103. static void writeFile(String path, ReadableArray data, final boolean append, final Promise promise) {
  104. try {
  105. File f = new File(path);
  106. File dir = f.getParentFile();
  107. if(!f.exists()) {
  108. if(dir != null && !dir.exists()) {
  109. if (!dir.mkdirs()) {
  110. promise.reject("ENOTDIR", "Failed to create parent directory of '" + path + "'");
  111. return;
  112. }
  113. }
  114. if(!f.createNewFile()) {
  115. promise.reject("ENOENT", "File '" + path + "' does not exist and could not be created");
  116. return;
  117. }
  118. }
  119. FileOutputStream os = new FileOutputStream(f, append);
  120. byte[] bytes = new byte[data.size()];
  121. for(int i=0;i<data.size();i++) {
  122. bytes[i] = (byte) data.getInt(i);
  123. }
  124. os.write(bytes);
  125. os.close();
  126. promise.resolve(data.size());
  127. } catch (FileNotFoundException e) {
  128. // According to https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html
  129. promise.reject("ENOENT", "File '" + path + "' does not exist and could not be created");
  130. } catch (Exception e) {
  131. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  132. }
  133. }
  134. /**
  135. * Read file with a buffer that has the same size as the target file.
  136. * @param path Path of the file.
  137. * @param encoding Encoding of read stream.
  138. * @param promise JS promise
  139. */
  140. static void readFile(String path, String encoding, final Promise promise) {
  141. String resolved = normalizePath(path);
  142. if(resolved != null)
  143. path = resolved;
  144. try {
  145. byte[] bytes;
  146. int bytesRead;
  147. int length; // max. array length limited to "int", also see https://stackoverflow.com/a/10787175/544779
  148. if(resolved != null && resolved.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  149. String assetName = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  150. // This fails should an asset file be >2GB
  151. length = (int) RNFetchBlob.RCTContext.getAssets().openFd(assetName).getLength();
  152. bytes = new byte[length];
  153. InputStream in = RNFetchBlob.RCTContext.getAssets().open(assetName);
  154. bytesRead = in.read(bytes, 0, length);
  155. in.close();
  156. }
  157. // issue 287
  158. else if(resolved == null) {
  159. InputStream in = RNFetchBlob.RCTContext.getContentResolver().openInputStream(Uri.parse(path));
  160. // TODO See https://developer.android.com/reference/java/io/InputStream.html#available()
  161. // Quote: "Note that while some implementations of InputStream will return the total number of bytes
  162. // in the stream, many will not. It is never correct to use the return value of this method to
  163. // allocate a buffer intended to hold all data in this stream."
  164. length = in.available();
  165. bytes = new byte[length];
  166. bytesRead = in.read(bytes);
  167. in.close();
  168. }
  169. else {
  170. File f = new File(path);
  171. length = (int) f.length();
  172. bytes = new byte[length];
  173. FileInputStream in = new FileInputStream(f);
  174. bytesRead = in.read(bytes);
  175. in.close();
  176. }
  177. if (bytesRead < length) {
  178. promise.reject("EUNSPECIFIED", "Read only " + bytesRead + " bytes of " + length);
  179. return;
  180. }
  181. switch (encoding.toLowerCase()) {
  182. case "base64" :
  183. promise.resolve(Base64.encodeToString(bytes, Base64.NO_WRAP));
  184. break;
  185. case "ascii" :
  186. WritableArray asciiResult = Arguments.createArray();
  187. for (byte b : bytes) {
  188. asciiResult.pushInt((int) b);
  189. }
  190. promise.resolve(asciiResult);
  191. break;
  192. case "utf8" :
  193. promise.resolve(new String(bytes));
  194. break;
  195. default:
  196. promise.resolve(new String(bytes));
  197. break;
  198. }
  199. }
  200. catch(FileNotFoundException err) {
  201. String msg = err.getLocalizedMessage();
  202. if (msg.contains("EISDIR")) {
  203. promise.reject("EISDIR", "Expecting a file but '" + path + "' is a directory; " + msg);
  204. } else {
  205. promise.reject("ENOENT", "No such file '" + path + "'; " + msg);
  206. }
  207. }
  208. catch(Exception err) {
  209. promise.reject("EUNSPECIFIED", err.getLocalizedMessage());
  210. }
  211. }
  212. /**
  213. * Static method that returns system folders to JS context
  214. * @param ctx React Native application context
  215. */
  216. static Map<String, Object> getSystemfolders(ReactApplicationContext ctx) {
  217. Map<String, Object> res = new HashMap<>();
  218. res.put("DocumentDir", ctx.getFilesDir().getAbsolutePath());
  219. res.put("CacheDir", ctx.getCacheDir().getAbsolutePath());
  220. res.put("DCIMDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath());
  221. res.put("PictureDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
  222. res.put("MusicDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath());
  223. res.put("DownloadDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
  224. res.put("MovieDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath());
  225. res.put("RingtoneDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES).getAbsolutePath());
  226. String state;
  227. state = Environment.getExternalStorageState();
  228. if (state.equals(Environment.MEDIA_MOUNTED)) {
  229. res.put("SDCardDir", Environment.getExternalStorageDirectory().getAbsolutePath());
  230. File externalDirectory = ctx.getExternalFilesDir(null);
  231. if (externalDirectory != null) {
  232. res.put("SDCardApplicationDir", externalDirectory.getParentFile().getAbsolutePath());
  233. } else {
  234. res.put("SDCardApplicationDir", "");
  235. }
  236. }
  237. res.put("MainBundleDir", ctx.getApplicationInfo().dataDir);
  238. return res;
  239. }
  240. static public void getSDCardDir(Promise promise) {
  241. if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  242. promise.resolve(Environment.getExternalStorageDirectory().getAbsolutePath());
  243. } else {
  244. promise.reject("RNFetchBlob.getSDCardDir", "External storage not mounted");
  245. }
  246. }
  247. static public void getSDCardApplicationDir(ReactApplicationContext ctx, Promise promise) {
  248. if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  249. try {
  250. final String path = ctx.getExternalFilesDir(null).getParentFile().getAbsolutePath();
  251. promise.resolve(path);
  252. } catch (Exception e) {
  253. promise.reject("RNFetchBlob.getSDCardApplicationDir", e.getLocalizedMessage());
  254. }
  255. } else {
  256. promise.reject("RNFetchBlob.getSDCardApplicationDir", "External storage not mounted");
  257. }
  258. }
  259. /**
  260. * Static method that returns a temp file path
  261. * @param taskId An unique string for identify
  262. * @return String
  263. */
  264. static String getTmpPath(String taskId) {
  265. return RNFetchBlob.RCTContext.getFilesDir() + "/RNFetchBlobTmp_" + taskId;
  266. }
  267. /**
  268. * Create a file stream for read
  269. * @param path File stream target path
  270. * @param encoding File stream decoder, should be one of `base64`, `utf8`, `ascii`
  271. * @param bufferSize Buffer size of read stream, default to 4096 (4095 when encode is `base64`)
  272. */
  273. void readStream(String path, String encoding, int bufferSize, int tick, final String streamId) {
  274. String resolved = normalizePath(path);
  275. if(resolved != null)
  276. path = resolved;
  277. try {
  278. int chunkSize = encoding.equalsIgnoreCase("base64") ? 4095 : 4096;
  279. if(bufferSize > 0)
  280. chunkSize = bufferSize;
  281. InputStream fs;
  282. if(resolved != null && path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  283. fs = RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  284. }
  285. // fix issue 287
  286. else if(resolved == null) {
  287. fs = RNFetchBlob.RCTContext.getContentResolver().openInputStream(Uri.parse(path));
  288. }
  289. else {
  290. fs = new FileInputStream(new File(path));
  291. }
  292. byte[] buffer = new byte[chunkSize];
  293. int cursor = 0;
  294. boolean error = false;
  295. if (encoding.equalsIgnoreCase("utf8")) {
  296. CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
  297. while ((cursor = fs.read(buffer)) != -1) {
  298. encoder.encode(ByteBuffer.wrap(buffer).asCharBuffer());
  299. String chunk = new String(buffer, 0, cursor);
  300. emitStreamEvent(streamId, "data", chunk);
  301. if(tick > 0)
  302. SystemClock.sleep(tick);
  303. }
  304. } else if (encoding.equalsIgnoreCase("ascii")) {
  305. while ((cursor = fs.read(buffer)) != -1) {
  306. WritableArray chunk = Arguments.createArray();
  307. for(int i =0;i<cursor;i++)
  308. {
  309. chunk.pushInt((int)buffer[i]);
  310. }
  311. emitStreamEvent(streamId, "data", chunk);
  312. if(tick > 0)
  313. SystemClock.sleep(tick);
  314. }
  315. } else if (encoding.equalsIgnoreCase("base64")) {
  316. while ((cursor = fs.read(buffer)) != -1) {
  317. if(cursor < chunkSize) {
  318. byte[] copy = new byte[cursor];
  319. System.arraycopy(buffer, 0, copy, 0, cursor);
  320. emitStreamEvent(streamId, "data", Base64.encodeToString(copy, Base64.NO_WRAP));
  321. }
  322. else
  323. emitStreamEvent(streamId, "data", Base64.encodeToString(buffer, Base64.NO_WRAP));
  324. if(tick > 0)
  325. SystemClock.sleep(tick);
  326. }
  327. } else {
  328. emitStreamEvent(
  329. streamId,
  330. "error",
  331. "EINVAL",
  332. "Unrecognized encoding `" + encoding + "`, should be one of `base64`, `utf8`, `ascii`"
  333. );
  334. error = true;
  335. }
  336. if(!error)
  337. emitStreamEvent(streamId, "end", "");
  338. fs.close();
  339. buffer = null;
  340. } catch (FileNotFoundException err) {
  341. emitStreamEvent(
  342. streamId,
  343. "error",
  344. "ENOENT",
  345. "No such file '" + path + "'"
  346. );
  347. } catch (Exception err) {
  348. emitStreamEvent(
  349. streamId,
  350. "error",
  351. "EUNSPECIFIED",
  352. "Failed to convert data to " + encoding + " encoded string. This might be because this encoding cannot be used for this data."
  353. );
  354. err.printStackTrace();
  355. }
  356. }
  357. /**
  358. * Create a write stream and store its instance in RNFetchBlobFS.fileStreams
  359. * @param path Target file path
  360. * @param encoding Should be one of `base64`, `utf8`, `ascii`
  361. * @param append Flag represents if the file stream overwrite existing content
  362. * @param callback Callback
  363. */
  364. void writeStream(String path, String encoding, boolean append, Callback callback) {
  365. try {
  366. File dest = new File(path);
  367. File dir = dest.getParentFile();
  368. if(!dest.exists()) {
  369. if(dir != null && !dir.exists()) {
  370. if (!dir.mkdirs()) {
  371. callback.invoke("ENOTDIR", "Failed to create parent directory of '" + path + "'");
  372. return;
  373. }
  374. }
  375. if(!dest.createNewFile()) {
  376. callback.invoke("ENOENT", "File '" + path + "' does not exist and could not be created");
  377. return;
  378. }
  379. } else if(dest.isDirectory()) {
  380. callback.invoke("EISDIR", "Expecting a file but '" + path + "' is a directory");
  381. return;
  382. }
  383. OutputStream fs = new FileOutputStream(path, append);
  384. this.encoding = encoding;
  385. String streamId = UUID.randomUUID().toString();
  386. RNFetchBlobFS.fileStreams.put(streamId, this);
  387. this.writeStreamInstance = fs;
  388. callback.invoke(null, null, streamId);
  389. } catch(Exception err) {
  390. callback.invoke("EUNSPECIFIED", "Failed to create write stream at path `" + path + "`; " + err.getLocalizedMessage());
  391. }
  392. }
  393. /**
  394. * Write a chunk of data into a file stream.
  395. * @param streamId File stream ID
  396. * @param data Data chunk in string format
  397. * @param callback JS context callback
  398. */
  399. static void writeChunk(String streamId, String data, Callback callback) {
  400. RNFetchBlobFS fs = fileStreams.get(streamId);
  401. OutputStream stream = fs.writeStreamInstance;
  402. byte[] chunk = RNFetchBlobFS.stringToBytes(data, fs.encoding);
  403. try {
  404. stream.write(chunk);
  405. callback.invoke();
  406. } catch (Exception e) {
  407. callback.invoke(e.getLocalizedMessage());
  408. }
  409. }
  410. /**
  411. * Write data using ascii array
  412. * @param streamId File stream ID
  413. * @param data Data chunk in ascii array format
  414. * @param callback JS context callback
  415. */
  416. static void writeArrayChunk(String streamId, ReadableArray data, Callback callback) {
  417. try {
  418. RNFetchBlobFS fs = fileStreams.get(streamId);
  419. OutputStream stream = fs.writeStreamInstance;
  420. byte[] chunk = new byte[data.size()];
  421. for(int i =0; i< data.size();i++) {
  422. chunk[i] = (byte) data.getInt(i);
  423. }
  424. stream.write(chunk);
  425. callback.invoke();
  426. } catch (Exception e) {
  427. callback.invoke(e.getLocalizedMessage());
  428. }
  429. }
  430. /**
  431. * Close file write stream by ID
  432. * @param streamId Stream ID
  433. * @param callback JS context callback
  434. */
  435. static void closeStream(String streamId, Callback callback) {
  436. try {
  437. RNFetchBlobFS fs = fileStreams.get(streamId);
  438. OutputStream stream = fs.writeStreamInstance;
  439. fileStreams.remove(streamId);
  440. stream.close();
  441. callback.invoke();
  442. } catch(Exception err) {
  443. callback.invoke(err.getLocalizedMessage());
  444. }
  445. }
  446. /**
  447. * Unlink file at path
  448. * @param path Path of target
  449. * @param callback JS context callback
  450. */
  451. static void unlink(String path, Callback callback) {
  452. try {
  453. RNFetchBlobFS.deleteRecursive(new File(path));
  454. callback.invoke(null, true);
  455. } catch(Exception err) {
  456. callback.invoke(err.getLocalizedMessage(), false);
  457. }
  458. }
  459. private static void deleteRecursive(File fileOrDirectory) throws IOException {
  460. if (fileOrDirectory.isDirectory()) {
  461. File[] files = fileOrDirectory.listFiles();
  462. if (files == null) {
  463. throw new NullPointerException("Received null trying to list files of directory '" + fileOrDirectory + "'");
  464. } else {
  465. for (File child : files) {
  466. deleteRecursive(child);
  467. }
  468. }
  469. }
  470. boolean result = fileOrDirectory.delete();
  471. if (!result) {
  472. throw new IOException("Failed to delete '" + fileOrDirectory + "'");
  473. }
  474. }
  475. /**
  476. * Make a folder
  477. * @param path Source path
  478. * @param promise JS promise
  479. */
  480. static void mkdir(String path, Promise promise) {
  481. File dest = new File(path);
  482. if(dest.exists()) {
  483. promise.reject("EEXIST", dest.isDirectory() ? "Folder" : "File" + " '" + path + "' already exists");
  484. return;
  485. }
  486. try {
  487. boolean result = dest.mkdirs();
  488. if (!result) {
  489. promise.reject("EUNSPECIFIED", "mkdir failed to create some or all directories in '" + path + "'");
  490. return;
  491. }
  492. } catch (Exception e) {
  493. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  494. return;
  495. }
  496. promise.resolve(true);
  497. }
  498. /**
  499. * Copy file to destination path
  500. * @param path Source path
  501. * @param dest Target path
  502. * @param callback JS context callback
  503. */
  504. static void cp(String path, String dest, Callback callback) {
  505. path = normalizePath(path);
  506. InputStream in = null;
  507. OutputStream out = null;
  508. try {
  509. if(!isPathExists(path)) {
  510. callback.invoke("Source file at path`" + path + "` does not exist");
  511. return;
  512. }
  513. if(!new File(dest).exists()) {
  514. boolean result = new File(dest).createNewFile();
  515. if (!result) {
  516. callback.invoke("Destination file at '" + dest + "' already exists");
  517. return;
  518. }
  519. }
  520. in = inputStreamFromPath(path);
  521. out = new FileOutputStream(dest);
  522. byte[] buf = new byte[10240];
  523. int len;
  524. while ((len = in.read(buf)) > 0) {
  525. out.write(buf, 0, len);
  526. }
  527. } catch (Exception err) {
  528. callback.invoke(err.getLocalizedMessage());
  529. } finally {
  530. try {
  531. if (in != null) {
  532. in.close();
  533. }
  534. if (out != null) {
  535. out.close();
  536. }
  537. callback.invoke();
  538. } catch (Exception e) {
  539. callback.invoke(e.getLocalizedMessage());
  540. }
  541. }
  542. }
  543. /**
  544. * Move file
  545. * @param path Source file path
  546. * @param dest Destination file path
  547. * @param callback JS context callback
  548. */
  549. static void mv(String path, String dest, Callback callback) {
  550. File src = new File(path);
  551. if(!src.exists()) {
  552. callback.invoke("Source file at path `" + path + "` does not exist");
  553. return;
  554. }
  555. //Check if the output file directory exists.
  556. File dir = new File(dest);
  557. if (!dir.exists())
  558. {
  559. dir.mkdirs();
  560. }
  561. try {
  562. InputStream in = new FileInputStream(path);
  563. OutputStream out = new FileOutputStream(dest);
  564. //read source path to byte buffer. Write from input to output stream
  565. byte[] buffer = new byte[1024];
  566. int read;
  567. while ((read = in.read(buffer)) != -1) { //read is successful
  568. out.write(buffer, 0, read);
  569. }
  570. in.close();
  571. out.flush();
  572. src.delete(); //remove original file
  573. } catch (FileNotFoundException exception) {
  574. callback.invoke(exception.toString());
  575. return;
  576. } catch (Exception e) {
  577. callback.invoke(e.toString());
  578. return;
  579. }
  580. callback.invoke();
  581. }
  582. /**
  583. * Check if the path exists, also check if it is a folder when exists.
  584. * @param path Path to check
  585. * @param callback JS context callback
  586. */
  587. static void exists(String path, Callback callback) {
  588. if(isAsset(path)) {
  589. try {
  590. String filename = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  591. com.RNFetchBlob.RNFetchBlob.RCTContext.getAssets().openFd(filename);
  592. callback.invoke(true, false);
  593. } catch (IOException e) {
  594. callback.invoke(false, false);
  595. }
  596. }
  597. else {
  598. path = normalizePath(path);
  599. boolean exist = new File(path).exists();
  600. boolean isDir = new File(path).isDirectory();
  601. callback.invoke(exist, isDir);
  602. }
  603. }
  604. /**
  605. * List content of folder
  606. * @param path Target folder
  607. * @param callback JS context callback
  608. */
  609. static void ls(String path, Promise promise) {
  610. try {
  611. path = normalizePath(path);
  612. File src = new File(path);
  613. if (!src.exists()) {
  614. promise.reject("ENOENT", "No such file '" + path + "'");
  615. return;
  616. }
  617. if (!src.isDirectory()) {
  618. promise.reject("ENOTDIR", "Not a directory '" + path + "'");
  619. return;
  620. }
  621. String[] files = new File(path).list();
  622. WritableArray arg = Arguments.createArray();
  623. // File => list(): "If this abstract pathname does not denote a directory, then this method returns null."
  624. // We excluded that possibility above - ignore the "can produce NullPointerException" warning of the IDE.
  625. for (String i : files) {
  626. arg.pushString(i);
  627. }
  628. promise.resolve(arg);
  629. } catch (Exception e) {
  630. e.printStackTrace();
  631. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  632. }
  633. }
  634. /**
  635. * Create a file by slicing given file path
  636. * @param path Source file path
  637. * @param dest Destination of created file
  638. * @param start Start byte offset in source file
  639. * @param end End byte offset
  640. * @param encode NOT IMPLEMENTED
  641. */
  642. static void slice(String path, String dest, int start, int end, String encode, Promise promise) {
  643. try {
  644. path = normalizePath(path);
  645. File source = new File(path);
  646. if(source.isDirectory()){
  647. promise.reject("EISDIR", "Expecting a file but '" + path + "' is a directory");
  648. return;
  649. }
  650. if(!source.exists()){
  651. promise.reject("ENOENT", "No such file '" + path + "'");
  652. return;
  653. }
  654. int size = (int) source.length();
  655. int max = Math.min(size, end);
  656. int expected = max - start;
  657. int now = 0;
  658. FileInputStream in = new FileInputStream(new File(path));
  659. FileOutputStream out = new FileOutputStream(new File(dest));
  660. int skipped = (int) in.skip(start);
  661. if (skipped != start) {
  662. promise.reject("EUNSPECIFIED", "Skipped " + skipped + " instead of the specified " + start + " bytes, size is " + size);
  663. return;
  664. }
  665. byte[] buffer = new byte[10240];
  666. while(now < expected) {
  667. int read = in.read(buffer, 0, 10240);
  668. int remain = expected - now;
  669. if(read <= 0) {
  670. break;
  671. }
  672. out.write(buffer, 0, (int) Math.min(remain, read));
  673. now += read;
  674. }
  675. in.close();
  676. out.flush();
  677. out.close();
  678. promise.resolve(dest);
  679. } catch (Exception e) {
  680. e.printStackTrace();
  681. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  682. }
  683. }
  684. static void lstat(String path, final Callback callback) {
  685. path = normalizePath(path);
  686. new AsyncTask<String, Integer, Integer>() {
  687. @Override
  688. protected Integer doInBackground(String ...args) {
  689. WritableArray res = Arguments.createArray();
  690. if(args[0] == null) {
  691. callback.invoke("the path specified for lstat is either `null` or `undefined`.");
  692. return 0;
  693. }
  694. File src = new File(args[0]);
  695. if(!src.exists()) {
  696. callback.invoke("failed to lstat path `" + args[0] + "` because it does not exist or it is not a folder");
  697. return 0;
  698. }
  699. if(src.isDirectory()) {
  700. String [] files = src.list();
  701. // File => list(): "If this abstract pathname does not denote a directory, then this method returns null."
  702. // We excluded that possibility above - ignore the "can produce NullPointerException" warning of the IDE.
  703. for(String p : files) {
  704. res.pushMap(statFile(src.getPath() + "/" + p));
  705. }
  706. }
  707. else {
  708. res.pushMap(statFile(src.getAbsolutePath()));
  709. }
  710. callback.invoke(null, res);
  711. return 0;
  712. }
  713. }.execute(path);
  714. }
  715. /**
  716. * show status of a file or directory
  717. * @param path Path
  718. * @param callback Callback
  719. */
  720. static void stat(String path, Callback callback) {
  721. try {
  722. path = normalizePath(path);
  723. WritableMap result = statFile(path);
  724. if(result == null)
  725. callback.invoke("failed to stat path `" + path + "` because it does not exist or it is not a folder", null);
  726. else
  727. callback.invoke(null, result);
  728. } catch(Exception err) {
  729. callback.invoke(err.getLocalizedMessage());
  730. }
  731. }
  732. /**
  733. * Basic stat method
  734. * @param path Path
  735. * @return Stat Result of a file or path
  736. */
  737. static WritableMap statFile(String path) {
  738. try {
  739. path = normalizePath(path);
  740. WritableMap stat = Arguments.createMap();
  741. if(isAsset(path)) {
  742. String name = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  743. AssetFileDescriptor fd = RNFetchBlob.RCTContext.getAssets().openFd(name);
  744. stat.putString("filename", name);
  745. stat.putString("path", path);
  746. stat.putString("type", "asset");
  747. stat.putString("size", String.valueOf(fd.getLength()));
  748. stat.putInt("lastModified", 0);
  749. }
  750. else {
  751. File target = new File(path);
  752. if (!target.exists()) {
  753. return null;
  754. }
  755. stat.putString("filename", target.getName());
  756. stat.putString("path", target.getPath());
  757. stat.putString("type", target.isDirectory() ? "directory" : "file");
  758. stat.putString("size", String.valueOf(target.length()));
  759. String lastModified = String.valueOf(target.lastModified());
  760. stat.putString("lastModified", lastModified);
  761. }
  762. return stat;
  763. } catch(Exception err) {
  764. return null;
  765. }
  766. }
  767. /**
  768. * Media scanner scan file
  769. * @param path Path to file
  770. * @param mimes Array of MIME type strings
  771. * @param callback Callback for results
  772. */
  773. void scanFile(String [] path, String[] mimes, final Callback callback) {
  774. try {
  775. MediaScannerConnection.scanFile(mCtx, path, mimes, new MediaScannerConnection.OnScanCompletedListener() {
  776. @Override
  777. public void onScanCompleted(String s, Uri uri) {
  778. callback.invoke(null, true);
  779. }
  780. });
  781. } catch(Exception err) {
  782. callback.invoke(err.getLocalizedMessage(), null);
  783. }
  784. }
  785. static void hash(String path, String algorithm, Promise promise) {
  786. try {
  787. Map<String, String> algorithms = new HashMap<>();
  788. algorithms.put("md5", "MD5");
  789. algorithms.put("sha1", "SHA-1");
  790. algorithms.put("sha224", "SHA-224");
  791. algorithms.put("sha256", "SHA-256");
  792. algorithms.put("sha384", "SHA-384");
  793. algorithms.put("sha512", "SHA-512");
  794. if (!algorithms.containsKey(algorithm)) {
  795. promise.reject("EINVAL", "Invalid algorithm '" + algorithm + "', must be one of md5, sha1, sha224, sha256, sha384, sha512");
  796. return;
  797. }
  798. File file = new File(path);
  799. if (file.isDirectory()) {
  800. promise.reject("EISDIR", "Expecting a file but '" + path + "' is a directory");
  801. return;
  802. }
  803. if (!file.exists()) {
  804. promise.reject("ENOENT", "No such file '" + path + "'");
  805. return;
  806. }
  807. MessageDigest md = MessageDigest.getInstance(algorithms.get(algorithm));
  808. FileInputStream inputStream = new FileInputStream(path);
  809. byte[] buffer = new byte[(int)file.length()];
  810. int read;
  811. while ((read = inputStream.read(buffer)) != -1) {
  812. md.update(buffer, 0, read);
  813. }
  814. StringBuilder hexString = new StringBuilder();
  815. for (byte digestByte : md.digest())
  816. hexString.append(String.format("%02x", digestByte));
  817. promise.resolve(hexString.toString());
  818. } catch (Exception e) {
  819. e.printStackTrace();
  820. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  821. }
  822. }
  823. /**
  824. * Create new file at path
  825. * @param path The destination path of the new file.
  826. * @param data Initial data of the new file.
  827. * @param encoding Encoding of initial data.
  828. * @param promise Promise for Javascript
  829. */
  830. static void createFile(String path, String data, String encoding, Promise promise) {
  831. try {
  832. File dest = new File(path);
  833. boolean created = dest.createNewFile();
  834. if(encoding.equals(RNFetchBlobConst.DATA_ENCODE_URI)) {
  835. String orgPath = data.replace(RNFetchBlobConst.FILE_PREFIX, "");
  836. File src = new File(orgPath);
  837. if(!src.exists()) {
  838. promise.reject("ENOENT", "Source file : " + data + " does not exist");
  839. return ;
  840. }
  841. FileInputStream fin = new FileInputStream(src);
  842. OutputStream ostream = new FileOutputStream(dest);
  843. byte[] buffer = new byte[10240];
  844. int read = fin.read(buffer);
  845. while (read > 0) {
  846. ostream.write(buffer, 0, read);
  847. read = fin.read(buffer);
  848. }
  849. fin.close();
  850. ostream.close();
  851. } else {
  852. if (!created) {
  853. promise.reject("EEXIST", "File `" + path + "` already exists");
  854. return;
  855. }
  856. OutputStream ostream = new FileOutputStream(dest);
  857. ostream.write(RNFetchBlobFS.stringToBytes(data, encoding));
  858. }
  859. promise.resolve(path);
  860. } catch(Exception err) {
  861. promise.reject("EUNSPECIFIED", err.getLocalizedMessage());
  862. }
  863. }
  864. /**
  865. * Create file for ASCII encoding
  866. * @param path Path of new file.
  867. * @param data Content of new file
  868. * @param promise JS Promise
  869. */
  870. static void createFileASCII(String path, ReadableArray data, Promise promise) {
  871. try {
  872. File dest = new File(path);
  873. boolean created = dest.createNewFile();
  874. if(!created) {
  875. promise.reject("EEXIST", "File at path `" + path + "` already exists");
  876. return;
  877. }
  878. OutputStream ostream = new FileOutputStream(dest);
  879. byte[] chunk = new byte[data.size()];
  880. for(int i=0; i<data.size(); i++) {
  881. chunk[i] = (byte) data.getInt(i);
  882. }
  883. ostream.write(chunk);
  884. promise.resolve(path);
  885. } catch(Exception err) {
  886. promise.reject("EUNSPECIFIED", err.getLocalizedMessage());
  887. }
  888. }
  889. static void df(Callback callback) {
  890. StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
  891. WritableMap args = Arguments.createMap();
  892. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  893. args.putString("internal_free", String.valueOf(stat.getFreeBytes()));
  894. args.putString("internal_total", String.valueOf(stat.getTotalBytes()));
  895. StatFs statEx = new StatFs(Environment.getExternalStorageDirectory().getPath());
  896. args.putString("external_free", String.valueOf(statEx.getFreeBytes()));
  897. args.putString("external_total", String.valueOf(statEx.getTotalBytes()));
  898. }
  899. callback.invoke(null ,args);
  900. }
  901. /**
  902. * Remove files in session.
  903. * @param paths An array of file paths.
  904. * @param callback JS contest callback
  905. */
  906. static void removeSession(ReadableArray paths, final Callback callback) {
  907. AsyncTask<ReadableArray, Integer, Integer> task = new AsyncTask<ReadableArray, Integer, Integer>() {
  908. @Override
  909. protected Integer doInBackground(ReadableArray ...paths) {
  910. try {
  911. ArrayList<String> failuresToDelete = new ArrayList<>();
  912. for (int i = 0; i < paths[0].size(); i++) {
  913. String fileName = paths[0].getString(i);
  914. File f = new File(fileName);
  915. if (f.exists()) {
  916. boolean result = f.delete();
  917. if (!result) {
  918. failuresToDelete.add(fileName);
  919. }
  920. }
  921. }
  922. if (failuresToDelete.isEmpty()) {
  923. callback.invoke(null, true);
  924. } else {
  925. StringBuilder listString = new StringBuilder();
  926. listString.append("Failed to delete: ");
  927. for (String s : failuresToDelete) {
  928. listString.append(s).append(", ");
  929. }
  930. callback.invoke(listString.toString());
  931. }
  932. } catch(Exception err) {
  933. callback.invoke(err.getLocalizedMessage());
  934. }
  935. return paths[0].size();
  936. }
  937. };
  938. task.execute(paths);
  939. }
  940. /**
  941. * String to byte converter method
  942. * @param data Raw data in string format
  943. * @param encoding Decoder name
  944. * @return Converted data byte array
  945. */
  946. private static byte[] stringToBytes(String data, String encoding) {
  947. if(encoding.equalsIgnoreCase("ascii")) {
  948. return data.getBytes(Charset.forName("US-ASCII"));
  949. }
  950. else if(encoding.toLowerCase().contains("base64")) {
  951. return Base64.decode(data, Base64.NO_WRAP);
  952. }
  953. else if(encoding.equalsIgnoreCase("utf8")) {
  954. return data.getBytes(Charset.forName("UTF-8"));
  955. }
  956. return data.getBytes(Charset.forName("US-ASCII"));
  957. }
  958. /**
  959. * Private method for emit read stream event.
  960. * @param streamName ID of the read stream
  961. * @param event Event name, `data`, `end`, `error`, etc.
  962. * @param data Event data
  963. */
  964. private void emitStreamEvent(String streamName, String event, String data) {
  965. WritableMap eventData = Arguments.createMap();
  966. eventData.putString("event", event);
  967. eventData.putString("detail", data);
  968. this.emitter.emit(streamName, eventData);
  969. }
  970. // "event" always is "data"...
  971. private void emitStreamEvent(String streamName, String event, WritableArray data) {
  972. WritableMap eventData = Arguments.createMap();
  973. eventData.putString("event", event);
  974. eventData.putArray("detail", data);
  975. this.emitter.emit(streamName, eventData);
  976. }
  977. // "event" always is "error"...
  978. private void emitStreamEvent(String streamName, String event, String code, String message) {
  979. WritableMap eventData = Arguments.createMap();
  980. eventData.putString("event", event);
  981. eventData.putString("code", code);
  982. eventData.putString("detail", message);
  983. this.emitter.emit(streamName, eventData);
  984. }
  985. /**
  986. * Get input stream of the given path, when the path is a string starts with bundle-assets://
  987. * the stream is created by Assets Manager, otherwise use FileInputStream.
  988. * @param path The file to open stream
  989. * @return InputStream instance
  990. * @throws IOException If the given file does not exist or is a directory FileInputStream will throw a FileNotFoundException
  991. */
  992. private static InputStream inputStreamFromPath(String path) throws IOException {
  993. if (path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  994. return RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  995. }
  996. return new FileInputStream(new File(path));
  997. }
  998. /**
  999. * Check if the asset or the file exists
  1000. * @param path A file path URI string
  1001. * @return A boolean value represents if the path exists.
  1002. */
  1003. private static boolean isPathExists(String path) {
  1004. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  1005. try {
  1006. RNFetchBlob.RCTContext.getAssets().open(path.replace(com.RNFetchBlob.RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  1007. } catch (IOException e) {
  1008. return false;
  1009. }
  1010. return true;
  1011. }
  1012. else {
  1013. return new File(path).exists();
  1014. }
  1015. }
  1016. static boolean isAsset(String path) {
  1017. return path != null && path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET);
  1018. }
  1019. /**
  1020. * Normalize the path, remove URI scheme (xxx://) so that we can handle it.
  1021. * @param path URI string.
  1022. * @return Normalized string
  1023. */
  1024. static String normalizePath(String path) {
  1025. if(path == null)
  1026. return null;
  1027. if(!path.matches("\\w+\\:.*"))
  1028. return path;
  1029. if(path.startsWith("file://")) {
  1030. return path.replace("file://", "");
  1031. }
  1032. Uri uri = Uri.parse(path);
  1033. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  1034. return path;
  1035. }
  1036. else
  1037. return PathResolver.getRealPathFromURI(RNFetchBlob.RCTContext, uri);
  1038. }
  1039. }