No Description

RNFetchBlobFS.java 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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. try {
  556. InputStream in = new FileInputStream(path);
  557. OutputStream out = new FileOutputStream(dest);
  558. //read source path to byte buffer. Write from input to output stream
  559. byte[] buffer = new byte[1024];
  560. int read;
  561. while ((read = in.read(buffer)) != -1) { //read is successful
  562. out.write(buffer, 0, read);
  563. }
  564. in.close();
  565. out.flush();
  566. src.delete(); //remove original file
  567. } catch (FileNotFoundException exception) {
  568. callback.invoke("Source file not found.");
  569. return;
  570. } catch (Exception e) {
  571. callback.invoke(e.toString());
  572. return;
  573. }
  574. callback.invoke();
  575. }
  576. /**
  577. * Check if the path exists, also check if it is a folder when exists.
  578. * @param path Path to check
  579. * @param callback JS context callback
  580. */
  581. static void exists(String path, Callback callback) {
  582. if(isAsset(path)) {
  583. try {
  584. String filename = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  585. com.RNFetchBlob.RNFetchBlob.RCTContext.getAssets().openFd(filename);
  586. callback.invoke(true, false);
  587. } catch (IOException e) {
  588. callback.invoke(false, false);
  589. }
  590. }
  591. else {
  592. path = normalizePath(path);
  593. boolean exist = new File(path).exists();
  594. boolean isDir = new File(path).isDirectory();
  595. callback.invoke(exist, isDir);
  596. }
  597. }
  598. /**
  599. * List content of folder
  600. * @param path Target folder
  601. * @param callback JS context callback
  602. */
  603. static void ls(String path, Promise promise) {
  604. try {
  605. path = normalizePath(path);
  606. File src = new File(path);
  607. if (!src.exists()) {
  608. promise.reject("ENOENT", "No such file '" + path + "'");
  609. return;
  610. }
  611. if (!src.isDirectory()) {
  612. promise.reject("ENOTDIR", "Not a directory '" + path + "'");
  613. return;
  614. }
  615. String[] files = new File(path).list();
  616. WritableArray arg = Arguments.createArray();
  617. // File => list(): "If this abstract pathname does not denote a directory, then this method returns null."
  618. // We excluded that possibility above - ignore the "can produce NullPointerException" warning of the IDE.
  619. for (String i : files) {
  620. arg.pushString(i);
  621. }
  622. promise.resolve(arg);
  623. } catch (Exception e) {
  624. e.printStackTrace();
  625. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  626. }
  627. }
  628. /**
  629. * Create a file by slicing given file path
  630. * @param path Source file path
  631. * @param dest Destination of created file
  632. * @param start Start byte offset in source file
  633. * @param end End byte offset
  634. * @param encode NOT IMPLEMENTED
  635. */
  636. static void slice(String path, String dest, int start, int end, String encode, Promise promise) {
  637. try {
  638. path = normalizePath(path);
  639. File source = new File(path);
  640. if(source.isDirectory()){
  641. promise.reject("EISDIR", "Expecting a file but '" + path + "' is a directory");
  642. return;
  643. }
  644. if(!source.exists()){
  645. promise.reject("ENOENT", "No such file '" + path + "'");
  646. return;
  647. }
  648. int size = (int) source.length();
  649. int max = Math.min(size, end);
  650. int expected = max - start;
  651. int now = 0;
  652. FileInputStream in = new FileInputStream(new File(path));
  653. FileOutputStream out = new FileOutputStream(new File(dest));
  654. int skipped = (int) in.skip(start);
  655. if (skipped != start) {
  656. promise.reject("EUNSPECIFIED", "Skipped " + skipped + " instead of the specified " + start + " bytes, size is " + size);
  657. return;
  658. }
  659. byte[] buffer = new byte[10240];
  660. while(now < expected) {
  661. int read = in.read(buffer, 0, 10240);
  662. int remain = expected - now;
  663. if(read <= 0) {
  664. break;
  665. }
  666. out.write(buffer, 0, (int) Math.min(remain, read));
  667. now += read;
  668. }
  669. in.close();
  670. out.flush();
  671. out.close();
  672. promise.resolve(dest);
  673. } catch (Exception e) {
  674. e.printStackTrace();
  675. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  676. }
  677. }
  678. static void lstat(String path, final Callback callback) {
  679. path = normalizePath(path);
  680. new AsyncTask<String, Integer, Integer>() {
  681. @Override
  682. protected Integer doInBackground(String ...args) {
  683. WritableArray res = Arguments.createArray();
  684. if(args[0] == null) {
  685. callback.invoke("the path specified for lstat is either `null` or `undefined`.");
  686. return 0;
  687. }
  688. File src = new File(args[0]);
  689. if(!src.exists()) {
  690. callback.invoke("failed to lstat path `" + args[0] + "` because it does not exist or it is not a folder");
  691. return 0;
  692. }
  693. if(src.isDirectory()) {
  694. String [] files = src.list();
  695. // File => list(): "If this abstract pathname does not denote a directory, then this method returns null."
  696. // We excluded that possibility above - ignore the "can produce NullPointerException" warning of the IDE.
  697. for(String p : files) {
  698. res.pushMap(statFile(src.getPath() + "/" + p));
  699. }
  700. }
  701. else {
  702. res.pushMap(statFile(src.getAbsolutePath()));
  703. }
  704. callback.invoke(null, res);
  705. return 0;
  706. }
  707. }.execute(path);
  708. }
  709. /**
  710. * show status of a file or directory
  711. * @param path Path
  712. * @param callback Callback
  713. */
  714. static void stat(String path, Callback callback) {
  715. try {
  716. path = normalizePath(path);
  717. WritableMap result = statFile(path);
  718. if(result == null)
  719. callback.invoke("failed to stat path `" + path + "` because it does not exist or it is not a folder", null);
  720. else
  721. callback.invoke(null, result);
  722. } catch(Exception err) {
  723. callback.invoke(err.getLocalizedMessage());
  724. }
  725. }
  726. /**
  727. * Basic stat method
  728. * @param path Path
  729. * @return Stat Result of a file or path
  730. */
  731. static WritableMap statFile(String path) {
  732. try {
  733. path = normalizePath(path);
  734. WritableMap stat = Arguments.createMap();
  735. if(isAsset(path)) {
  736. String name = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  737. AssetFileDescriptor fd = RNFetchBlob.RCTContext.getAssets().openFd(name);
  738. stat.putString("filename", name);
  739. stat.putString("path", path);
  740. stat.putString("type", "asset");
  741. stat.putString("size", String.valueOf(fd.getLength()));
  742. stat.putInt("lastModified", 0);
  743. }
  744. else {
  745. File target = new File(path);
  746. if (!target.exists()) {
  747. return null;
  748. }
  749. stat.putString("filename", target.getName());
  750. stat.putString("path", target.getPath());
  751. stat.putString("type", target.isDirectory() ? "directory" : "file");
  752. stat.putString("size", String.valueOf(target.length()));
  753. String lastModified = String.valueOf(target.lastModified());
  754. stat.putString("lastModified", lastModified);
  755. }
  756. return stat;
  757. } catch(Exception err) {
  758. return null;
  759. }
  760. }
  761. /**
  762. * Media scanner scan file
  763. * @param path Path to file
  764. * @param mimes Array of MIME type strings
  765. * @param callback Callback for results
  766. */
  767. void scanFile(String [] path, String[] mimes, final Callback callback) {
  768. try {
  769. MediaScannerConnection.scanFile(mCtx, path, mimes, new MediaScannerConnection.OnScanCompletedListener() {
  770. @Override
  771. public void onScanCompleted(String s, Uri uri) {
  772. callback.invoke(null, true);
  773. }
  774. });
  775. } catch(Exception err) {
  776. callback.invoke(err.getLocalizedMessage(), null);
  777. }
  778. }
  779. static void hash(String path, String algorithm, Promise promise) {
  780. try {
  781. Map<String, String> algorithms = new HashMap<>();
  782. algorithms.put("md5", "MD5");
  783. algorithms.put("sha1", "SHA-1");
  784. algorithms.put("sha224", "SHA-224");
  785. algorithms.put("sha256", "SHA-256");
  786. algorithms.put("sha384", "SHA-384");
  787. algorithms.put("sha512", "SHA-512");
  788. if (!algorithms.containsKey(algorithm)) {
  789. promise.reject("EINVAL", "Invalid algorithm '" + algorithm + "', must be one of md5, sha1, sha224, sha256, sha384, sha512");
  790. return;
  791. }
  792. File file = new File(path);
  793. if (file.isDirectory()) {
  794. promise.reject("EISDIR", "Expecting a file but '" + path + "' is a directory");
  795. return;
  796. }
  797. if (!file.exists()) {
  798. promise.reject("ENOENT", "No such file '" + path + "'");
  799. return;
  800. }
  801. MessageDigest md = MessageDigest.getInstance(algorithms.get(algorithm));
  802. FileInputStream inputStream = new FileInputStream(path);
  803. byte[] buffer = new byte[(int)file.length()];
  804. int read;
  805. while ((read = inputStream.read(buffer)) != -1) {
  806. md.update(buffer, 0, read);
  807. }
  808. StringBuilder hexString = new StringBuilder();
  809. for (byte digestByte : md.digest())
  810. hexString.append(String.format("%02x", digestByte));
  811. promise.resolve(hexString.toString());
  812. } catch (Exception e) {
  813. e.printStackTrace();
  814. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  815. }
  816. }
  817. /**
  818. * Create new file at path
  819. * @param path The destination path of the new file.
  820. * @param data Initial data of the new file.
  821. * @param encoding Encoding of initial data.
  822. * @param promise Promise for Javascript
  823. */
  824. static void createFile(String path, String data, String encoding, Promise promise) {
  825. try {
  826. File dest = new File(path);
  827. boolean created = dest.createNewFile();
  828. if(encoding.equals(RNFetchBlobConst.DATA_ENCODE_URI)) {
  829. String orgPath = data.replace(RNFetchBlobConst.FILE_PREFIX, "");
  830. File src = new File(orgPath);
  831. if(!src.exists()) {
  832. promise.reject("ENOENT", "Source file : " + data + " does not exist");
  833. return ;
  834. }
  835. FileInputStream fin = new FileInputStream(src);
  836. OutputStream ostream = new FileOutputStream(dest);
  837. byte[] buffer = new byte[10240];
  838. int read = fin.read(buffer);
  839. while (read > 0) {
  840. ostream.write(buffer, 0, read);
  841. read = fin.read(buffer);
  842. }
  843. fin.close();
  844. ostream.close();
  845. } else {
  846. if (!created) {
  847. promise.reject("EEXIST", "File `" + path + "` already exists");
  848. return;
  849. }
  850. OutputStream ostream = new FileOutputStream(dest);
  851. ostream.write(RNFetchBlobFS.stringToBytes(data, encoding));
  852. }
  853. promise.resolve(path);
  854. } catch(Exception err) {
  855. promise.reject("EUNSPECIFIED", err.getLocalizedMessage());
  856. }
  857. }
  858. /**
  859. * Create file for ASCII encoding
  860. * @param path Path of new file.
  861. * @param data Content of new file
  862. * @param promise JS Promise
  863. */
  864. static void createFileASCII(String path, ReadableArray data, Promise promise) {
  865. try {
  866. File dest = new File(path);
  867. boolean created = dest.createNewFile();
  868. if(!created) {
  869. promise.reject("EEXIST", "File at path `" + path + "` already exists");
  870. return;
  871. }
  872. OutputStream ostream = new FileOutputStream(dest);
  873. byte[] chunk = new byte[data.size()];
  874. for(int i=0; i<data.size(); i++) {
  875. chunk[i] = (byte) data.getInt(i);
  876. }
  877. ostream.write(chunk);
  878. promise.resolve(path);
  879. } catch(Exception err) {
  880. promise.reject("EUNSPECIFIED", err.getLocalizedMessage());
  881. }
  882. }
  883. static void df(Callback callback) {
  884. StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
  885. WritableMap args = Arguments.createMap();
  886. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  887. args.putString("internal_free", String.valueOf(stat.getFreeBytes()));
  888. args.putString("internal_total", String.valueOf(stat.getTotalBytes()));
  889. StatFs statEx = new StatFs(Environment.getExternalStorageDirectory().getPath());
  890. args.putString("external_free", String.valueOf(statEx.getFreeBytes()));
  891. args.putString("external_total", String.valueOf(statEx.getTotalBytes()));
  892. }
  893. callback.invoke(null ,args);
  894. }
  895. /**
  896. * Remove files in session.
  897. * @param paths An array of file paths.
  898. * @param callback JS contest callback
  899. */
  900. static void removeSession(ReadableArray paths, final Callback callback) {
  901. AsyncTask<ReadableArray, Integer, Integer> task = new AsyncTask<ReadableArray, Integer, Integer>() {
  902. @Override
  903. protected Integer doInBackground(ReadableArray ...paths) {
  904. try {
  905. ArrayList<String> failuresToDelete = new ArrayList<>();
  906. for (int i = 0; i < paths[0].size(); i++) {
  907. String fileName = paths[0].getString(i);
  908. File f = new File(fileName);
  909. if (f.exists()) {
  910. boolean result = f.delete();
  911. if (!result) {
  912. failuresToDelete.add(fileName);
  913. }
  914. }
  915. }
  916. if (failuresToDelete.isEmpty()) {
  917. callback.invoke(null, true);
  918. } else {
  919. StringBuilder listString = new StringBuilder();
  920. listString.append("Failed to delete: ");
  921. for (String s : failuresToDelete) {
  922. listString.append(s).append(", ");
  923. }
  924. callback.invoke(listString.toString());
  925. }
  926. } catch(Exception err) {
  927. callback.invoke(err.getLocalizedMessage());
  928. }
  929. return paths[0].size();
  930. }
  931. };
  932. task.execute(paths);
  933. }
  934. /**
  935. * String to byte converter method
  936. * @param data Raw data in string format
  937. * @param encoding Decoder name
  938. * @return Converted data byte array
  939. */
  940. private static byte[] stringToBytes(String data, String encoding) {
  941. if(encoding.equalsIgnoreCase("ascii")) {
  942. return data.getBytes(Charset.forName("US-ASCII"));
  943. }
  944. else if(encoding.toLowerCase().contains("base64")) {
  945. return Base64.decode(data, Base64.NO_WRAP);
  946. }
  947. else if(encoding.equalsIgnoreCase("utf8")) {
  948. return data.getBytes(Charset.forName("UTF-8"));
  949. }
  950. return data.getBytes(Charset.forName("US-ASCII"));
  951. }
  952. /**
  953. * Private method for emit read stream event.
  954. * @param streamName ID of the read stream
  955. * @param event Event name, `data`, `end`, `error`, etc.
  956. * @param data Event data
  957. */
  958. private void emitStreamEvent(String streamName, String event, String data) {
  959. WritableMap eventData = Arguments.createMap();
  960. eventData.putString("event", event);
  961. eventData.putString("detail", data);
  962. this.emitter.emit(streamName, eventData);
  963. }
  964. // "event" always is "data"...
  965. private void emitStreamEvent(String streamName, String event, WritableArray data) {
  966. WritableMap eventData = Arguments.createMap();
  967. eventData.putString("event", event);
  968. eventData.putArray("detail", data);
  969. this.emitter.emit(streamName, eventData);
  970. }
  971. // "event" always is "error"...
  972. private void emitStreamEvent(String streamName, String event, String code, String message) {
  973. WritableMap eventData = Arguments.createMap();
  974. eventData.putString("event", event);
  975. eventData.putString("code", code);
  976. eventData.putString("detail", message);
  977. this.emitter.emit(streamName, eventData);
  978. }
  979. /**
  980. * Get input stream of the given path, when the path is a string starts with bundle-assets://
  981. * the stream is created by Assets Manager, otherwise use FileInputStream.
  982. * @param path The file to open stream
  983. * @return InputStream instance
  984. * @throws IOException If the given file does not exist or is a directory FileInputStream will throw a FileNotFoundException
  985. */
  986. private static InputStream inputStreamFromPath(String path) throws IOException {
  987. if (path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  988. return RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  989. }
  990. return new FileInputStream(new File(path));
  991. }
  992. /**
  993. * Check if the asset or the file exists
  994. * @param path A file path URI string
  995. * @return A boolean value represents if the path exists.
  996. */
  997. private static boolean isPathExists(String path) {
  998. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  999. try {
  1000. RNFetchBlob.RCTContext.getAssets().open(path.replace(com.RNFetchBlob.RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  1001. } catch (IOException e) {
  1002. return false;
  1003. }
  1004. return true;
  1005. }
  1006. else {
  1007. return new File(path).exists();
  1008. }
  1009. }
  1010. static boolean isAsset(String path) {
  1011. return path != null && path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET);
  1012. }
  1013. /**
  1014. * Normalize the path, remove URI scheme (xxx://) so that we can handle it.
  1015. * @param path URI string.
  1016. * @return Normalized string
  1017. */
  1018. static String normalizePath(String path) {
  1019. if(path == null)
  1020. return null;
  1021. if(!path.matches("\\w+\\:.*"))
  1022. return path;
  1023. if(path.startsWith("file://")) {
  1024. return path.replace("file://", "");
  1025. }
  1026. Uri uri = Uri.parse(path);
  1027. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  1028. return path;
  1029. }
  1030. else
  1031. return PathResolver.getRealPathFromURI(RNFetchBlob.RCTContext, uri);
  1032. }
  1033. }