No Description

RNFetchBlobFS.java 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. package com.RNFetchBlob;
  2. import android.content.pm.PackageInfo;
  3. import android.content.pm.PackageManager;
  4. import android.content.res.AssetFileDescriptor;
  5. import android.media.MediaScannerConnection;
  6. import android.net.Uri;
  7. import android.os.AsyncTask;
  8. import android.os.Build;
  9. import android.os.Environment;
  10. import android.os.StatFs;
  11. import android.os.SystemClock;
  12. import android.util.Base64;
  13. import com.RNFetchBlob.Utils.PathResolver;
  14. import com.facebook.react.bridge.Arguments;
  15. import com.facebook.react.bridge.Callback;
  16. import com.facebook.react.bridge.Promise;
  17. import com.facebook.react.bridge.ReactApplicationContext;
  18. import com.facebook.react.bridge.ReadableArray;
  19. import com.facebook.react.bridge.WritableArray;
  20. import com.facebook.react.bridge.WritableMap;
  21. import com.facebook.react.modules.core.DeviceEventManagerModule;
  22. import java.io.File;
  23. import java.io.FileInputStream;
  24. import java.io.FileOutputStream;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.io.OutputStream;
  28. import java.nio.ByteBuffer;
  29. import java.nio.charset.Charset;
  30. import java.nio.charset.CharsetEncoder;
  31. import java.util.HashMap;
  32. import java.util.Map;
  33. import java.util.UUID;
  34. public class RNFetchBlobFS {
  35. ReactApplicationContext mCtx;
  36. DeviceEventManagerModule.RCTDeviceEventEmitter emitter;
  37. String encoding = "base64";
  38. boolean append = false;
  39. OutputStream writeStreamInstance = null;
  40. static HashMap<String, RNFetchBlobFS> fileStreams = new HashMap<>();
  41. RNFetchBlobFS(ReactApplicationContext ctx) {
  42. this.mCtx = ctx;
  43. this.emitter = ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
  44. }
  45. static String getExternalFilePath(ReactApplicationContext ctx, String taskId, RNFetchBlobConfig config) {
  46. if(config.path != null)
  47. return config.path;
  48. else if(config.fileCache && config.appendExt != null)
  49. return RNFetchBlobFS.getTmpPath(ctx, taskId) + "." + config.appendExt;
  50. else
  51. return RNFetchBlobFS.getTmpPath(ctx, taskId);
  52. }
  53. /**
  54. * Write string with encoding to file
  55. * @param path Destination file path.
  56. * @param encoding Encoding of the string.
  57. * @param data Array passed from JS context.
  58. * @param promise RCT Promise
  59. */
  60. static public void writeFile(String path, String encoding, String data, final boolean append, final Promise promise) {
  61. try {
  62. int written = 0;
  63. File f = new File(path);
  64. File dir = f.getParentFile();
  65. if(!dir.exists())
  66. dir.mkdirs();
  67. FileOutputStream fout = new FileOutputStream(f, append);
  68. // write data from a file
  69. if(encoding.equalsIgnoreCase(RNFetchBlobConst.DATA_ENCODE_URI)) {
  70. data = normalizePath(data);
  71. File src = new File(data);
  72. if(!src.exists()) {
  73. promise.reject("RNfetchBlob writeFile error", "source file : " + data + " does not exist");
  74. fout.close();
  75. return ;
  76. }
  77. FileInputStream fin = new FileInputStream(src);
  78. byte [] buffer = new byte [10240];
  79. int read;
  80. written = 0;
  81. while((read = fin.read(buffer)) > 0) {
  82. fout.write(buffer, 0, read);
  83. written += read;
  84. }
  85. fin.close();
  86. }
  87. else {
  88. byte[] bytes = stringToBytes(data, encoding);
  89. fout.write(bytes);
  90. written = bytes.length;
  91. }
  92. fout.close();
  93. promise.resolve(written);
  94. } catch (Exception e) {
  95. promise.reject("RNFetchBlob writeFile error", e.getLocalizedMessage());
  96. }
  97. }
  98. /**
  99. * Write array of bytes into file
  100. * @param path Destination file path.
  101. * @param data Array passed from JS context.
  102. * @param promise RCT Promise
  103. */
  104. static public void writeFile(String path, ReadableArray data, final boolean append, final Promise promise) {
  105. try {
  106. File f = new File(path);
  107. File dir = f.getParentFile();
  108. if(!dir.exists())
  109. dir.mkdirs();
  110. FileOutputStream os = new FileOutputStream(f, append);
  111. byte [] bytes = new byte[data.size()];
  112. for(int i=0;i<data.size();i++) {
  113. bytes[i] = (byte) data.getInt(i);
  114. }
  115. os.write(bytes);
  116. os.close();
  117. promise.resolve(data.size());
  118. } catch (Exception e) {
  119. promise.reject("RNFetchBlob writeFile error", e.getLocalizedMessage());
  120. }
  121. }
  122. /**
  123. * Read file with a buffer that has the same size as the target file.
  124. * @param path Path of the file.
  125. * @param encoding Encoding of read stream.
  126. * @param promise
  127. */
  128. static public void readFile(String path, String encoding, final Promise promise ) {
  129. String resolved = normalizePath(path);
  130. if(resolved != null)
  131. path = resolved;
  132. try {
  133. byte[] bytes;
  134. if(resolved != null && resolved.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  135. String assetName = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  136. long length = RNFetchBlob.RCTContext.getAssets().openFd(assetName).getLength();
  137. bytes = new byte[(int) length];
  138. InputStream in = RNFetchBlob.RCTContext.getAssets().open(assetName);
  139. in.read(bytes, 0, (int) length);
  140. in.close();
  141. }
  142. // issue 287
  143. else if(resolved == null) {
  144. InputStream in = RNFetchBlob.RCTContext.getContentResolver().openInputStream(Uri.parse(path));
  145. int length = (int) in.available();
  146. bytes = new byte[length];
  147. in.read(bytes);
  148. in.close();
  149. }
  150. else {
  151. File f = new File(path);
  152. int length = (int) f.length();
  153. bytes = new byte[length];
  154. FileInputStream in = new FileInputStream(f);
  155. in.read(bytes);
  156. in.close();
  157. }
  158. switch (encoding.toLowerCase()) {
  159. case "base64" :
  160. promise.resolve(Base64.encodeToString(bytes, Base64.NO_WRAP));
  161. break;
  162. case "ascii" :
  163. WritableArray asciiResult = Arguments.createArray();
  164. for(byte b : bytes) {
  165. asciiResult.pushInt((int)b);
  166. }
  167. promise.resolve(asciiResult);
  168. break;
  169. case "utf8" :
  170. promise.resolve(new String(bytes));
  171. break;
  172. default:
  173. promise.resolve(new String(bytes));
  174. break;
  175. }
  176. }
  177. catch(Exception err) {
  178. promise.reject("ReadFile Error", err.getLocalizedMessage());
  179. }
  180. }
  181. /**
  182. * Static method that returns system folders to JS context
  183. * @param ctx React Native application context
  184. */
  185. static public Map<String, Object> getSystemfolders(ReactApplicationContext ctx) {
  186. Map<String, Object> res = new HashMap<>();
  187. res.put("DocumentDir", ctx.getFilesDir().getAbsolutePath());
  188. res.put("CacheDir", ctx.getCacheDir().getAbsolutePath());
  189. res.put("DCIMDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath());
  190. res.put("PictureDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
  191. res.put("MusicDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath());
  192. res.put("DownloadDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
  193. res.put("MovieDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath());
  194. res.put("RingtoneDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES).getAbsolutePath());
  195. String state;
  196. state = Environment.getExternalStorageState();
  197. if (state.equals(Environment.MEDIA_MOUNTED)) {
  198. res.put("SDCardDir", Environment.getExternalStorageDirectory().getAbsolutePath());
  199. res.put("SDCardApplicationDir", ctx.getExternalFilesDir(null).getParentFile().getAbsolutePath());
  200. }
  201. res.put("MainBundleDir", ctx.getApplicationInfo().dataDir);
  202. return res;
  203. }
  204. /**
  205. * Static method that returns a temp file path
  206. * @param ctx React Native application context
  207. * @param taskId An unique string for identify
  208. * @return
  209. */
  210. static public String getTmpPath(ReactApplicationContext ctx, String taskId) {
  211. return RNFetchBlob.RCTContext.getFilesDir() + "/RNFetchBlobTmp_" + taskId;
  212. }
  213. /**
  214. * Create a file stream for read
  215. * @param path File stream target path
  216. * @param encoding File stream decoder, should be one of `base64`, `utf8`, `ascii`
  217. * @param bufferSize Buffer size of read stream, default to 4096 (4095 when encode is `base64`)
  218. */
  219. public void readStream(String path, String encoding, int bufferSize, int tick, final String streamId) {
  220. String resolved = normalizePath(path);
  221. if(resolved != null)
  222. path = resolved;
  223. try {
  224. int chunkSize = encoding.equalsIgnoreCase("base64") ? 4095 : 4096;
  225. if(bufferSize > 0)
  226. chunkSize = bufferSize;
  227. InputStream fs;
  228. if(resolved != null && path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  229. fs = RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  230. }
  231. // fix issue 287
  232. else if(resolved == null) {
  233. fs = RNFetchBlob.RCTContext.getContentResolver().openInputStream(Uri.parse(path));
  234. }
  235. else {
  236. fs = new FileInputStream(new File(path));
  237. }
  238. byte[] buffer = new byte[chunkSize];
  239. int cursor = 0;
  240. boolean error = false;
  241. if (encoding.equalsIgnoreCase("utf8")) {
  242. CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
  243. while ((cursor = fs.read(buffer)) != -1) {
  244. encoder.encode(ByteBuffer.wrap(buffer).asCharBuffer());
  245. String chunk = new String(buffer, 0, cursor);
  246. emitStreamEvent(streamId, "data", chunk);
  247. if(tick > 0)
  248. SystemClock.sleep(tick);
  249. }
  250. } else if (encoding.equalsIgnoreCase("ascii")) {
  251. while ((cursor = fs.read(buffer)) != -1) {
  252. WritableArray chunk = Arguments.createArray();
  253. for(int i =0;i<cursor;i++)
  254. {
  255. chunk.pushInt((int)buffer[i]);
  256. }
  257. emitStreamEvent(streamId, "data", chunk);
  258. if(tick > 0)
  259. SystemClock.sleep(tick);
  260. }
  261. } else if (encoding.equalsIgnoreCase("base64")) {
  262. while ((cursor = fs.read(buffer)) != -1) {
  263. if(cursor < chunkSize) {
  264. byte [] copy = new byte[cursor];
  265. for(int i =0;i<cursor;i++) {
  266. copy[i] = buffer[i];
  267. }
  268. emitStreamEvent(streamId, "data", Base64.encodeToString(copy, Base64.NO_WRAP));
  269. }
  270. else
  271. emitStreamEvent(streamId, "data", Base64.encodeToString(buffer, Base64.NO_WRAP));
  272. if(tick > 0)
  273. SystemClock.sleep(tick);
  274. }
  275. } else {
  276. String msg = "unrecognized encoding `" + encoding + "`";
  277. emitStreamEvent(streamId, "error", msg);
  278. error = true;
  279. }
  280. if(!error)
  281. emitStreamEvent(streamId, "end", "");
  282. fs.close();
  283. buffer = null;
  284. } catch (Exception err) {
  285. emitStreamEvent(streamId, "warn", "Failed to convert data to " + encoding +
  286. " encoded string, this might due to the source data is not able to convert using this encoding.");
  287. err.printStackTrace();
  288. }
  289. }
  290. /**
  291. * Create a write stream and store its instance in RNFetchBlobFS.fileStreams
  292. * @param path Target file path
  293. * @param encoding Should be one of `base64`, `utf8`, `ascii`
  294. * @param append Flag represents if the file stream overwrite existing content
  295. * @param callback
  296. */
  297. public void writeStream(String path, String encoding, boolean append, Callback callback) {
  298. File dest = new File(path);
  299. if(!dest.exists() || dest.isDirectory()) {
  300. callback.invoke("target path `" + path + "` may not exist or it is a folder");
  301. return;
  302. }
  303. try {
  304. OutputStream fs = new FileOutputStream(path, append);
  305. this.encoding = encoding;
  306. this.append = append;
  307. String streamId = UUID.randomUUID().toString();
  308. RNFetchBlobFS.fileStreams.put(streamId, this);
  309. this.writeStreamInstance = fs;
  310. callback.invoke(null, streamId);
  311. } catch(Exception err) {
  312. callback.invoke("failed to create write stream at path `" + path + "` " + err.getLocalizedMessage());
  313. }
  314. }
  315. /**
  316. * Write a chunk of data into a file stream.
  317. * @param streamId File stream ID
  318. * @param data Data chunk in string format
  319. * @param callback JS context callback
  320. */
  321. static void writeChunk(String streamId, String data, Callback callback) {
  322. RNFetchBlobFS fs = fileStreams.get(streamId);
  323. OutputStream stream = fs.writeStreamInstance;
  324. byte [] chunk = RNFetchBlobFS.stringToBytes(data, fs.encoding);
  325. try {
  326. stream.write(chunk);
  327. callback.invoke();
  328. } catch (Exception e) {
  329. callback.invoke(e.getLocalizedMessage());
  330. }
  331. }
  332. /**
  333. * Write data using ascii array
  334. * @param streamId File stream ID
  335. * @param data Data chunk in ascii array format
  336. * @param callback JS context callback
  337. */
  338. static void writeArrayChunk(String streamId, ReadableArray data, Callback callback) {
  339. try {
  340. RNFetchBlobFS fs = fileStreams.get(streamId);
  341. OutputStream stream = fs.writeStreamInstance;
  342. byte [] chunk = new byte[data.size()];
  343. for(int i =0; i< data.size();i++) {
  344. chunk[i] = (byte) data.getInt(i);
  345. }
  346. stream.write(chunk);
  347. callback.invoke();
  348. } catch (Exception e) {
  349. callback.invoke(e.getLocalizedMessage());
  350. }
  351. }
  352. /**
  353. * Close file write stream by ID
  354. * @param streamId Stream ID
  355. * @param callback JS context callback
  356. */
  357. static void closeStream(String streamId, Callback callback) {
  358. try {
  359. RNFetchBlobFS fs = fileStreams.get(streamId);
  360. OutputStream stream = fs.writeStreamInstance;
  361. fileStreams.remove(streamId);
  362. stream.close();
  363. callback.invoke();
  364. } catch(Exception err) {
  365. callback.invoke(err.getLocalizedMessage());
  366. }
  367. }
  368. /**
  369. * Unlink file at path
  370. * @param path Path of target
  371. * @param callback JS context callback
  372. */
  373. static void unlink(String path, Callback callback) {
  374. try {
  375. RNFetchBlobFS.deleteRecursive(new File(path));
  376. callback.invoke(null, true);
  377. } catch(Exception err) {
  378. if(err != null)
  379. callback.invoke(err.getLocalizedMessage(), false);
  380. }
  381. }
  382. static void deleteRecursive(File fileOrDirectory) {
  383. if (fileOrDirectory.isDirectory()) {
  384. for (File child : fileOrDirectory.listFiles()) {
  385. deleteRecursive(child);
  386. }
  387. }
  388. fileOrDirectory.delete();
  389. }
  390. /**
  391. * Make a folder
  392. * @param path Source path
  393. * @param callback JS context callback
  394. */
  395. static void mkdir(String path, Callback callback) {
  396. File dest = new File(path);
  397. if(dest.exists()) {
  398. callback.invoke("mkdir failed, folder already exists at " + path);
  399. return;
  400. }
  401. dest.mkdirs();
  402. callback.invoke();
  403. }
  404. /**
  405. * Copy file to destination path
  406. * @param path Source path
  407. * @param dest Target path
  408. * @param callback JS context callback
  409. */
  410. static void cp(String path, String dest, Callback callback) {
  411. path = normalizePath(path);
  412. InputStream in = null;
  413. OutputStream out = null;
  414. try {
  415. if(!isPathExists(path)) {
  416. callback.invoke("source file at path`" + path + "` does not exist");
  417. return;
  418. }
  419. if(!new File(dest).exists())
  420. new File(dest).createNewFile();
  421. in = inputStreamFromPath(path);
  422. out = new FileOutputStream(dest);
  423. byte[] buf = new byte[10240];
  424. int len;
  425. while ((len = in.read(buf)) > 0) {
  426. out.write(buf, 0, len);
  427. }
  428. } catch (Exception err) {
  429. callback.invoke(err.getLocalizedMessage());
  430. } finally {
  431. try {
  432. if (in != null) {
  433. in.close();
  434. }
  435. if (out != null) {
  436. out.close();
  437. }
  438. callback.invoke();
  439. } catch (Exception e) {
  440. callback.invoke(e.getLocalizedMessage());
  441. }
  442. }
  443. }
  444. /**
  445. * Move file
  446. * @param path Source file path
  447. * @param dest Destination file path
  448. * @param callback JS context callback
  449. */
  450. static void mv(String path, String dest, Callback callback) {
  451. File src = new File(path);
  452. if(!src.exists()) {
  453. callback.invoke("source file at path `" + path + "` does not exist");
  454. return;
  455. }
  456. src.renameTo(new File(dest));
  457. callback.invoke();
  458. }
  459. /**
  460. * Check if the path exists, also check if it is a folder when exists.
  461. * @param path Path to check
  462. * @param callback JS context callback
  463. */
  464. static void exists(String path, Callback callback) {
  465. if(isAsset(path)) {
  466. try {
  467. String filename = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  468. AssetFileDescriptor fd = RNFetchBlob.RCTContext.getAssets().openFd(filename);
  469. callback.invoke(true, false);
  470. } catch (IOException e) {
  471. callback.invoke(false, false);
  472. }
  473. }
  474. else {
  475. path = normalizePath(path);
  476. boolean exist = new File(path).exists();
  477. boolean isDir = new File(path).isDirectory();
  478. callback.invoke(exist, isDir);
  479. }
  480. }
  481. /**
  482. * List content of folder
  483. * @param path Target folder
  484. * @param callback JS context callback
  485. */
  486. static void ls(String path, Callback callback) {
  487. path = normalizePath(path);
  488. File src = new File(path);
  489. if (!src.exists() || !src.isDirectory()) {
  490. callback.invoke("failed to list path `" + path + "` for it is not exist or it is not a folder");
  491. return;
  492. }
  493. String[] files = new File(path).list();
  494. WritableArray arg = Arguments.createArray();
  495. for (String i : files) {
  496. arg.pushString(i);
  497. }
  498. callback.invoke(null, arg);
  499. }
  500. /**
  501. * Create a file by slicing given file path
  502. * @param src Source file path
  503. * @param dest Destination of created file
  504. * @param start Start byte offset in source file
  505. * @param end End byte offset
  506. * @param encode NOT IMPLEMENTED
  507. */
  508. public static void slice(String src, String dest, int start, int end, String encode, Promise promise) {
  509. try {
  510. src = normalizePath(src);
  511. File source = new File(src);
  512. if(!source.exists()) {
  513. promise.reject("RNFetchBlob slice error", "source file : " + src + " does not exist");
  514. return;
  515. }
  516. long size = source.length();
  517. long max = Math.min(size, end);
  518. long expected = max - start;
  519. long now = 0;
  520. FileInputStream in = new FileInputStream(new File(src));
  521. FileOutputStream out = new FileOutputStream(new File(dest));
  522. in.skip(start);
  523. byte [] buffer = new byte[10240];
  524. while(now < expected) {
  525. long read = in.read(buffer, 0, 10240);
  526. long remain = expected - now;
  527. if(read <= 0) {
  528. break;
  529. }
  530. out.write(buffer, 0, (int) Math.min(remain, read));
  531. now += read;
  532. }
  533. in.close();
  534. out.flush();
  535. out.close();
  536. promise.resolve(dest);
  537. } catch (Exception e) {
  538. e.printStackTrace();
  539. promise.reject("RNFetchBlob slice error", e.getLocalizedMessage());
  540. }
  541. }
  542. static void lstat(String path, final Callback callback) {
  543. path = normalizePath(path);
  544. new AsyncTask<String, Integer, Integer>() {
  545. @Override
  546. protected Integer doInBackground(String ...args) {
  547. WritableArray res = Arguments.createArray();
  548. if(args[0] == null) {
  549. callback.invoke("the path specified for lstat is either `null` or `undefined`.");
  550. return 0;
  551. }
  552. File src = new File(args[0]);
  553. if(!src.exists()) {
  554. callback.invoke("failed to lstat path `" + args[0] + "` because it does not exist or it is not a folder");
  555. return 0;
  556. }
  557. if(src.isDirectory()) {
  558. String [] files = src.list();
  559. for(String p : files) {
  560. res.pushMap(statFile(src.getPath() + "/" + p));
  561. }
  562. }
  563. else {
  564. res.pushMap(statFile(src.getAbsolutePath()));
  565. }
  566. callback.invoke(null, res);
  567. return 0;
  568. }
  569. }.execute(path);
  570. }
  571. /**
  572. * show status of a file or directory
  573. * @param path
  574. * @param callback
  575. */
  576. static void stat(String path, Callback callback) {
  577. try {
  578. path = normalizePath(path);
  579. WritableMap result = statFile(path);
  580. if(result == null)
  581. callback.invoke("failed to stat path `" + path + "` because it does not exist or it is not a folder", null);
  582. else
  583. callback.invoke(null, result);
  584. } catch(Exception err) {
  585. callback.invoke(err.getLocalizedMessage());
  586. }
  587. }
  588. /**
  589. * Basic stat method
  590. * @param path
  591. * @return Stat result of a file or path
  592. */
  593. static WritableMap statFile(String path) {
  594. try {
  595. path = normalizePath(path);
  596. WritableMap stat = Arguments.createMap();
  597. if(isAsset(path)) {
  598. String name = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  599. AssetFileDescriptor fd = RNFetchBlob.RCTContext.getAssets().openFd(name);
  600. stat.putString("filename", name);
  601. stat.putString("path", path);
  602. stat.putString("type", "asset");
  603. stat.putString("size", String.valueOf(fd.getLength()));
  604. stat.putInt("lastModified", 0);
  605. }
  606. else {
  607. File target = new File(path);
  608. if (!target.exists()) {
  609. return null;
  610. }
  611. stat.putString("filename", target.getName());
  612. stat.putString("path", target.getPath());
  613. stat.putString("type", target.isDirectory() ? "directory" : "file");
  614. stat.putString("size", String.valueOf(target.length()));
  615. String lastModified = String.valueOf(target.lastModified());
  616. stat.putString("lastModified", lastModified);
  617. }
  618. return stat;
  619. } catch(Exception err) {
  620. return null;
  621. }
  622. }
  623. /**
  624. * Media scanner scan file
  625. * @param path
  626. * @param mimes
  627. * @param callback
  628. */
  629. void scanFile(String [] path, String[] mimes, final Callback callback) {
  630. try {
  631. MediaScannerConnection.scanFile(mCtx, path, mimes, new MediaScannerConnection.OnScanCompletedListener() {
  632. @Override
  633. public void onScanCompleted(String s, Uri uri) {
  634. callback.invoke(null, true);
  635. }
  636. });
  637. } catch(Exception err) {
  638. callback.invoke(err.getLocalizedMessage(), null);
  639. }
  640. }
  641. /**
  642. * Create new file at path
  643. * @param path The destination path of the new file.
  644. * @param data Initial data of the new file.
  645. * @param encoding Encoding of initial data.
  646. * @param callback RCT bridge callback.
  647. */
  648. static void createFile(String path, String data, String encoding, Callback callback) {
  649. try {
  650. File dest = new File(path);
  651. boolean created = dest.createNewFile();
  652. if(encoding.equals(RNFetchBlobConst.DATA_ENCODE_URI)) {
  653. String orgPath = data.replace(RNFetchBlobConst.FILE_PREFIX, "");
  654. File src = new File(orgPath);
  655. if(!src.exists()) {
  656. callback.invoke("source file : " + data + " does not exist");
  657. return ;
  658. }
  659. FileInputStream fin = new FileInputStream(src);
  660. OutputStream ostream = new FileOutputStream(dest);
  661. byte[] buffer = new byte[10240];
  662. int read = fin.read(buffer);
  663. while (read > 0) {
  664. ostream.write(buffer, 0, read);
  665. read = fin.read(buffer);
  666. }
  667. fin.close();
  668. ostream.close();
  669. } else {
  670. if (!created) {
  671. callback.invoke("failed to create new file at path `" + path + "` because its parent path " +
  672. "may not exist, or the file already exists. If you intended to overwrite the " +
  673. "existing file use fs.writeFile instead.");
  674. return;
  675. }
  676. OutputStream ostream = new FileOutputStream(dest);
  677. ostream.write(RNFetchBlobFS.stringToBytes(data, encoding));
  678. }
  679. callback.invoke(null, path);
  680. } catch(Exception err) {
  681. callback.invoke(err.getLocalizedMessage());
  682. }
  683. }
  684. /**
  685. * Create file for ASCII encoding
  686. * @param path Path of new file.
  687. * @param data Content of new file
  688. * @param callback JS context callback
  689. */
  690. static void createFileASCII(String path, ReadableArray data, Callback callback) {
  691. try {
  692. File dest = new File(path);
  693. if(dest.exists()) {
  694. callback.invoke("failed to create new file at path `" + path + "`, file already exists.");
  695. return;
  696. }
  697. boolean created = dest.createNewFile();
  698. if(!created) {
  699. callback.invoke("failed to create new file at path `" + path + "` because its parent path may not exist");
  700. return;
  701. }
  702. OutputStream ostream = new FileOutputStream(dest);
  703. byte [] chunk = new byte[data.size()];
  704. for(int i =0; i<data.size();i++) {
  705. chunk[i] = (byte) data.getInt(i);
  706. }
  707. ostream.write(chunk);
  708. chunk = null;
  709. callback.invoke(null, path);
  710. } catch(Exception err) {
  711. callback.invoke(err.getLocalizedMessage());
  712. }
  713. }
  714. static void df(Callback callback) {
  715. StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
  716. WritableMap args = Arguments.createMap();
  717. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  718. args.putString("internal_free", String.valueOf(stat.getFreeBytes()));
  719. args.putString("internal_total", String.valueOf(stat.getTotalBytes()));
  720. StatFs statEx = new StatFs(Environment.getExternalStorageDirectory().getPath());
  721. args.putString("external_free", String.valueOf(statEx.getFreeBytes()));
  722. args.putString("external_total", String.valueOf(statEx.getTotalBytes()));
  723. }
  724. callback.invoke(null ,args);
  725. }
  726. /**
  727. * Remove files in session.
  728. * @param paths An array of file paths.
  729. * @param callback JS contest callback
  730. */
  731. static void removeSession(ReadableArray paths, final Callback callback) {
  732. AsyncTask<ReadableArray, Integer, Integer> task = new AsyncTask<ReadableArray, Integer, Integer>() {
  733. @Override
  734. protected Integer doInBackground(ReadableArray ...paths) {
  735. try {
  736. for (int i = 0; i < paths[0].size(); i++) {
  737. File f = new File(paths[0].getString(i));
  738. if (f.exists())
  739. f.delete();
  740. }
  741. callback.invoke(null, true);
  742. } catch(Exception err) {
  743. callback.invoke(err.getLocalizedMessage());
  744. }
  745. return paths[0].size();
  746. }
  747. };
  748. task.execute(paths);
  749. }
  750. /**
  751. * String to byte converter method
  752. * @param data Raw data in string format
  753. * @param encoding Decoder name
  754. * @return Converted data byte array
  755. */
  756. private static byte[] stringToBytes(String data, String encoding) {
  757. if(encoding.equalsIgnoreCase("ascii")) {
  758. return data.getBytes(Charset.forName("US-ASCII"));
  759. }
  760. else if(encoding.toLowerCase().contains("base64")) {
  761. return Base64.decode(data, Base64.NO_WRAP);
  762. }
  763. else if(encoding.equalsIgnoreCase("utf8")) {
  764. return data.getBytes(Charset.forName("UTF-8"));
  765. }
  766. return data.getBytes(Charset.forName("US-ASCII"));
  767. }
  768. /**
  769. * Private method for emit read stream event.
  770. * @param streamName ID of the read stream
  771. * @param event Event name, `data`, `end`, `error`, etc.
  772. * @param data Event data
  773. */
  774. private void emitStreamEvent(String streamName, String event, String data) {
  775. WritableMap eventData = Arguments.createMap();
  776. eventData.putString("event", event);
  777. eventData.putString("detail", data);
  778. this.emitter.emit(streamName, eventData);
  779. }
  780. private void emitStreamEvent(String streamName, String event, WritableArray data) {
  781. WritableMap eventData = Arguments.createMap();
  782. eventData.putString("event", event);
  783. eventData.putArray("detail", data);
  784. this.emitter.emit(streamName, eventData);
  785. }
  786. // TODO : should we remove this ?
  787. void emitFSData(String taskId, String event, String data) {
  788. WritableMap eventData = Arguments.createMap();
  789. eventData.putString("event", event);
  790. eventData.putString("detail", data);
  791. this.emitter.emit("RNFetchBlobStream" + taskId, eventData);
  792. }
  793. /**
  794. * Get input stream of the given path, when the path is a string starts with bundle-assets://
  795. * the stream is created by Assets Manager, otherwise use FileInputStream.
  796. * @param path The file to open stream
  797. * @return InputStream instance
  798. * @throws IOException
  799. */
  800. static InputStream inputStreamFromPath(String path) throws IOException {
  801. if (path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  802. return RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  803. }
  804. return new FileInputStream(new File(path));
  805. }
  806. /**
  807. * Check if the asset or the file exists
  808. * @param path A file path URI string
  809. * @return A boolean value represents if the path exists.
  810. */
  811. static boolean isPathExists(String path) {
  812. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  813. try {
  814. RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  815. } catch (IOException e) {
  816. return false;
  817. }
  818. return true;
  819. }
  820. else {
  821. return new File(path).exists();
  822. }
  823. }
  824. static boolean isAsset(String path) {
  825. if(path != null)
  826. return path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET);
  827. return false;
  828. }
  829. /**
  830. * Normalize the path, remove URI scheme (xxx://) so that we can handle it.
  831. * @param path URI string.
  832. * @return Normalized string
  833. */
  834. static String normalizePath(String path) {
  835. if(path == null)
  836. return null;
  837. if(!path.matches("\\w+\\:.*"))
  838. return path;
  839. if(path.startsWith("file://")) {
  840. return path.replace("file://", "");
  841. }
  842. Uri uri = Uri.parse(path);
  843. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  844. return path;
  845. }
  846. else
  847. return PathResolver.getRealPathFromURI(RNFetchBlob.RCTContext, uri);
  848. }
  849. }