No Description

RNFetchBlobFS.java 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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. res.put("SDCardApplicationDir", ctx.getExternalFilesDir(null).getParentFile().getAbsolutePath());
  231. }
  232. res.put("MainBundleDir", ctx.getApplicationInfo().dataDir);
  233. return res;
  234. }
  235. /**
  236. * Static method that returns a temp file path
  237. * @param taskId An unique string for identify
  238. * @return String
  239. */
  240. static String getTmpPath(String taskId) {
  241. return RNFetchBlob.RCTContext.getFilesDir() + "/RNFetchBlobTmp_" + taskId;
  242. }
  243. /**
  244. * Create a file stream for read
  245. * @param path File stream target path
  246. * @param encoding File stream decoder, should be one of `base64`, `utf8`, `ascii`
  247. * @param bufferSize Buffer size of read stream, default to 4096 (4095 when encode is `base64`)
  248. */
  249. void readStream(String path, String encoding, int bufferSize, int tick, final String streamId) {
  250. String resolved = normalizePath(path);
  251. if(resolved != null)
  252. path = resolved;
  253. try {
  254. int chunkSize = encoding.equalsIgnoreCase("base64") ? 4095 : 4096;
  255. if(bufferSize > 0)
  256. chunkSize = bufferSize;
  257. InputStream fs;
  258. if(resolved != null && path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  259. fs = RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  260. }
  261. // fix issue 287
  262. else if(resolved == null) {
  263. fs = RNFetchBlob.RCTContext.getContentResolver().openInputStream(Uri.parse(path));
  264. }
  265. else {
  266. fs = new FileInputStream(new File(path));
  267. }
  268. byte[] buffer = new byte[chunkSize];
  269. int cursor = 0;
  270. boolean error = false;
  271. if (encoding.equalsIgnoreCase("utf8")) {
  272. CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
  273. while ((cursor = fs.read(buffer)) != -1) {
  274. encoder.encode(ByteBuffer.wrap(buffer).asCharBuffer());
  275. String chunk = new String(buffer, 0, cursor);
  276. emitStreamEvent(streamId, "data", chunk);
  277. if(tick > 0)
  278. SystemClock.sleep(tick);
  279. }
  280. } else if (encoding.equalsIgnoreCase("ascii")) {
  281. while ((cursor = fs.read(buffer)) != -1) {
  282. WritableArray chunk = Arguments.createArray();
  283. for(int i =0;i<cursor;i++)
  284. {
  285. chunk.pushInt((int)buffer[i]);
  286. }
  287. emitStreamEvent(streamId, "data", chunk);
  288. if(tick > 0)
  289. SystemClock.sleep(tick);
  290. }
  291. } else if (encoding.equalsIgnoreCase("base64")) {
  292. while ((cursor = fs.read(buffer)) != -1) {
  293. if(cursor < chunkSize) {
  294. byte[] copy = new byte[cursor];
  295. System.arraycopy(buffer, 0, copy, 0, cursor);
  296. emitStreamEvent(streamId, "data", Base64.encodeToString(copy, Base64.NO_WRAP));
  297. }
  298. else
  299. emitStreamEvent(streamId, "data", Base64.encodeToString(buffer, Base64.NO_WRAP));
  300. if(tick > 0)
  301. SystemClock.sleep(tick);
  302. }
  303. } else {
  304. emitStreamEvent(
  305. streamId,
  306. "error",
  307. "EINVAL",
  308. "Unrecognized encoding `" + encoding + "`, should be one of `base64`, `utf8`, `ascii`"
  309. );
  310. error = true;
  311. }
  312. if(!error)
  313. emitStreamEvent(streamId, "end", "");
  314. fs.close();
  315. buffer = null;
  316. } catch (FileNotFoundException err) {
  317. emitStreamEvent(
  318. streamId,
  319. "error",
  320. "ENOENT",
  321. "No such file '" + path + "'"
  322. );
  323. } catch (Exception err) {
  324. emitStreamEvent(
  325. streamId,
  326. "error",
  327. "EUNSPECIFIED",
  328. "Failed to convert data to " + encoding + " encoded string. This might be because this encoding cannot be used for this data."
  329. );
  330. err.printStackTrace();
  331. }
  332. }
  333. /**
  334. * Create a write stream and store its instance in RNFetchBlobFS.fileStreams
  335. * @param path Target file path
  336. * @param encoding Should be one of `base64`, `utf8`, `ascii`
  337. * @param append Flag represents if the file stream overwrite existing content
  338. * @param callback Callback
  339. */
  340. void writeStream(String path, String encoding, boolean append, Callback callback) {
  341. try {
  342. File dest = new File(path);
  343. File dir = dest.getParentFile();
  344. if(!dest.exists()) {
  345. if(dir != null && !dir.exists()) {
  346. if (!dir.mkdirs()) {
  347. callback.invoke("ENOTDIR", "Failed to create parent directory of '" + path + "'");
  348. return;
  349. }
  350. }
  351. if(!dest.createNewFile()) {
  352. callback.invoke("ENOENT", "File '" + path + "' does not exist and could not be created");
  353. return;
  354. }
  355. } else if(dest.isDirectory()) {
  356. callback.invoke("EISDIR", "Expecting a file but '" + path + "' is a directory");
  357. return;
  358. }
  359. OutputStream fs = new FileOutputStream(path, append);
  360. this.encoding = encoding;
  361. String streamId = UUID.randomUUID().toString();
  362. RNFetchBlobFS.fileStreams.put(streamId, this);
  363. this.writeStreamInstance = fs;
  364. callback.invoke(null, null, streamId);
  365. } catch(Exception err) {
  366. callback.invoke("EUNSPECIFIED", "Failed to create write stream at path `" + path + "`; " + err.getLocalizedMessage());
  367. }
  368. }
  369. /**
  370. * Write a chunk of data into a file stream.
  371. * @param streamId File stream ID
  372. * @param data Data chunk in string format
  373. * @param callback JS context callback
  374. */
  375. static void writeChunk(String streamId, String data, Callback callback) {
  376. RNFetchBlobFS fs = fileStreams.get(streamId);
  377. OutputStream stream = fs.writeStreamInstance;
  378. byte[] chunk = RNFetchBlobFS.stringToBytes(data, fs.encoding);
  379. try {
  380. stream.write(chunk);
  381. callback.invoke();
  382. } catch (Exception e) {
  383. callback.invoke(e.getLocalizedMessage());
  384. }
  385. }
  386. /**
  387. * Write data using ascii array
  388. * @param streamId File stream ID
  389. * @param data Data chunk in ascii array format
  390. * @param callback JS context callback
  391. */
  392. static void writeArrayChunk(String streamId, ReadableArray data, Callback callback) {
  393. try {
  394. RNFetchBlobFS fs = fileStreams.get(streamId);
  395. OutputStream stream = fs.writeStreamInstance;
  396. byte[] chunk = new byte[data.size()];
  397. for(int i =0; i< data.size();i++) {
  398. chunk[i] = (byte) data.getInt(i);
  399. }
  400. stream.write(chunk);
  401. callback.invoke();
  402. } catch (Exception e) {
  403. callback.invoke(e.getLocalizedMessage());
  404. }
  405. }
  406. /**
  407. * Close file write stream by ID
  408. * @param streamId Stream ID
  409. * @param callback JS context callback
  410. */
  411. static void closeStream(String streamId, Callback callback) {
  412. try {
  413. RNFetchBlobFS fs = fileStreams.get(streamId);
  414. OutputStream stream = fs.writeStreamInstance;
  415. fileStreams.remove(streamId);
  416. stream.close();
  417. callback.invoke();
  418. } catch(Exception err) {
  419. callback.invoke(err.getLocalizedMessage());
  420. }
  421. }
  422. /**
  423. * Unlink file at path
  424. * @param path Path of target
  425. * @param callback JS context callback
  426. */
  427. static void unlink(String path, Callback callback) {
  428. try {
  429. RNFetchBlobFS.deleteRecursive(new File(path));
  430. callback.invoke(null, true);
  431. } catch(Exception err) {
  432. callback.invoke(err.getLocalizedMessage(), false);
  433. }
  434. }
  435. private static void deleteRecursive(File fileOrDirectory) throws IOException {
  436. if (fileOrDirectory.isDirectory()) {
  437. File[] files = fileOrDirectory.listFiles();
  438. if (files == null) {
  439. throw new NullPointerException("Received null trying to list files of directory '" + fileOrDirectory + "'");
  440. } else {
  441. for (File child : files) {
  442. deleteRecursive(child);
  443. }
  444. }
  445. }
  446. boolean result = fileOrDirectory.delete();
  447. if (!result) {
  448. throw new IOException("Failed to delete '" + fileOrDirectory + "'");
  449. }
  450. }
  451. /**
  452. * Make a folder
  453. * @param path Source path
  454. * @param promise JS promise
  455. */
  456. static void mkdir(String path, Promise promise) {
  457. File dest = new File(path);
  458. if(dest.exists()) {
  459. promise.reject("EEXIST", dest.isDirectory() ? "Folder" : "File" + " '" + path + "' already exists");
  460. return;
  461. }
  462. try {
  463. boolean result = dest.mkdirs();
  464. if (!result) {
  465. promise.reject("EUNSPECIFIED", "mkdir failed to create some or all directories in '" + path + "'");
  466. return;
  467. }
  468. } catch (Exception e) {
  469. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  470. return;
  471. }
  472. promise.resolve(true);
  473. }
  474. /**
  475. * Copy file to destination path
  476. * @param path Source path
  477. * @param dest Target path
  478. * @param callback JS context callback
  479. */
  480. static void cp(String path, String dest, Callback callback) {
  481. path = normalizePath(path);
  482. InputStream in = null;
  483. OutputStream out = null;
  484. try {
  485. if(!isPathExists(path)) {
  486. callback.invoke("Source file at path`" + path + "` does not exist");
  487. return;
  488. }
  489. if(!new File(dest).exists()) {
  490. boolean result = new File(dest).createNewFile();
  491. if (!result) {
  492. callback.invoke("Destination file at '" + dest + "' already exists");
  493. return;
  494. }
  495. }
  496. in = inputStreamFromPath(path);
  497. out = new FileOutputStream(dest);
  498. byte[] buf = new byte[10240];
  499. int len;
  500. while ((len = in.read(buf)) > 0) {
  501. out.write(buf, 0, len);
  502. }
  503. } catch (Exception err) {
  504. callback.invoke(err.getLocalizedMessage());
  505. } finally {
  506. try {
  507. if (in != null) {
  508. in.close();
  509. }
  510. if (out != null) {
  511. out.close();
  512. }
  513. callback.invoke();
  514. } catch (Exception e) {
  515. callback.invoke(e.getLocalizedMessage());
  516. }
  517. }
  518. }
  519. /**
  520. * Move file
  521. * @param path Source file path
  522. * @param dest Destination file path
  523. * @param callback JS context callback
  524. */
  525. static void mv(String path, String dest, Callback callback) {
  526. File src = new File(path);
  527. if(!src.exists()) {
  528. callback.invoke("Source file at path `" + path + "` does not exist");
  529. return;
  530. }
  531. try {
  532. boolean result = src.renameTo(new File(dest));
  533. if (!result) {
  534. callback.invoke("mv failed for unknown reasons");
  535. return;
  536. }
  537. } catch (Exception e) {
  538. callback.invoke(e.getLocalizedMessage());
  539. return;
  540. }
  541. callback.invoke();
  542. }
  543. /**
  544. * Check if the path exists, also check if it is a folder when exists.
  545. * @param path Path to check
  546. * @param callback JS context callback
  547. */
  548. static void exists(String path, Callback callback) {
  549. if(isAsset(path)) {
  550. try {
  551. String filename = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  552. com.RNFetchBlob.RNFetchBlob.RCTContext.getAssets().openFd(filename);
  553. callback.invoke(true, false);
  554. } catch (IOException e) {
  555. callback.invoke(false, false);
  556. }
  557. }
  558. else {
  559. path = normalizePath(path);
  560. boolean exist = new File(path).exists();
  561. boolean isDir = new File(path).isDirectory();
  562. callback.invoke(exist, isDir);
  563. }
  564. }
  565. /**
  566. * List content of folder
  567. * @param path Target folder
  568. * @param callback JS context callback
  569. */
  570. static void ls(String path, Promise promise) {
  571. try {
  572. path = normalizePath(path);
  573. File src = new File(path);
  574. if (!src.exists()) {
  575. promise.reject("ENOENT", "No such file '" + path + "'");
  576. return;
  577. }
  578. if (!src.isDirectory()) {
  579. promise.reject("ENOTDIR", "Not a directory '" + path + "'");
  580. return;
  581. }
  582. String[] files = new File(path).list();
  583. WritableArray arg = Arguments.createArray();
  584. // File => list(): "If this abstract pathname does not denote a directory, then this method returns null."
  585. // We excluded that possibility above - ignore the "can produce NullPointerException" warning of the IDE.
  586. for (String i : files) {
  587. arg.pushString(i);
  588. }
  589. promise.resolve(arg);
  590. } catch (Exception e) {
  591. e.printStackTrace();
  592. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  593. }
  594. }
  595. /**
  596. * Create a file by slicing given file path
  597. * @param path Source file path
  598. * @param dest Destination of created file
  599. * @param start Start byte offset in source file
  600. * @param end End byte offset
  601. * @param encode NOT IMPLEMENTED
  602. */
  603. static void slice(String path, String dest, int start, int end, String encode, Promise promise) {
  604. try {
  605. path = normalizePath(path);
  606. File source = new File(path);
  607. if(source.isDirectory()){
  608. promise.reject("EISDIR", "Expecting a file but '" + path + "' is a directory");
  609. return;
  610. }
  611. if(!source.exists()){
  612. promise.reject("ENOENT", "No such file '" + path + "'");
  613. return;
  614. }
  615. int size = (int) source.length();
  616. int max = Math.min(size, end);
  617. int expected = max - start;
  618. int now = 0;
  619. FileInputStream in = new FileInputStream(new File(path));
  620. FileOutputStream out = new FileOutputStream(new File(dest));
  621. int skipped = (int) in.skip(start);
  622. if (skipped != start) {
  623. promise.reject("EUNSPECIFIED", "Skipped " + skipped + " instead of the specified " + start + " bytes, size is " + size);
  624. return;
  625. }
  626. byte[] buffer = new byte[10240];
  627. while(now < expected) {
  628. int read = in.read(buffer, 0, 10240);
  629. int remain = expected - now;
  630. if(read <= 0) {
  631. break;
  632. }
  633. out.write(buffer, 0, (int) Math.min(remain, read));
  634. now += read;
  635. }
  636. in.close();
  637. out.flush();
  638. out.close();
  639. promise.resolve(dest);
  640. } catch (Exception e) {
  641. e.printStackTrace();
  642. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  643. }
  644. }
  645. static void lstat(String path, final Callback callback) {
  646. path = normalizePath(path);
  647. new AsyncTask<String, Integer, Integer>() {
  648. @Override
  649. protected Integer doInBackground(String ...args) {
  650. WritableArray res = Arguments.createArray();
  651. if(args[0] == null) {
  652. callback.invoke("the path specified for lstat is either `null` or `undefined`.");
  653. return 0;
  654. }
  655. File src = new File(args[0]);
  656. if(!src.exists()) {
  657. callback.invoke("failed to lstat path `" + args[0] + "` because it does not exist or it is not a folder");
  658. return 0;
  659. }
  660. if(src.isDirectory()) {
  661. String [] files = src.list();
  662. // File => list(): "If this abstract pathname does not denote a directory, then this method returns null."
  663. // We excluded that possibility above - ignore the "can produce NullPointerException" warning of the IDE.
  664. for(String p : files) {
  665. res.pushMap(statFile(src.getPath() + "/" + p));
  666. }
  667. }
  668. else {
  669. res.pushMap(statFile(src.getAbsolutePath()));
  670. }
  671. callback.invoke(null, res);
  672. return 0;
  673. }
  674. }.execute(path);
  675. }
  676. /**
  677. * show status of a file or directory
  678. * @param path Path
  679. * @param callback Callback
  680. */
  681. static void stat(String path, Callback callback) {
  682. try {
  683. path = normalizePath(path);
  684. WritableMap result = statFile(path);
  685. if(result == null)
  686. callback.invoke("failed to stat path `" + path + "` because it does not exist or it is not a folder", null);
  687. else
  688. callback.invoke(null, result);
  689. } catch(Exception err) {
  690. callback.invoke(err.getLocalizedMessage());
  691. }
  692. }
  693. /**
  694. * Basic stat method
  695. * @param path Path
  696. * @return Stat Result of a file or path
  697. */
  698. static WritableMap statFile(String path) {
  699. try {
  700. path = normalizePath(path);
  701. WritableMap stat = Arguments.createMap();
  702. if(isAsset(path)) {
  703. String name = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  704. AssetFileDescriptor fd = RNFetchBlob.RCTContext.getAssets().openFd(name);
  705. stat.putString("filename", name);
  706. stat.putString("path", path);
  707. stat.putString("type", "asset");
  708. stat.putString("size", String.valueOf(fd.getLength()));
  709. stat.putInt("lastModified", 0);
  710. }
  711. else {
  712. File target = new File(path);
  713. if (!target.exists()) {
  714. return null;
  715. }
  716. stat.putString("filename", target.getName());
  717. stat.putString("path", target.getPath());
  718. stat.putString("type", target.isDirectory() ? "directory" : "file");
  719. stat.putString("size", String.valueOf(target.length()));
  720. String lastModified = String.valueOf(target.lastModified());
  721. stat.putString("lastModified", lastModified);
  722. }
  723. return stat;
  724. } catch(Exception err) {
  725. return null;
  726. }
  727. }
  728. /**
  729. * Media scanner scan file
  730. * @param path Path to file
  731. * @param mimes Array of MIME type strings
  732. * @param callback Callback for results
  733. */
  734. void scanFile(String [] path, String[] mimes, final Callback callback) {
  735. try {
  736. MediaScannerConnection.scanFile(mCtx, path, mimes, new MediaScannerConnection.OnScanCompletedListener() {
  737. @Override
  738. public void onScanCompleted(String s, Uri uri) {
  739. callback.invoke(null, true);
  740. }
  741. });
  742. } catch(Exception err) {
  743. callback.invoke(err.getLocalizedMessage(), null);
  744. }
  745. }
  746. static void hash(String path, String algorithm, Promise promise) {
  747. try {
  748. Map<String, String> algorithms = new HashMap<>();
  749. algorithms.put("md5", "MD5");
  750. algorithms.put("sha1", "SHA-1");
  751. algorithms.put("sha224", "SHA-224");
  752. algorithms.put("sha256", "SHA-256");
  753. algorithms.put("sha384", "SHA-384");
  754. algorithms.put("sha512", "SHA-512");
  755. if (!algorithms.containsKey(algorithm)) {
  756. promise.reject("EINVAL", "Invalid algorithm '" + algorithm + "', must be one of md5, sha1, sha224, sha256, sha384, sha512");
  757. return;
  758. }
  759. File file = new File(path);
  760. if (file.isDirectory()) {
  761. promise.reject("EISDIR", "Expecting a file but '" + path + "' is a directory");
  762. return;
  763. }
  764. if (!file.exists()) {
  765. promise.reject("ENOENT", "No such file '" + path + "'");
  766. return;
  767. }
  768. MessageDigest md = MessageDigest.getInstance(algorithms.get(algorithm));
  769. FileInputStream inputStream = new FileInputStream(path);
  770. byte[] buffer = new byte[(int)file.length()];
  771. int read;
  772. while ((read = inputStream.read(buffer)) != -1) {
  773. md.update(buffer, 0, read);
  774. }
  775. StringBuilder hexString = new StringBuilder();
  776. for (byte digestByte : md.digest())
  777. hexString.append(String.format("%02x", digestByte));
  778. promise.resolve(hexString.toString());
  779. } catch (Exception e) {
  780. e.printStackTrace();
  781. promise.reject("EUNSPECIFIED", e.getLocalizedMessage());
  782. }
  783. }
  784. /**
  785. * Create new file at path
  786. * @param path The destination path of the new file.
  787. * @param data Initial data of the new file.
  788. * @param encoding Encoding of initial data.
  789. * @param promise Promise for Javascript
  790. */
  791. static void createFile(String path, String data, String encoding, Promise promise) {
  792. try {
  793. File dest = new File(path);
  794. boolean created = dest.createNewFile();
  795. if(encoding.equals(RNFetchBlobConst.DATA_ENCODE_URI)) {
  796. String orgPath = data.replace(RNFetchBlobConst.FILE_PREFIX, "");
  797. File src = new File(orgPath);
  798. if(!src.exists()) {
  799. promise.reject("ENOENT", "Source file : " + data + " does not exist");
  800. return ;
  801. }
  802. FileInputStream fin = new FileInputStream(src);
  803. OutputStream ostream = new FileOutputStream(dest);
  804. byte[] buffer = new byte[10240];
  805. int read = fin.read(buffer);
  806. while (read > 0) {
  807. ostream.write(buffer, 0, read);
  808. read = fin.read(buffer);
  809. }
  810. fin.close();
  811. ostream.close();
  812. } else {
  813. if (!created) {
  814. promise.reject("EEXIST", "File `" + path + "` already exists");
  815. return;
  816. }
  817. OutputStream ostream = new FileOutputStream(dest);
  818. ostream.write(RNFetchBlobFS.stringToBytes(data, encoding));
  819. }
  820. promise.resolve(path);
  821. } catch(Exception err) {
  822. promise.reject("EUNSPECIFIED", err.getLocalizedMessage());
  823. }
  824. }
  825. /**
  826. * Create file for ASCII encoding
  827. * @param path Path of new file.
  828. * @param data Content of new file
  829. * @param promise JS Promise
  830. */
  831. static void createFileASCII(String path, ReadableArray data, Promise promise) {
  832. try {
  833. File dest = new File(path);
  834. boolean created = dest.createNewFile();
  835. if(!created) {
  836. promise.reject("EEXIST", "File at path `" + path + "` already exists");
  837. return;
  838. }
  839. OutputStream ostream = new FileOutputStream(dest);
  840. byte[] chunk = new byte[data.size()];
  841. for(int i=0; i<data.size(); i++) {
  842. chunk[i] = (byte) data.getInt(i);
  843. }
  844. ostream.write(chunk);
  845. promise.resolve(path);
  846. } catch(Exception err) {
  847. promise.reject("EUNSPECIFIED", err.getLocalizedMessage());
  848. }
  849. }
  850. static void df(Callback callback) {
  851. StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
  852. WritableMap args = Arguments.createMap();
  853. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  854. args.putString("internal_free", String.valueOf(stat.getFreeBytes()));
  855. args.putString("internal_total", String.valueOf(stat.getTotalBytes()));
  856. StatFs statEx = new StatFs(Environment.getExternalStorageDirectory().getPath());
  857. args.putString("external_free", String.valueOf(statEx.getFreeBytes()));
  858. args.putString("external_total", String.valueOf(statEx.getTotalBytes()));
  859. }
  860. callback.invoke(null ,args);
  861. }
  862. /**
  863. * Remove files in session.
  864. * @param paths An array of file paths.
  865. * @param callback JS contest callback
  866. */
  867. static void removeSession(ReadableArray paths, final Callback callback) {
  868. AsyncTask<ReadableArray, Integer, Integer> task = new AsyncTask<ReadableArray, Integer, Integer>() {
  869. @Override
  870. protected Integer doInBackground(ReadableArray ...paths) {
  871. try {
  872. ArrayList<String> failuresToDelete = new ArrayList<>();
  873. for (int i = 0; i < paths[0].size(); i++) {
  874. String fileName = paths[0].getString(i);
  875. File f = new File(fileName);
  876. if (f.exists()) {
  877. boolean result = f.delete();
  878. if (!result) {
  879. failuresToDelete.add(fileName);
  880. }
  881. }
  882. }
  883. if (failuresToDelete.isEmpty()) {
  884. callback.invoke(null, true);
  885. } else {
  886. StringBuilder listString = new StringBuilder();
  887. listString.append("Failed to delete: ");
  888. for (String s : failuresToDelete) {
  889. listString.append(s).append(", ");
  890. }
  891. callback.invoke(listString.toString());
  892. }
  893. } catch(Exception err) {
  894. callback.invoke(err.getLocalizedMessage());
  895. }
  896. return paths[0].size();
  897. }
  898. };
  899. task.execute(paths);
  900. }
  901. /**
  902. * String to byte converter method
  903. * @param data Raw data in string format
  904. * @param encoding Decoder name
  905. * @return Converted data byte array
  906. */
  907. private static byte[] stringToBytes(String data, String encoding) {
  908. if(encoding.equalsIgnoreCase("ascii")) {
  909. return data.getBytes(Charset.forName("US-ASCII"));
  910. }
  911. else if(encoding.toLowerCase().contains("base64")) {
  912. return Base64.decode(data, Base64.NO_WRAP);
  913. }
  914. else if(encoding.equalsIgnoreCase("utf8")) {
  915. return data.getBytes(Charset.forName("UTF-8"));
  916. }
  917. return data.getBytes(Charset.forName("US-ASCII"));
  918. }
  919. /**
  920. * Private method for emit read stream event.
  921. * @param streamName ID of the read stream
  922. * @param event Event name, `data`, `end`, `error`, etc.
  923. * @param data Event data
  924. */
  925. private void emitStreamEvent(String streamName, String event, String data) {
  926. WritableMap eventData = Arguments.createMap();
  927. eventData.putString("event", event);
  928. eventData.putString("detail", data);
  929. this.emitter.emit(streamName, eventData);
  930. }
  931. // "event" always is "data"...
  932. private void emitStreamEvent(String streamName, String event, WritableArray data) {
  933. WritableMap eventData = Arguments.createMap();
  934. eventData.putString("event", event);
  935. eventData.putArray("detail", data);
  936. this.emitter.emit(streamName, eventData);
  937. }
  938. // "event" always is "error"...
  939. private void emitStreamEvent(String streamName, String event, String code, String message) {
  940. WritableMap eventData = Arguments.createMap();
  941. eventData.putString("event", event);
  942. eventData.putString("code", code);
  943. eventData.putString("detail", message);
  944. this.emitter.emit(streamName, eventData);
  945. }
  946. /**
  947. * Get input stream of the given path, when the path is a string starts with bundle-assets://
  948. * the stream is created by Assets Manager, otherwise use FileInputStream.
  949. * @param path The file to open stream
  950. * @return InputStream instance
  951. * @throws IOException If the given file does not exist or is a directory FileInputStream will throw a FileNotFoundException
  952. */
  953. private static InputStream inputStreamFromPath(String path) throws IOException {
  954. if (path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  955. return RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  956. }
  957. return new FileInputStream(new File(path));
  958. }
  959. /**
  960. * Check if the asset or the file exists
  961. * @param path A file path URI string
  962. * @return A boolean value represents if the path exists.
  963. */
  964. private static boolean isPathExists(String path) {
  965. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  966. try {
  967. RNFetchBlob.RCTContext.getAssets().open(path.replace(com.RNFetchBlob.RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  968. } catch (IOException e) {
  969. return false;
  970. }
  971. return true;
  972. }
  973. else {
  974. return new File(path).exists();
  975. }
  976. }
  977. static boolean isAsset(String path) {
  978. return path != null && path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET);
  979. }
  980. /**
  981. * Normalize the path, remove URI scheme (xxx://) so that we can handle it.
  982. * @param path URI string.
  983. * @return Normalized string
  984. */
  985. static String normalizePath(String path) {
  986. if(path == null)
  987. return null;
  988. if(!path.matches("\\w+\\:.*"))
  989. return path;
  990. if(path.startsWith("file://")) {
  991. return path.replace("file://", "");
  992. }
  993. Uri uri = Uri.parse(path);
  994. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  995. return path;
  996. }
  997. else
  998. return PathResolver.getRealPathFromURI(RNFetchBlob.RCTContext, uri);
  999. }
  1000. }