No Description

RNFetchBlob.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. package com.RNFetchBlob;
  2. import android.app.Activity;
  3. import android.app.DownloadManager;
  4. import android.content.Intent;
  5. import android.content.pm.PackageManager;
  6. import android.net.Uri;
  7. import android.os.Build;
  8. import android.support.v4.content.FileProvider;
  9. import android.util.SparseArray;
  10. import com.facebook.react.bridge.ActivityEventListener;
  11. import com.facebook.react.bridge.Callback;
  12. import com.facebook.react.bridge.LifecycleEventListener;
  13. import com.facebook.react.bridge.Promise;
  14. import com.facebook.react.bridge.ReactApplicationContext;
  15. import com.facebook.react.bridge.ReactContextBaseJavaModule;
  16. import com.facebook.react.bridge.ReactMethod;
  17. import com.facebook.react.bridge.ReadableArray;
  18. import com.facebook.react.bridge.ReadableMap;
  19. // Cookies
  20. import com.facebook.react.bridge.WritableMap;
  21. import com.facebook.react.modules.network.ForwardingCookieHandler;
  22. import com.facebook.react.modules.network.CookieJarContainer;
  23. import com.facebook.react.modules.network.OkHttpClientProvider;
  24. import okhttp3.OkHttpClient;
  25. import okhttp3.JavaNetCookieJar;
  26. import java.io.File;
  27. import java.util.HashMap;
  28. import java.util.Map;
  29. import java.util.concurrent.LinkedBlockingQueue;
  30. import java.util.concurrent.ThreadPoolExecutor;
  31. import java.util.concurrent.TimeUnit;
  32. import static android.app.Activity.RESULT_OK;
  33. import static com.RNFetchBlob.RNFetchBlobConst.GET_CONTENT_INTENT;
  34. public class RNFetchBlob extends ReactContextBaseJavaModule {
  35. private final OkHttpClient mClient;
  36. static ReactApplicationContext RCTContext;
  37. private static LinkedBlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();
  38. private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 5000, TimeUnit.MILLISECONDS, taskQueue);
  39. static LinkedBlockingQueue<Runnable> fsTaskQueue = new LinkedBlockingQueue<>();
  40. private static ThreadPoolExecutor fsThreadPool = new ThreadPoolExecutor(2, 10, 5000, TimeUnit.MILLISECONDS, taskQueue);
  41. private static boolean ActionViewVisible = false;
  42. private static SparseArray<Promise> promiseTable = new SparseArray<>();
  43. public RNFetchBlob(ReactApplicationContext reactContext) {
  44. super(reactContext);
  45. mClient = OkHttpClientProvider.getOkHttpClient();
  46. ForwardingCookieHandler mCookieHandler = new ForwardingCookieHandler(reactContext);
  47. CookieJarContainer mCookieJarContainer = (CookieJarContainer) mClient.cookieJar();
  48. mCookieJarContainer.setCookieJar(new JavaNetCookieJar(mCookieHandler));
  49. RCTContext = reactContext;
  50. reactContext.addActivityEventListener(new ActivityEventListener() {
  51. @Override
  52. public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
  53. if(requestCode == GET_CONTENT_INTENT && resultCode == RESULT_OK) {
  54. Uri d = data.getData();
  55. promiseTable.get(GET_CONTENT_INTENT).resolve(d.toString());
  56. promiseTable.remove(GET_CONTENT_INTENT);
  57. }
  58. }
  59. @Override
  60. public void onNewIntent(Intent intent) {
  61. }
  62. });
  63. }
  64. @Override
  65. public String getName() {
  66. return "RNFetchBlob";
  67. }
  68. @Override
  69. public Map<String, Object> getConstants() {
  70. return RNFetchBlobFS.getSystemfolders(this.getReactApplicationContext());
  71. }
  72. @ReactMethod
  73. public void createFile(final String path, final String content, final String encode, final Promise promise) {
  74. threadPool.execute(new Runnable() {
  75. @Override
  76. public void run() {
  77. RNFetchBlobFS.createFile(path, content, encode, promise);
  78. }
  79. });
  80. }
  81. @ReactMethod
  82. public void createFileASCII(final String path, final ReadableArray dataArray, final Promise promise) {
  83. threadPool.execute(new Runnable() {
  84. @Override
  85. public void run() {
  86. RNFetchBlobFS.createFileASCII(path, dataArray, promise);
  87. }
  88. });
  89. }
  90. @ReactMethod
  91. public void actionViewIntent(String path, String mime, final Promise promise) {
  92. try {
  93. Uri uriForFile = FileProvider.getUriForFile(getCurrentActivity(),
  94. this.getReactApplicationContext().getPackageName() + ".provider", new File(path));
  95. if (Build.VERSION.SDK_INT >= 24) {
  96. // Create the intent with data and type
  97. Intent intent = new Intent(Intent.ACTION_VIEW)
  98. .setDataAndType(uriForFile, mime);
  99. // Set flag to give temporary permission to external app to use FileProvider
  100. intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  101. // All the activity to be opened outside of an activity
  102. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  103. // Validate that the device can open the file
  104. PackageManager pm = getCurrentActivity().getPackageManager();
  105. if (intent.resolveActivity(pm) != null) {
  106. this.getReactApplicationContext().startActivity(intent);
  107. }
  108. } else {
  109. Intent intent = new Intent(Intent.ACTION_VIEW)
  110. .setDataAndType(Uri.parse("file://" + path), mime).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  111. this.getReactApplicationContext().startActivity(intent);
  112. }
  113. ActionViewVisible = true;
  114. final LifecycleEventListener listener = new LifecycleEventListener() {
  115. @Override
  116. public void onHostResume() {
  117. if(ActionViewVisible)
  118. promise.resolve(null);
  119. RCTContext.removeLifecycleEventListener(this);
  120. }
  121. @Override
  122. public void onHostPause() {
  123. }
  124. @Override
  125. public void onHostDestroy() {
  126. }
  127. };
  128. RCTContext.addLifecycleEventListener(listener);
  129. } catch(Exception ex) {
  130. promise.reject("EUNSPECIFIED", ex.getLocalizedMessage());
  131. }
  132. }
  133. @ReactMethod
  134. public void writeArrayChunk(final String streamId, final ReadableArray dataArray, final Callback callback) {
  135. RNFetchBlobFS.writeArrayChunk(streamId, dataArray, callback);
  136. }
  137. @ReactMethod
  138. public void unlink(String path, Callback callback) {
  139. RNFetchBlobFS.unlink(path, callback);
  140. }
  141. @ReactMethod
  142. public void mkdir(String path, Promise promise) {
  143. RNFetchBlobFS.mkdir(path, promise);
  144. }
  145. @ReactMethod
  146. public void exists(String path, Callback callback) {
  147. RNFetchBlobFS.exists(path, callback);
  148. }
  149. @ReactMethod
  150. public void cp(final String path, final String dest, final Callback callback) {
  151. threadPool.execute(new Runnable() {
  152. @Override
  153. public void run() {
  154. RNFetchBlobFS.cp(path, dest, callback);
  155. }
  156. });
  157. }
  158. @ReactMethod
  159. public void mv(String path, String dest, Callback callback) {
  160. RNFetchBlobFS.mv(path, dest, callback);
  161. }
  162. @ReactMethod
  163. public void ls(String path, Promise promise) {
  164. RNFetchBlobFS.ls(path, promise);
  165. }
  166. @ReactMethod
  167. public void writeStream(String path, String encode, boolean append, Callback callback) {
  168. new RNFetchBlobFS(this.getReactApplicationContext()).writeStream(path, encode, append, callback);
  169. }
  170. @ReactMethod
  171. public void writeChunk(String streamId, String data, Callback callback) {
  172. RNFetchBlobFS.writeChunk(streamId, data, callback);
  173. }
  174. @ReactMethod
  175. public void closeStream(String streamId, Callback callback) {
  176. RNFetchBlobFS.closeStream(streamId, callback);
  177. }
  178. @ReactMethod
  179. public void removeSession(ReadableArray paths, Callback callback) {
  180. RNFetchBlobFS.removeSession(paths, callback);
  181. }
  182. @ReactMethod
  183. public void readFile(final String path, final String encoding, final Promise promise) {
  184. threadPool.execute(new Runnable() {
  185. @Override
  186. public void run() {
  187. RNFetchBlobFS.readFile(path, encoding, promise);
  188. }
  189. });
  190. }
  191. @ReactMethod
  192. public void writeFileArray(final String path, final ReadableArray data, final boolean append, final Promise promise) {
  193. threadPool.execute(new Runnable() {
  194. @Override
  195. public void run() {
  196. RNFetchBlobFS.writeFile(path, data, append, promise);
  197. }
  198. });
  199. }
  200. @ReactMethod
  201. public void writeFile(final String path, final String encoding, final String data, final boolean append, final Promise promise) {
  202. threadPool.execute(new Runnable() {
  203. @Override
  204. public void run() {
  205. RNFetchBlobFS.writeFile(path, encoding, data, append, promise);
  206. }
  207. });
  208. }
  209. @ReactMethod
  210. public void lstat(String path, Callback callback) {
  211. RNFetchBlobFS.lstat(path, callback);
  212. }
  213. @ReactMethod
  214. public void stat(String path, Callback callback) {
  215. RNFetchBlobFS.stat(path, callback);
  216. }
  217. @ReactMethod
  218. public void scanFile(final ReadableArray pairs, final Callback callback) {
  219. final ReactApplicationContext ctx = this.getReactApplicationContext();
  220. threadPool.execute(new Runnable() {
  221. @Override
  222. public void run() {
  223. int size = pairs.size();
  224. String [] p = new String[size];
  225. String [] m = new String[size];
  226. for(int i=0;i<size;i++) {
  227. ReadableMap pair = pairs.getMap(i);
  228. if(pair.hasKey("path")) {
  229. p[i] = pair.getString("path");
  230. if(pair.hasKey("mime"))
  231. m[i] = pair.getString("mime");
  232. else
  233. m[i] = null;
  234. }
  235. }
  236. new RNFetchBlobFS(ctx).scanFile(p, m, callback);
  237. }
  238. });
  239. }
  240. @ReactMethod
  241. public void hash(final String path, final String algorithm, final Promise promise) {
  242. threadPool.execute(new Runnable() {
  243. @Override
  244. public void run() {
  245. RNFetchBlobFS.hash(path, algorithm, promise);
  246. }
  247. });
  248. }
  249. /**
  250. * @param path Stream file path
  251. * @param encoding Stream encoding, should be one of `base64`, `ascii`, and `utf8`
  252. * @param bufferSize Stream buffer size, default to 4096 or 4095(base64).
  253. */
  254. @ReactMethod
  255. public void readStream(final String path, final String encoding, final int bufferSize, final int tick, final String streamId) {
  256. final ReactApplicationContext ctx = this.getReactApplicationContext();
  257. fsThreadPool.execute(new Runnable() {
  258. @Override
  259. public void run() {
  260. RNFetchBlobFS fs = new RNFetchBlobFS(ctx);
  261. fs.readStream(path, encoding, bufferSize, tick, streamId);
  262. }
  263. });
  264. }
  265. @ReactMethod
  266. public void cancelRequest(String taskId, Callback callback) {
  267. try {
  268. RNFetchBlobReq.cancelTask(taskId);
  269. callback.invoke(null, taskId);
  270. } catch (Exception ex) {
  271. callback.invoke(ex.getLocalizedMessage(), null);
  272. }
  273. }
  274. @ReactMethod
  275. public void slice(String src, String dest, int start, int end, Promise promise) {
  276. RNFetchBlobFS.slice(src, dest, start, end, "", promise);
  277. }
  278. @ReactMethod
  279. public void enableProgressReport(String taskId, int interval, int count) {
  280. RNFetchBlobProgressConfig config = new RNFetchBlobProgressConfig(true, interval, count, RNFetchBlobProgressConfig.ReportType.Download);
  281. RNFetchBlobReq.progressReport.put(taskId, config);
  282. }
  283. @ReactMethod
  284. public void df(final Callback callback) {
  285. fsThreadPool.execute(new Runnable() {
  286. @Override
  287. public void run() {
  288. RNFetchBlobFS.df(callback);
  289. }
  290. });
  291. }
  292. @ReactMethod
  293. public void enableUploadProgressReport(String taskId, int interval, int count) {
  294. RNFetchBlobProgressConfig config = new RNFetchBlobProgressConfig(true, interval, count, RNFetchBlobProgressConfig.ReportType.Upload);
  295. RNFetchBlobReq.uploadProgressReport.put(taskId, config);
  296. }
  297. @ReactMethod
  298. public void fetchBlob(ReadableMap options, String taskId, String method, String url, ReadableMap headers, String body, final Callback callback) {
  299. new RNFetchBlobReq(options, taskId, method, url, headers, body, null, mClient, callback).run();
  300. }
  301. @ReactMethod
  302. public void fetchBlobForm(ReadableMap options, String taskId, String method, String url, ReadableMap headers, ReadableArray body, final Callback callback) {
  303. new RNFetchBlobReq(options, taskId, method, url, headers, null, body, mClient, callback).run();
  304. }
  305. @ReactMethod
  306. public void getContentIntent(String mime, Promise promise) {
  307. Intent i = new Intent(Intent.ACTION_GET_CONTENT);
  308. if(mime != null)
  309. i.setType(mime);
  310. else
  311. i.setType("*/*");
  312. promiseTable.put(GET_CONTENT_INTENT, promise);
  313. this.getReactApplicationContext().startActivityForResult(i, GET_CONTENT_INTENT, null);
  314. }
  315. @ReactMethod
  316. public void addCompleteDownload (ReadableMap config, Promise promise) {
  317. DownloadManager dm = (DownloadManager) RCTContext.getSystemService(RCTContext.DOWNLOAD_SERVICE);
  318. if (config == null || !config.hasKey("path"))
  319. {
  320. promise.reject("EINVAL", "RNFetchblob.addCompleteDownload config or path missing.");
  321. return;
  322. }
  323. String path = RNFetchBlobFS.normalizePath(config.getString("path"));
  324. if(path == null) {
  325. promise.reject("EINVAL", "RNFetchblob.addCompleteDownload can not resolve URI:" + config.getString("path"));
  326. return;
  327. }
  328. try {
  329. WritableMap stat = RNFetchBlobFS.statFile(path);
  330. dm.addCompletedDownload(
  331. config.hasKey("title") ? config.getString("title") : "",
  332. config.hasKey("description") ? config.getString("description") : "",
  333. true,
  334. config.hasKey("mime") ? config.getString("mime") : null,
  335. path,
  336. Long.valueOf(stat.getString("size")),
  337. config.hasKey("showNotification") && config.getBoolean("showNotification")
  338. );
  339. promise.resolve(null);
  340. }
  341. catch(Exception ex) {
  342. promise.reject("EUNSPECIFIED", ex.getLocalizedMessage());
  343. }
  344. }
  345. @ReactMethod
  346. public void getSDCardDir(Promise promise) {
  347. RNFetchBlobFS.getSDCardDir(promise);
  348. }
  349. @ReactMethod
  350. public void getSDCardApplicationDir(Promise promise) {
  351. RNFetchBlobFS.getSDCardApplicationDir(this.getReactApplicationContext(), promise);
  352. }
  353. }