Brak opisu

RNFetchBlob.java 15KB

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