説明なし

RNFetchBlobFS.java 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. package com.RNFetchBlob;
  2. import android.app.LoaderManager;
  3. import android.content.ContentResolver;
  4. import android.content.CursorLoader;
  5. import android.content.res.AssetFileDescriptor;
  6. import android.database.Cursor;
  7. import android.media.MediaScannerConnection;
  8. import android.net.Uri;
  9. import android.os.AsyncTask;
  10. import android.os.Environment;
  11. import android.os.Looper;
  12. import android.provider.MediaStore;
  13. import android.util.Base64;
  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.charset.Charset;
  29. import java.util.HashMap;
  30. import java.util.Map;
  31. import java.util.UUID;
  32. /**
  33. * Created by wkh237 on 2016/5/26.
  34. */
  35. public class RNFetchBlobFS {
  36. ReactApplicationContext mCtx;
  37. DeviceEventManagerModule.RCTDeviceEventEmitter emitter;
  38. String encoding = "base64";
  39. boolean append = false;
  40. OutputStream writeStreamInstance = null;
  41. static HashMap<String, RNFetchBlobFS> fileStreams = new HashMap<>();
  42. RNFetchBlobFS(ReactApplicationContext ctx) {
  43. this.mCtx = ctx;
  44. this.emitter = ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
  45. }
  46. static String getExternalFilePath(ReactApplicationContext ctx, String taskId, RNFetchBlobConfig config) {
  47. if(config.path != null)
  48. return config.path;
  49. else if(config.fileCache && config.appendExt != null)
  50. return RNFetchBlobFS.getTmpPath(ctx, taskId) + "." + config.appendExt;
  51. else
  52. return RNFetchBlobFS.getTmpPath(ctx, taskId);
  53. }
  54. /**
  55. * Write string with encoding to file
  56. * @param path Destination file path.
  57. * @param encoding Encoding of the string.
  58. * @param data Array passed from JS context.
  59. * @param promise
  60. */
  61. static public void writeFile(String path, String encoding, String data, final boolean append, final Promise promise) {
  62. AsyncTask<String, Integer, Integer> task = new AsyncTask<String, Integer, Integer>() {
  63. @Override
  64. protected Integer doInBackground(String... args) {
  65. try {
  66. String path = args[0];
  67. String encoding = args[1];
  68. String data = args[2];
  69. File f = new File(path);
  70. File dir = f.getParentFile();
  71. if(!dir.exists())
  72. dir.mkdirs();
  73. FileOutputStream fout = new FileOutputStream(f, append);
  74. fout.write(stringToBytes(data, encoding));
  75. fout.close();
  76. promise.resolve(Arguments.createArray());
  77. } catch (Exception e) {
  78. promise.reject("RNFetchBlob writeFileError", e.getLocalizedMessage());
  79. }
  80. return null;
  81. }
  82. };
  83. task.execute(path, encoding, data);
  84. }
  85. /**
  86. * Write array of bytes into file
  87. * @param path Destination file path.
  88. * @param data Array passed from JS context.
  89. * @param promise
  90. */
  91. static public void writeFile(String path, ReadableArray data, final boolean append, final Promise promise) {
  92. AsyncTask<Object, Void, Void> task = new AsyncTask<Object, Void, Void>() {
  93. @Override
  94. protected Void doInBackground(Object... args) {
  95. try {
  96. String path = (String)args[0];
  97. ReadableArray data = (ReadableArray) args[1];
  98. File f = new File(path);
  99. File dir = f.getParentFile();
  100. if(!dir.exists())
  101. dir.mkdirs();
  102. FileOutputStream os = new FileOutputStream(f, append);
  103. byte [] bytes = new byte[data.size()];
  104. for(int i=0;i<data.size();i++) {
  105. bytes[i] = (byte) data.getInt(i);
  106. }
  107. os.write(bytes);
  108. os.close();
  109. promise.resolve(null);
  110. } catch (Exception e) {
  111. promise.reject("RNFetchBlob writeFileError", e.getLocalizedMessage());
  112. }
  113. return null;
  114. }
  115. };
  116. task.execute(path, data);
  117. }
  118. /**
  119. * Read file with a buffer that has the same size as the target file.
  120. * @param path Path of the file.
  121. * @param encoding Encoding of read stream.
  122. * @param promise
  123. */
  124. static public void readFile(String path, String encoding, final Promise promise ) {
  125. path = normalizePath(path);
  126. AsyncTask<String, Integer, Integer> task = new AsyncTask<String, Integer, Integer>() {
  127. @Override
  128. protected Integer doInBackground(String... strings) {
  129. try {
  130. String path = strings[0];
  131. String encoding = strings[1];
  132. byte[] bytes;
  133. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  134. String assetName = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  135. long length = RNFetchBlob.RCTContext.getAssets().openFd(assetName).getLength();
  136. bytes = new byte[(int) length];
  137. InputStream in = RNFetchBlob.RCTContext.getAssets().open(assetName);
  138. in.read(bytes, 0, (int) length);
  139. in.close();
  140. }
  141. else {
  142. File f = new File(path);
  143. int length = (int) f.length();
  144. bytes = new byte[length];
  145. FileInputStream in = new FileInputStream(f);
  146. in.read(bytes);
  147. in.close();
  148. }
  149. switch (encoding.toLowerCase()) {
  150. case "base64" :
  151. promise.resolve(Base64.encodeToString(bytes, Base64.NO_WRAP));
  152. break;
  153. case "ascii" :
  154. WritableArray asciiResult = Arguments.createArray();
  155. for(byte b : bytes) {
  156. asciiResult.pushInt((int)b);
  157. }
  158. promise.resolve(asciiResult);
  159. break;
  160. case "utf8" :
  161. promise.resolve(new String(bytes));
  162. break;
  163. default:
  164. promise.resolve(new String(bytes));
  165. break;
  166. }
  167. }
  168. catch(Exception err) {
  169. promise.reject("ReadFile Error", err.getLocalizedMessage());
  170. }
  171. return null;
  172. }
  173. };
  174. task.execute(path, encoding);
  175. }
  176. /**
  177. * Static method that returns system folders to JS context
  178. * @param ctx React Native application context
  179. */
  180. static public Map<String, Object> getSystemfolders(ReactApplicationContext ctx) {
  181. Map<String, Object> res = new HashMap<>();
  182. res.put("DocumentDir", ctx.getFilesDir().getAbsolutePath());
  183. res.put("CacheDir", ctx.getCacheDir().getAbsolutePath());
  184. res.put("DCIMDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath());
  185. res.put("PictureDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
  186. res.put("MusicDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath());
  187. res.put("DownloadDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
  188. res.put("MovieDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath());
  189. res.put("RingtoneDir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES).getAbsolutePath());
  190. return res;
  191. }
  192. /**
  193. * Static method that returns a temp file path
  194. * @param ctx React Native application context
  195. * @param taskId An unique string for identify
  196. * @return
  197. */
  198. static public String getTmpPath(ReactApplicationContext ctx, String taskId) {
  199. return ctx.getFilesDir() + "/RNFetchBlobTmp_" + taskId;
  200. }
  201. /**
  202. * Create a file stream for read
  203. * @param path File stream target path
  204. * @param encoding File stream decoder, should be one of `base64`, `utf8`, `ascii`
  205. * @param bufferSize Buffer size of read stream, default to 4096 (4095 when encode is `base64`)
  206. */
  207. public void readStream( String path, String encoding, int bufferSize) {
  208. path = normalizePath(path);
  209. AsyncTask<String, Integer, Integer> task = new AsyncTask<String, Integer, Integer>() {
  210. @Override
  211. protected Integer doInBackground(String ... args) {
  212. String path = args[0];
  213. String encoding = args[1];
  214. int bufferSize = Integer.parseInt(args[2]);
  215. String eventName = "RNFetchBlobStream+" + path;
  216. try {
  217. int chunkSize = encoding.equalsIgnoreCase("base64") ? 4095 : 4096;
  218. if(bufferSize > 0)
  219. chunkSize = bufferSize;
  220. InputStream fs;
  221. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  222. fs = RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  223. }
  224. else {
  225. fs = new FileInputStream(new File(path));
  226. }
  227. byte[] buffer = new byte[chunkSize];
  228. int cursor = 0;
  229. boolean error = false;
  230. if (encoding.equalsIgnoreCase("utf8")) {
  231. while ((cursor = fs.read(buffer)) != -1) {
  232. String chunk = new String(buffer, 0, cursor, "UTF-8");
  233. emitStreamEvent(eventName, "data", chunk);
  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(eventName, "data", chunk);
  243. }
  244. } else if (encoding.equalsIgnoreCase("base64")) {
  245. while ((cursor = fs.read(buffer)) != -1) {
  246. if(cursor < chunkSize) {
  247. byte [] copy = new byte[cursor];
  248. for(int i =0;i<cursor;i++) {
  249. copy[i] = buffer[i];
  250. }
  251. emitStreamEvent(eventName, "data", Base64.encodeToString(copy, Base64.NO_WRAP));
  252. }
  253. else
  254. emitStreamEvent(eventName, "data", Base64.encodeToString(buffer, Base64.NO_WRAP));
  255. }
  256. } else {
  257. String msg = "unrecognized encoding `" + encoding + "`";
  258. emitStreamEvent(eventName, "error", msg);
  259. error = true;
  260. }
  261. if(!error)
  262. emitStreamEvent(eventName, "end", "");
  263. fs.close();
  264. buffer = null;
  265. } catch (Exception err) {
  266. emitStreamEvent(eventName, "error", err.getLocalizedMessage());
  267. }
  268. return null;
  269. }
  270. };
  271. task.execute(path, encoding, String.valueOf(bufferSize));
  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. RNFetchBlobFS fs = fileStreams.get(streamId);
  323. OutputStream stream = fs.writeStreamInstance;
  324. byte [] chunk = new byte[data.size()];
  325. for(int i =0; i< data.size();i++) {
  326. chunk[i] = (byte) data.getInt(i);
  327. }
  328. try {
  329. stream.write(chunk);
  330. callback.invoke();
  331. chunk = null;
  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. boolean success = new File(path).delete();
  360. callback.invoke( null, success);
  361. } catch(Exception err) {
  362. if(err != null)
  363. callback.invoke(err.getLocalizedMessage());
  364. }
  365. }
  366. /**
  367. * Make a folder
  368. * @param path Source path
  369. * @param callback JS context callback
  370. */
  371. static void mkdir(String path, Callback callback) {
  372. File dest = new File(path);
  373. if(dest.exists()) {
  374. callback.invoke("mkdir error: failed to create folder at `" + path + "` folder already exists");
  375. return;
  376. }
  377. dest.mkdirs();
  378. callback.invoke();
  379. }
  380. /**
  381. * Copy file to destination path
  382. * @param path Source path
  383. * @param dest Target path
  384. * @param callback JS context callback
  385. */
  386. static void cp(String path, String dest, Callback callback) {
  387. path = normalizePath(path);
  388. InputStream in = null;
  389. OutputStream out = null;
  390. try {
  391. if(!isPathExists(path)) {
  392. callback.invoke("cp error: source file at path`" + path + "` not exists");
  393. return;
  394. }
  395. if(!new File(dest).exists())
  396. new File(dest).createNewFile();
  397. in = inputStreamFromPath(path);
  398. out = new FileOutputStream(dest);
  399. byte[] buf = new byte[1024];
  400. int len;
  401. while ((len = in.read(buf)) > 0) {
  402. out.write(buf, 0, len);
  403. }
  404. } catch (Exception err) {
  405. if(err != null)
  406. callback.invoke(err.getLocalizedMessage());
  407. } finally {
  408. try {
  409. in.close();
  410. out.close();
  411. callback.invoke();
  412. } catch (IOException e) {
  413. callback.invoke(e.getLocalizedMessage());
  414. }
  415. }
  416. }
  417. /**
  418. * Move file
  419. * @param path Source file path
  420. * @param dest Destination file path
  421. * @param callback JS context callback
  422. */
  423. static void mv(String path, String dest, Callback callback) {
  424. File src = new File(path);
  425. if(!src.exists()) {
  426. callback.invoke("mv error: source file at path `" + path + "` does not exists");
  427. return;
  428. }
  429. src.renameTo(new File(dest));
  430. callback.invoke();
  431. }
  432. /**
  433. * Check if the path exists, also check if it is a folder when exists.
  434. * @param path Path to check
  435. * @param callback JS context callback
  436. */
  437. static void exists(String path, Callback callback) {
  438. path = normalizePath(path);
  439. if(isAsset(path)) {
  440. try {
  441. String filename = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  442. AssetFileDescriptor fd = RNFetchBlob.RCTContext.getAssets().openFd(filename);
  443. callback.invoke(true, false);
  444. } catch (IOException e) {
  445. callback.invoke(false, false);
  446. }
  447. }
  448. else {
  449. boolean exist = new File(path).exists();
  450. boolean isDir = new File(path).isDirectory();
  451. callback.invoke(exist, isDir);
  452. }
  453. }
  454. /**
  455. * List content of folder
  456. * @param path Target folder
  457. * @param callback JS context callback
  458. */
  459. static void ls(String path, Callback callback) {
  460. path = normalizePath(path);
  461. File src = new File(path);
  462. if (!src.exists() || !src.isDirectory()) {
  463. callback.invoke("ls error: failed to list path `" + path + "` for it is not exist or it is not a folder");
  464. return;
  465. }
  466. String[] files = new File(path).list();
  467. WritableArray arg = Arguments.createArray();
  468. for (String i : files) {
  469. arg.pushString(i);
  470. }
  471. callback.invoke(null, arg);
  472. }
  473. static void lstat(String path, final Callback callback) {
  474. path = normalizePath(path);
  475. new AsyncTask<String, Integer, Integer>() {
  476. @Override
  477. protected Integer doInBackground(String ...args) {
  478. WritableArray res = Arguments.createArray();
  479. File src = new File(args[0]);
  480. if(!src.exists()) {
  481. callback.invoke("lstat error: failed to list path `" + args[0] + "` for it is not exist or it is not a folder");
  482. return 0;
  483. }
  484. if(src.isDirectory()) {
  485. String [] files = src.list();
  486. for(String p : files) {
  487. res.pushMap(statFile ( src.getPath() + "/" + p));
  488. }
  489. }
  490. else {
  491. res.pushMap(statFile(src.getAbsolutePath()));
  492. }
  493. callback.invoke(null, res);
  494. return 0;
  495. }
  496. }.execute(path);
  497. }
  498. /**
  499. * show status of a file or directory
  500. * @param path
  501. * @param callback
  502. */
  503. static void stat(String path, Callback callback) {
  504. try {
  505. WritableMap result = statFile(path);
  506. if(result == null)
  507. callback.invoke("stat error: failed to list path `" + path + "` for it is not exist or it is not a folder", null);
  508. else
  509. callback.invoke(null, result);
  510. } catch(Exception err) {
  511. callback.invoke(err.getLocalizedMessage());
  512. }
  513. }
  514. /**
  515. * Basic stat method
  516. * @param path
  517. * @return Stat result of a file or path
  518. */
  519. static WritableMap statFile(String path) {
  520. try {
  521. path = normalizePath(path);
  522. WritableMap stat = Arguments.createMap();
  523. if(isAsset(path)) {
  524. String name = path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
  525. AssetFileDescriptor fd = RNFetchBlob.RCTContext.getAssets().openFd(name);
  526. stat.putString("filename", name);
  527. stat.putString("path", path);
  528. stat.putString("type", "asset");
  529. stat.putString("size", String.valueOf(fd.getLength()));
  530. stat.putString("lastModified", "0");
  531. }
  532. else {
  533. File target = new File(path);
  534. if (!target.exists()) {
  535. return null;
  536. }
  537. stat.putString("filename", target.getName());
  538. stat.putString("path", target.getPath());
  539. stat.putString("type", target.isDirectory() ? "directory" : "file");
  540. stat.putString("size", String.valueOf(target.length()));
  541. String lastModified = String.valueOf(target.lastModified());
  542. stat.putString("lastModified", lastModified);
  543. }
  544. return stat;
  545. } catch(Exception err) {
  546. return null;
  547. }
  548. }
  549. /**
  550. * Media scanner scan file
  551. * @param path
  552. * @param mimes
  553. * @param callback
  554. */
  555. void scanFile(String [] path, String[] mimes, final Callback callback) {
  556. try {
  557. MediaScannerConnection.scanFile(mCtx, path, mimes, new MediaScannerConnection.OnScanCompletedListener() {
  558. @Override
  559. public void onScanCompleted(String s, Uri uri) {
  560. callback.invoke(null, true);
  561. }
  562. });
  563. } catch(Exception err) {
  564. callback.invoke(err.getLocalizedMessage(), null);
  565. }
  566. }
  567. /**
  568. * Create new file at path
  569. * @param path
  570. * @param data
  571. * @param encoding
  572. * @param callback
  573. */
  574. static void createFile(String path, String data, String encoding, Callback callback) {
  575. try {
  576. File dest = new File(path);
  577. boolean created = dest.createNewFile();
  578. if(!created) {
  579. callback.invoke("create file error: failed to create file at path `" + path + "` for its parent path may not exists");
  580. return;
  581. }
  582. OutputStream ostream = new FileOutputStream(dest);
  583. ostream.write(RNFetchBlobFS.stringToBytes(data, encoding));
  584. callback.invoke(null, path);
  585. } catch(Exception err) {
  586. callback.invoke(err.getLocalizedMessage());
  587. }
  588. }
  589. /**
  590. * Create file for ASCII encoding
  591. * @param path Path of new file.
  592. * @param data Content of new file
  593. * @param callback JS context callback
  594. */
  595. static void createFileASCII(String path, ReadableArray data, Callback callback) {
  596. try {
  597. File dest = new File(path);
  598. if(dest.exists()) {
  599. callback.invoke("create file error: failed to create file at path `" + path + "`, file already exists.");
  600. return;
  601. }
  602. boolean created = dest.createNewFile();
  603. if(!created) {
  604. callback.invoke("create file error: failed to create file at path `" + path + "` for its parent path may not exists");
  605. return;
  606. }
  607. OutputStream ostream = new FileOutputStream(dest);
  608. byte [] chunk = new byte[data.size()];
  609. for(int i =0; i<data.size();i++) {
  610. chunk[i] = (byte) data.getInt(i);
  611. }
  612. ostream.write(chunk);
  613. chunk = null;
  614. callback.invoke(null, path);
  615. } catch(Exception err) {
  616. callback.invoke(err.getLocalizedMessage());
  617. }
  618. }
  619. /**
  620. * Remove files in session.
  621. * @param paths An array of file paths.
  622. * @param callback JS contest callback
  623. */
  624. static void removeSession(ReadableArray paths, final Callback callback) {
  625. AsyncTask<ReadableArray, Integer, Integer> task = new AsyncTask<ReadableArray, Integer, Integer>() {
  626. @Override
  627. protected Integer doInBackground(ReadableArray ...paths) {
  628. try {
  629. for (int i = 0; i < paths[0].size(); i++) {
  630. File f = new File(paths[0].getString(i));
  631. if (f.exists())
  632. f.delete();
  633. }
  634. callback.invoke(null, true);
  635. } catch(Exception err) {
  636. callback.invoke(err.getLocalizedMessage());
  637. }
  638. return paths[0].size();
  639. }
  640. };
  641. task.execute(paths);
  642. }
  643. /**
  644. * String to byte converter method
  645. * @param data Raw data in string format
  646. * @param encoding Decoder name
  647. * @return Converted data byte array
  648. */
  649. private static byte[] stringToBytes(String data, String encoding) {
  650. if(encoding.equalsIgnoreCase("ascii")) {
  651. return data.getBytes(Charset.forName("US-ASCII"));
  652. }
  653. else if(encoding.equalsIgnoreCase("base64")) {
  654. return Base64.decode(data, Base64.NO_WRAP);
  655. }
  656. else if(encoding.equalsIgnoreCase("utf8")) {
  657. return data.getBytes(Charset.forName("UTF-8"));
  658. }
  659. return data.getBytes(Charset.forName("US-ASCII"));
  660. }
  661. /**
  662. * Private method for emit read stream event.
  663. * @param streamName ID of the read stream
  664. * @param event Event name, `data`, `end`, `error`, etc.
  665. * @param data Event data
  666. */
  667. void emitStreamEvent(String streamName, String event, String data) {
  668. WritableMap eventData = Arguments.createMap();
  669. eventData.putString("event", event);
  670. eventData.putString("detail", data);
  671. this.emitter.emit(streamName, eventData);
  672. }
  673. void emitStreamEvent(String streamName, String event, WritableArray data) {
  674. WritableMap eventData = Arguments.createMap();
  675. eventData.putString("event", event);
  676. eventData.putArray("detail", data);
  677. this.emitter.emit(streamName, eventData);
  678. }
  679. // TODO : should we remove this ?
  680. void emitFSData(String taskId, String event, String data) {
  681. WritableMap eventData = Arguments.createMap();
  682. eventData.putString("event", event);
  683. eventData.putString("detail", data);
  684. this.emitter.emit("RNFetchBlobStream" + taskId, eventData);
  685. }
  686. /**
  687. * Get input stream of the given path, when the path is a string starts with bundle-assets://
  688. * the stream is created by Assets Manager, otherwise use FileInputStream.
  689. * @param path
  690. * @return
  691. * @throws IOException
  692. */
  693. static InputStream inputStreamFromPath(String path) throws IOException {
  694. if (path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  695. return RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  696. }
  697. return new FileInputStream(new File(path));
  698. }
  699. /**
  700. * Check if the asset or the file exists
  701. * @param path
  702. * @return
  703. */
  704. static boolean isPathExists(String path) {
  705. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  706. try {
  707. RNFetchBlob.RCTContext.getAssets().open(path.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, ""));
  708. } catch (IOException e) {
  709. return false;
  710. }
  711. return true;
  712. }
  713. else {
  714. return new File(path).exists();
  715. }
  716. }
  717. public static boolean isAsset(String path) {
  718. return path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET);
  719. }
  720. public static String normalizePath(String path) {
  721. if(path.startsWith(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET)) {
  722. return path;
  723. }
  724. else if (path.startsWith(RNFetchBlobConst.FILE_PREFIX_CONTENT)) {
  725. String filePath = null;
  726. Uri uri = Uri.parse(path);
  727. if (uri != null && "content".equals(uri.getScheme())) {
  728. ContentResolver resolver = RNFetchBlob.RCTContext.getContentResolver();
  729. Cursor cursor = resolver.query(uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null);
  730. cursor.moveToFirst();
  731. filePath = cursor.getString(0);
  732. cursor.close();
  733. } else {
  734. filePath = uri.getPath();
  735. }
  736. return filePath;
  737. }
  738. return path;
  739. }
  740. }