Geen omschrijving

RNFetchBlob.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. // Validate that the device can open the file
  101. PackageManager pm = getCurrentActivity().getPackageManager();
  102. if (intent.resolveActivity(pm) != null) {
  103. this.getReactApplicationContext().startActivity(intent);
  104. }
  105. } else {
  106. Intent intent = new Intent(Intent.ACTION_VIEW)
  107. .setDataAndType(Uri.parse("file://" + path), mime).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  108. this.getReactApplicationContext().startActivity(intent);
  109. }
  110. ActionViewVisible = true;
  111. final LifecycleEventListener listener = new LifecycleEventListener() {
  112. @Override
  113. public void onHostResume() {
  114. if(ActionViewVisible)
  115. promise.resolve(null);
  116. RCTContext.removeLifecycleEventListener(this);
  117. }
  118. @Override
  119. public void onHostPause() {
  120. }
  121. @Override
  122. public void onHostDestroy() {
  123. }
  124. };
  125. RCTContext.addLifecycleEventListener(listener);
  126. } catch(Exception ex) {
  127. promise.reject("EUNSPECIFIED", ex.getLocalizedMessage());
  128. }
  129. }
  130. @ReactMethod
  131. public void writeArrayChunk(final String streamId, final ReadableArray dataArray, final Callback callback) {
  132. RNFetchBlobFS.writeArrayChunk(streamId, dataArray, callback);
  133. }
  134. @ReactMethod
  135. public void unlink(String path, Callback callback) {
  136. RNFetchBlobFS.unlink(path, callback);
  137. }
  138. @ReactMethod
  139. public void mkdir(String path, Promise promise) {
  140. RNFetchBlobFS.mkdir(path, promise);
  141. }
  142. @ReactMethod
  143. public void exists(String path, Callback callback) {
  144. RNFetchBlobFS.exists(path, callback);
  145. }
  146. @ReactMethod
  147. public void cp(final String path, final String dest, final Callback callback) {
  148. threadPool.execute(new Runnable() {
  149. @Override
  150. public void run() {
  151. RNFetchBlobFS.cp(path, dest, callback);
  152. }
  153. });
  154. }
  155. @ReactMethod
  156. public void mv(String path, String dest, Callback callback) {
  157. RNFetchBlobFS.mv(path, dest, callback);
  158. }
  159. @ReactMethod
  160. public void ls(String path, Promise promise) {
  161. RNFetchBlobFS.ls(path, promise);
  162. }
  163. @ReactMethod
  164. public void writeStream(String path, String encode, boolean append, Callback callback) {
  165. new RNFetchBlobFS(this.getReactApplicationContext()).writeStream(path, encode, append, callback);
  166. }
  167. @ReactMethod
  168. public void writeChunk(String streamId, String data, Callback callback) {
  169. RNFetchBlobFS.writeChunk(streamId, data, callback);
  170. }
  171. @ReactMethod
  172. public void closeStream(String streamId, Callback callback) {
  173. RNFetchBlobFS.closeStream(streamId, callback);
  174. }
  175. @ReactMethod
  176. public void removeSession(ReadableArray paths, Callback callback) {
  177. RNFetchBlobFS.removeSession(paths, callback);
  178. }
  179. @ReactMethod
  180. public void readFile(final String path, final String encoding, final Promise promise) {
  181. threadPool.execute(new Runnable() {
  182. @Override
  183. public void run() {
  184. RNFetchBlobFS.readFile(path, encoding, promise);
  185. }
  186. });
  187. }
  188. @ReactMethod
  189. public void writeFileArray(final String path, final ReadableArray data, final boolean append, final Promise promise) {
  190. threadPool.execute(new Runnable() {
  191. @Override
  192. public void run() {
  193. RNFetchBlobFS.writeFile(path, data, append, promise);
  194. }
  195. });
  196. }
  197. @ReactMethod
  198. public void writeFile(final String path, final String encoding, final String data, final boolean append, final Promise promise) {
  199. threadPool.execute(new Runnable() {
  200. @Override
  201. public void run() {
  202. RNFetchBlobFS.writeFile(path, encoding, data, append, promise);
  203. }
  204. });
  205. }
  206. @ReactMethod
  207. public void lstat(String path, Callback callback) {
  208. RNFetchBlobFS.lstat(path, callback);
  209. }
  210. @ReactMethod
  211. public void stat(String path, Callback callback) {
  212. RNFetchBlobFS.stat(path, callback);
  213. }
  214. @ReactMethod
  215. public void scanFile(final ReadableArray pairs, final Callback callback) {
  216. final ReactApplicationContext ctx = this.getReactApplicationContext();
  217. threadPool.execute(new Runnable() {
  218. @Override
  219. public void run() {
  220. int size = pairs.size();
  221. String [] p = new String[size];
  222. String [] m = new String[size];
  223. for(int i=0;i<size;i++) {
  224. ReadableMap pair = pairs.getMap(i);
  225. if(pair.hasKey("path")) {
  226. p[i] = pair.getString("path");
  227. if(pair.hasKey("mime"))
  228. m[i] = pair.getString("mime");
  229. else
  230. m[i] = null;
  231. }
  232. }
  233. new RNFetchBlobFS(ctx).scanFile(p, m, callback);
  234. }
  235. });
  236. }
  237. @ReactMethod
  238. public void hash(final String path, final String algorithm, final Promise promise) {
  239. threadPool.execute(new Runnable() {
  240. @Override
  241. public void run() {
  242. RNFetchBlobFS.hash(path, algorithm, promise);
  243. }
  244. });
  245. }
  246. /**
  247. * @param path Stream file path
  248. * @param encoding Stream encoding, should be one of `base64`, `ascii`, and `utf8`
  249. * @param bufferSize Stream buffer size, default to 4096 or 4095(base64).
  250. */
  251. @ReactMethod
  252. public void readStream(final String path, final String encoding, final int bufferSize, final int tick, final String streamId) {
  253. final ReactApplicationContext ctx = this.getReactApplicationContext();
  254. fsThreadPool.execute(new Runnable() {
  255. @Override
  256. public void run() {
  257. RNFetchBlobFS fs = new RNFetchBlobFS(ctx);
  258. fs.readStream(path, encoding, bufferSize, tick, streamId);
  259. }
  260. });
  261. }
  262. @ReactMethod
  263. public void cancelRequest(String taskId, Callback callback) {
  264. try {
  265. RNFetchBlobReq.cancelTask(taskId);
  266. callback.invoke(null, taskId);
  267. } catch (Exception ex) {
  268. callback.invoke(ex.getLocalizedMessage(), null);
  269. }
  270. }
  271. @ReactMethod
  272. public void slice(String src, String dest, int start, int end, Promise promise) {
  273. RNFetchBlobFS.slice(src, dest, start, end, "", promise);
  274. }
  275. @ReactMethod
  276. public void enableProgressReport(String taskId, int interval, int count) {
  277. RNFetchBlobProgressConfig config = new RNFetchBlobProgressConfig(true, interval, count, RNFetchBlobProgressConfig.ReportType.Download);
  278. RNFetchBlobReq.progressReport.put(taskId, config);
  279. }
  280. @ReactMethod
  281. public void df(final Callback callback) {
  282. fsThreadPool.execute(new Runnable() {
  283. @Override
  284. public void run() {
  285. RNFetchBlobFS.df(callback);
  286. }
  287. });
  288. }
  289. @ReactMethod
  290. public void enableUploadProgressReport(String taskId, int interval, int count) {
  291. RNFetchBlobProgressConfig config = new RNFetchBlobProgressConfig(true, interval, count, RNFetchBlobProgressConfig.ReportType.Upload);
  292. RNFetchBlobReq.uploadProgressReport.put(taskId, config);
  293. }
  294. @ReactMethod
  295. public void fetchBlob(ReadableMap options, String taskId, String method, String url, ReadableMap headers, String body, final Callback callback) {
  296. new RNFetchBlobReq(options, taskId, method, url, headers, body, null, mClient, callback).run();
  297. }
  298. @ReactMethod
  299. public void fetchBlobForm(ReadableMap options, String taskId, String method, String url, ReadableMap headers, ReadableArray body, final Callback callback) {
  300. new RNFetchBlobReq(options, taskId, method, url, headers, null, body, mClient, callback).run();
  301. }
  302. @ReactMethod
  303. public void getContentIntent(String mime, Promise promise) {
  304. Intent i = new Intent(Intent.ACTION_GET_CONTENT);
  305. if(mime != null)
  306. i.setType(mime);
  307. else
  308. i.setType("*/*");
  309. promiseTable.put(GET_CONTENT_INTENT, promise);
  310. this.getReactApplicationContext().startActivityForResult(i, GET_CONTENT_INTENT, null);
  311. }
  312. @ReactMethod
  313. public void addCompleteDownload (ReadableMap config, Promise promise) {
  314. DownloadManager dm = (DownloadManager) RCTContext.getSystemService(RCTContext.DOWNLOAD_SERVICE);
  315. if (config == null || !config.hasKey("path"))
  316. {
  317. promise.reject("EINVAL", "RNFetchblob.addCompleteDownload config or path missing.");
  318. return;
  319. }
  320. String path = RNFetchBlobFS.normalizePath(config.getString("path"));
  321. if(path == null) {
  322. promise.reject("EINVAL", "RNFetchblob.addCompleteDownload can not resolve URI:" + config.getString("path"));
  323. return;
  324. }
  325. try {
  326. WritableMap stat = RNFetchBlobFS.statFile(path);
  327. dm.addCompletedDownload(
  328. config.hasKey("title") ? config.getString("title") : "",
  329. config.hasKey("description") ? config.getString("description") : "",
  330. true,
  331. config.hasKey("mime") ? config.getString("mime") : null,
  332. path,
  333. Long.valueOf(stat.getString("size")),
  334. config.hasKey("showNotification") && config.getBoolean("showNotification")
  335. );
  336. promise.resolve(null);
  337. }
  338. catch(Exception ex) {
  339. promise.reject("EUNSPECIFIED", ex.getLocalizedMessage());
  340. }
  341. }
  342. @ReactMethod
  343. public void getSDCardDir(Promise promise) {
  344. RNFetchBlobFS.getSDCardDir(promise);
  345. }
  346. @ReactMethod
  347. public void getSDCardApplicationDir(Promise promise) {
  348. RNFetchBlobFS.getSDCardApplicationDir(this.getReactApplicationContext(), promise);
  349. }
  350. }