No Description

RNFetchBlobFS.java 33KB

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