Açıklama Yok

RNFetchBlobFS.java 44KB

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