Aucune description

RNFetchBlobFS.java 33KB

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