暂无描述

RNFetchBlobFS.java 43KB

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