No Description

RNFetchBlobFS.java 43KB

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