Ingen beskrivning

RNFetchBlobFS.java 42KB

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