Açıklama Yok

RNFetchBlobFS.java 35KB

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