Ingen beskrivning

RNFetchBlobFS.java 35KB

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