Nessuna descrizione

RNFetchBlobReq.java 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. package com.RNFetchBlob;
  2. import android.app.DownloadManager;
  3. import android.content.BroadcastReceiver;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.IntentFilter;
  7. import android.database.Cursor;
  8. import android.net.Uri;
  9. import android.util.Base64;
  10. import com.RNFetchBlob.Response.RNFetchBlobDefaultResp;
  11. import com.RNFetchBlob.Response.RNFetchBlobFileResp;
  12. import com.facebook.react.bridge.Arguments;
  13. import com.facebook.react.bridge.Callback;
  14. import com.facebook.react.bridge.ReactApplicationContext;
  15. import com.facebook.react.bridge.ReadableArray;
  16. import com.facebook.react.bridge.ReadableMap;
  17. import com.facebook.react.bridge.ReadableMapKeySetIterator;
  18. import com.facebook.react.bridge.WritableArray;
  19. import com.facebook.react.bridge.WritableMap;
  20. import com.facebook.react.modules.core.DeviceEventManagerModule;
  21. import java.io.File;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.net.MalformedURLException;
  26. import java.net.SocketException;
  27. import java.net.SocketTimeoutException;
  28. import java.net.URL;
  29. import java.nio.ByteBuffer;
  30. import java.nio.charset.CharacterCodingException;
  31. import java.nio.charset.Charset;
  32. import java.nio.charset.CharsetEncoder;
  33. import java.util.ArrayList;
  34. import java.util.HashMap;
  35. import java.util.concurrent.TimeUnit;
  36. import okhttp3.Call;
  37. import okhttp3.ConnectionPool;
  38. import okhttp3.Headers;
  39. import okhttp3.Interceptor;
  40. import okhttp3.MediaType;
  41. import okhttp3.OkHttpClient;
  42. import okhttp3.Request;
  43. import okhttp3.RequestBody;
  44. import okhttp3.Response;
  45. import okhttp3.ResponseBody;
  46. public class RNFetchBlobReq extends BroadcastReceiver implements Runnable {
  47. enum RequestType {
  48. Form,
  49. SingleFile,
  50. AsIs,
  51. WithoutBody,
  52. Others
  53. }
  54. enum ResponseType {
  55. KeepInMemory,
  56. FileStorage
  57. }
  58. enum ResponseFormat {
  59. Auto,
  60. UTF8,
  61. BASE64
  62. }
  63. public static HashMap<String, Call> taskTable = new HashMap<>();
  64. static HashMap<String, RNFetchBlobProgressConfig> progressReport = new HashMap<>();
  65. static HashMap<String, RNFetchBlobProgressConfig> uploadProgressReport = new HashMap<>();
  66. static ConnectionPool pool = new ConnectionPool();
  67. ReactApplicationContext ctx;
  68. RNFetchBlobConfig options;
  69. String taskId;
  70. String method;
  71. String url;
  72. String rawRequestBody;
  73. String destPath;
  74. ReadableArray rawRequestBodyArray;
  75. ReadableMap headers;
  76. Callback callback;
  77. long contentLength;
  78. long downloadManagerId;
  79. RNFetchBlobBody requestBody;
  80. RequestType requestType;
  81. ResponseType responseType;
  82. ResponseFormat responseFormat = ResponseFormat.Auto;
  83. WritableMap respInfo;
  84. boolean timeout = false;
  85. ArrayList<String> redirects = new ArrayList<>();
  86. public RNFetchBlobReq(ReadableMap options, String taskId, String method, String url, ReadableMap headers, String body, ReadableArray arrayBody, final Callback callback) {
  87. this.method = method.toUpperCase();
  88. this.options = new RNFetchBlobConfig(options);
  89. this.taskId = taskId;
  90. this.url = url;
  91. this.headers = headers;
  92. this.callback = callback;
  93. this.rawRequestBody = body;
  94. this.rawRequestBodyArray = arrayBody;
  95. if(this.options.fileCache || this.options.path != null)
  96. responseType = ResponseType.FileStorage;
  97. else
  98. responseType = ResponseType.KeepInMemory;
  99. if (body != null)
  100. requestType = RequestType.SingleFile;
  101. else if (arrayBody != null)
  102. requestType = RequestType.Form;
  103. else
  104. requestType = RequestType.WithoutBody;
  105. }
  106. public static void cancelTask(String taskId) {
  107. if(taskTable.containsKey(taskId)) {
  108. Call call = taskTable.get(taskId);
  109. call.cancel();
  110. taskTable.remove(taskId);
  111. }
  112. }
  113. @Override
  114. public void run() {
  115. // use download manager instead of default HTTP implementation
  116. if (options.addAndroidDownloads != null && options.addAndroidDownloads.hasKey("useDownloadManager")) {
  117. if (options.addAndroidDownloads.getBoolean("useDownloadManager")) {
  118. Uri uri = Uri.parse(url);
  119. DownloadManager.Request req = new DownloadManager.Request(uri);
  120. req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  121. if(options.addAndroidDownloads.hasKey("title")) {
  122. req.setTitle(options.addAndroidDownloads.getString("title"));
  123. }
  124. if(options.addAndroidDownloads.hasKey("description")) {
  125. req.setDescription(options.addAndroidDownloads.getString("description"));
  126. }
  127. if(options.addAndroidDownloads.hasKey("path")) {
  128. req.setDestinationUri(Uri.parse("file://" + options.addAndroidDownloads.getString("path")));
  129. }
  130. // set headers
  131. ReadableMapKeySetIterator it = headers.keySetIterator();
  132. while (it.hasNextKey()) {
  133. String key = it.nextKey();
  134. req.addRequestHeader(key, headers.getString(key));
  135. }
  136. Context appCtx = RNFetchBlob.RCTContext.getApplicationContext();
  137. DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
  138. downloadManagerId = dm.enqueue(req);
  139. appCtx.registerReceiver(this, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
  140. return;
  141. }
  142. }
  143. // find cached result if `key` property exists
  144. String cacheKey = this.taskId;
  145. String ext = this.options.appendExt.isEmpty() ? "." + this.options.appendExt : "";
  146. if (this.options.key != null) {
  147. cacheKey = RNFetchBlobUtils.getMD5(this.options.key);
  148. if (cacheKey == null) {
  149. cacheKey = this.taskId;
  150. }
  151. File file = new File(RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext);
  152. if (file.exists()) {
  153. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, file.getAbsolutePath());
  154. return;
  155. }
  156. }
  157. if(this.options.path != null)
  158. this.destPath = this.options.path;
  159. else if(this.options.fileCache)
  160. this.destPath = RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext;
  161. OkHttpClient.Builder clientBuilder;
  162. try {
  163. // use trusty SSL socket
  164. if (this.options.trusty) {
  165. clientBuilder = RNFetchBlobUtils.getUnsafeOkHttpClient();
  166. } else {
  167. clientBuilder = new OkHttpClient.Builder();
  168. }
  169. final Request.Builder builder = new Request.Builder();
  170. try {
  171. builder.url(new URL(url));
  172. } catch (MalformedURLException e) {
  173. e.printStackTrace();
  174. }
  175. HashMap<String, String> mheaders = new HashMap<>();
  176. // set headers
  177. if (headers != null) {
  178. ReadableMapKeySetIterator it = headers.keySetIterator();
  179. while (it.hasNextKey()) {
  180. String key = it.nextKey();
  181. String value = headers.getString(key);
  182. if(key.equalsIgnoreCase("RNFB-Response")) {
  183. if(value.equalsIgnoreCase("base64"))
  184. responseFormat = ResponseFormat.BASE64;
  185. else if (value.equalsIgnoreCase("utf8"))
  186. responseFormat = ResponseFormat.UTF8;
  187. }
  188. else {
  189. builder.header(key, value);
  190. mheaders.put(key, value);
  191. }
  192. }
  193. }
  194. if(method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
  195. String cType = getHeaderIgnoreCases(mheaders, "Content-Type").toLowerCase();
  196. if(rawRequestBodyArray != null) {
  197. requestType = RequestType.Form;
  198. }
  199. else if(cType.isEmpty()) {
  200. builder.header("Content-Type", "application/octet-stream");
  201. requestType = RequestType.SingleFile;
  202. }
  203. if(rawRequestBody != null) {
  204. if(rawRequestBody.startsWith(RNFetchBlobConst.FILE_PREFIX)) {
  205. requestType = RequestType.SingleFile;
  206. }
  207. else if (cType.toLowerCase().contains(";base64") || cType.toLowerCase().startsWith("application/octet")) {
  208. cType = cType.replace(";base64","").replace(";BASE64","");
  209. if(mheaders.containsKey("content-type"))
  210. mheaders.put("content-type", cType);
  211. if(mheaders.containsKey("Content-Type"))
  212. mheaders.put("Content-Type", cType);
  213. requestType = RequestType.SingleFile;
  214. } else {
  215. requestType = RequestType.AsIs;
  216. }
  217. }
  218. }
  219. else {
  220. requestType = RequestType.WithoutBody;
  221. }
  222. boolean isChunkedRequest = getHeaderIgnoreCases(mheaders, "Transfer-Encoding").equalsIgnoreCase("chunked");
  223. // set request body
  224. switch (requestType) {
  225. case SingleFile:
  226. requestBody = new RNFetchBlobBody(taskId)
  227. .chunkedEncoding(isChunkedRequest)
  228. .setRequestType(requestType)
  229. .setBody(rawRequestBody)
  230. .setMIME(MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type")));
  231. builder.method(method, requestBody);
  232. break;
  233. case AsIs:
  234. requestBody = new RNFetchBlobBody(taskId)
  235. .chunkedEncoding(isChunkedRequest)
  236. .setRequestType(requestType)
  237. .setBody(rawRequestBody)
  238. .setMIME(MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type")));
  239. builder.method(method, requestBody);
  240. break;
  241. case Form:
  242. String boundary = "RNFetchBlob-" + taskId;
  243. requestBody = new RNFetchBlobBody(taskId)
  244. .chunkedEncoding(isChunkedRequest)
  245. .setRequestType(requestType)
  246. .setBody(rawRequestBodyArray)
  247. .setMIME(MediaType.parse("multipart/form-data; boundary="+ boundary));
  248. builder.method(method, requestBody);
  249. break;
  250. case WithoutBody:
  251. if(method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT"))
  252. {
  253. builder.method(method, RequestBody.create(null, new byte[0]));
  254. }
  255. else
  256. builder.method(method, null);
  257. break;
  258. }
  259. final Request req = builder.build();
  260. clientBuilder.addNetworkInterceptor(new Interceptor() {
  261. @Override
  262. public Response intercept(Chain chain) throws IOException {
  263. redirects.add(chain.request().url().toString());
  264. return chain.proceed(chain.request());
  265. }
  266. });
  267. // Add request interceptor for upload progress event
  268. clientBuilder.addInterceptor(new Interceptor() {
  269. @Override
  270. public Response intercept(Chain chain) throws IOException {
  271. try {
  272. Response originalResponse = chain.proceed(req);
  273. ResponseBody extended;
  274. switch (responseType) {
  275. case KeepInMemory:
  276. extended = new RNFetchBlobDefaultResp(
  277. RNFetchBlob.RCTContext,
  278. taskId,
  279. originalResponse.body());
  280. break;
  281. case FileStorage:
  282. extended = new RNFetchBlobFileResp(
  283. RNFetchBlob.RCTContext,
  284. taskId,
  285. originalResponse.body(),
  286. destPath);
  287. break;
  288. default:
  289. extended = new RNFetchBlobDefaultResp(
  290. RNFetchBlob.RCTContext,
  291. taskId,
  292. originalResponse.body());
  293. break;
  294. }
  295. return originalResponse.newBuilder().body(extended).build();
  296. }
  297. catch(SocketException e) {
  298. timeout = true;
  299. }
  300. catch (SocketTimeoutException e ){
  301. timeout = true;
  302. } catch(Exception ex) {
  303. RNFetchBlobUtils.emitWarningEvent("RNFetchBlob error when sending request : " + ex.getLocalizedMessage());
  304. }
  305. return chain.proceed(chain.request());
  306. }
  307. });
  308. if(options.timeout >= 0) {
  309. clientBuilder.connectTimeout(options.timeout, TimeUnit.MILLISECONDS);
  310. clientBuilder.readTimeout(options.timeout, TimeUnit.MILLISECONDS);
  311. }
  312. clientBuilder.connectionPool(pool);
  313. clientBuilder.retryOnConnectionFailure(false);
  314. clientBuilder.followRedirects(true);
  315. OkHttpClient client = clientBuilder.retryOnConnectionFailure(true).build();
  316. Call call = client.newCall(req);
  317. taskTable.put(taskId, call);
  318. call.enqueue(new okhttp3.Callback() {
  319. @Override
  320. public void onFailure(Call call, IOException e) {
  321. cancelTask(taskId);
  322. if(respInfo == null) {
  323. respInfo = Arguments.createMap();
  324. }
  325. // check if this error caused by socket timeout
  326. if(e.getClass().equals(SocketTimeoutException.class)) {
  327. respInfo.putBoolean("timeout", true);
  328. callback.invoke("request timed out.", null, null);
  329. }
  330. else
  331. callback.invoke(e.getLocalizedMessage(), null, null);
  332. releaseTaskResource();
  333. }
  334. @Override
  335. public void onResponse(Call call, Response response) throws IOException {
  336. ReadableMap notifyConfig = options.addAndroidDownloads;
  337. // Download manager settings
  338. if(notifyConfig != null ) {
  339. String title = "", desc = "", mime = "text/plain";
  340. boolean scannable = false, notification = false;
  341. if(notifyConfig.hasKey("title"))
  342. title = options.addAndroidDownloads.getString("title");
  343. if(notifyConfig.hasKey("description"))
  344. desc = notifyConfig.getString("description");
  345. if(notifyConfig.hasKey("mime"))
  346. mime = notifyConfig.getString("mime");
  347. if(notifyConfig.hasKey("mediaScannable"))
  348. scannable = notifyConfig.getBoolean("mediaScannable");
  349. if(notifyConfig.hasKey("notification"))
  350. notification = notifyConfig.getBoolean("notification");
  351. DownloadManager dm = (DownloadManager)RNFetchBlob.RCTContext.getSystemService(RNFetchBlob.RCTContext.DOWNLOAD_SERVICE);
  352. dm.addCompletedDownload(title, desc, scannable, mime, destPath, contentLength, notification);
  353. }
  354. done(response);
  355. }
  356. });
  357. } catch (Exception error) {
  358. error.printStackTrace();
  359. releaseTaskResource();
  360. callback.invoke("RNFetchBlob request error: " + error.getMessage() + error.getCause());
  361. }
  362. }
  363. /**
  364. * Remove cached information of the HTTP task
  365. */
  366. private void releaseTaskResource() {
  367. if(taskTable.containsKey(taskId))
  368. taskTable.remove(taskId);
  369. if(uploadProgressReport.containsKey(taskId))
  370. uploadProgressReport.remove(taskId);
  371. if(progressReport.containsKey(taskId))
  372. progressReport.remove(taskId);
  373. if(requestBody != null)
  374. requestBody.clearRequestBody();
  375. }
  376. /**
  377. * Send response data back to javascript context.
  378. * @param resp OkHttp response object
  379. */
  380. private void done(Response resp) {
  381. boolean isBlobResp = isBlobResponse(resp);
  382. emitStateEvent(getResponseInfo(resp, isBlobResp));
  383. switch (responseType) {
  384. case KeepInMemory:
  385. try {
  386. // For XMLHttpRequest, automatic response data storing strategy, when response
  387. // data is considered as binary data, write it to file system
  388. if(isBlobResp && options.auto) {
  389. String dest = RNFetchBlobFS.getTmpPath(ctx, taskId);
  390. InputStream ins = resp.body().byteStream();
  391. FileOutputStream os = new FileOutputStream(new File(dest));
  392. int read;
  393. byte [] buffer = new byte[10240];
  394. while ((read = ins.read(buffer)) != -1) {
  395. os.write(buffer, 0, read);
  396. }
  397. ins.close();
  398. os.flush();
  399. os.close();
  400. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, dest);
  401. }
  402. // response data directly pass to JS context as string.
  403. else {
  404. // #73 Check if the response data contains valid UTF8 string, since BASE64
  405. // encoding will somehow break the UTF8 string format, to encode UTF8
  406. // string correctly, we should do URL encoding before BASE64.
  407. byte[] b = resp.body().bytes();
  408. CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
  409. if(responseFormat == ResponseFormat.BASE64) {
  410. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_BASE64, android.util.Base64.encodeToString(b, Base64.NO_WRAP));
  411. return;
  412. }
  413. try {
  414. encoder.encode(ByteBuffer.wrap(b).asCharBuffer());
  415. // if the data contains invalid characters the following lines will be
  416. // skipped.
  417. String utf8 = new String(b);
  418. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, utf8);
  419. }
  420. // This usually mean the data is contains invalid unicode characters, it's
  421. // binary data
  422. catch(CharacterCodingException ignored) {
  423. if(responseFormat == ResponseFormat.UTF8) {
  424. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, "");
  425. }
  426. else {
  427. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_BASE64, android.util.Base64.encodeToString(b, Base64.NO_WRAP));
  428. }
  429. }
  430. }
  431. } catch (IOException e) {
  432. callback.invoke("RNFetchBlob failed to encode response data to BASE64 string.", null);
  433. }
  434. break;
  435. case FileStorage:
  436. try {
  437. // In order to write response data to `destPath` we have to invoke this method.
  438. // It uses customized response body which is able to report download progress
  439. // and write response data to destination path.
  440. resp.body().bytes();
  441. } catch (Exception ignored) {
  442. ignored.printStackTrace();
  443. }
  444. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, this.destPath);
  445. break;
  446. default:
  447. try {
  448. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, new String(resp.body().bytes(), "UTF-8"));
  449. } catch (IOException e) {
  450. callback.invoke("RNFetchBlob failed to encode response data to UTF8 string.", null);
  451. }
  452. break;
  453. }
  454. if(!resp.isSuccessful())
  455. resp.body().close();
  456. releaseTaskResource();
  457. }
  458. /**
  459. * Invoke this method to enable download progress reporting.
  460. * @param taskId Task ID of the HTTP task.
  461. * @return Task ID of the target task
  462. */
  463. public static RNFetchBlobProgressConfig getReportProgress(String taskId) {
  464. if(!progressReport.containsKey(taskId)) return null;
  465. return progressReport.get(taskId);
  466. }
  467. /**
  468. * Invoke this method to enable download progress reporting.
  469. * @param taskId Task ID of the HTTP task.
  470. * @return Task ID of the target task
  471. */
  472. public static RNFetchBlobProgressConfig getReportUploadProgress(String taskId) {
  473. if(!uploadProgressReport.containsKey(taskId)) return null;
  474. return uploadProgressReport.get(taskId);
  475. }
  476. /**
  477. * Create response information object, contains status code, headers, etc.
  478. * @param resp Response object
  479. * @param isBlobResp If the response is binary data
  480. * @return Get RCT bridge object contains response information.
  481. */
  482. private WritableMap getResponseInfo(Response resp, boolean isBlobResp) {
  483. WritableMap info = Arguments.createMap();
  484. info.putInt("status", resp.code());
  485. info.putString("state", "2");
  486. info.putString("taskId", this.taskId);
  487. info.putBoolean("timeout", timeout);
  488. WritableMap headers = Arguments.createMap();
  489. for(int i =0;i< resp.headers().size();i++) {
  490. headers.putString(resp.headers().name(i), resp.headers().value(i));
  491. }
  492. WritableArray redirectList = Arguments.createArray();
  493. for(String r : redirects) {
  494. redirectList.pushString(r);
  495. }
  496. info.putArray("redirects", redirectList);
  497. info.putMap("headers", headers);
  498. Headers h = resp.headers();
  499. if(isBlobResp) {
  500. info.putString("respType", "blob");
  501. }
  502. else if(getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("text/")) {
  503. info.putString("respType", "text");
  504. }
  505. else if(getHeaderIgnoreCases(h, "content-type").contains("application/json")) {
  506. info.putString("respType", "json");
  507. }
  508. else {
  509. info.putString("respType", "");
  510. }
  511. return info;
  512. }
  513. /**
  514. * Check if response data is binary data.
  515. * @param resp OkHttp response.
  516. * @return If the response data contains binary bytes
  517. */
  518. private boolean isBlobResponse(Response resp) {
  519. Headers h = resp.headers();
  520. String ctype = getHeaderIgnoreCases(h, "Content-Type");
  521. boolean isText = !ctype.equalsIgnoreCase("text/");
  522. boolean isJSON = !ctype.equalsIgnoreCase("application/json");
  523. boolean isCustomBinary = false;
  524. if(options.binaryContentTypes != null) {
  525. for(int i = 0; i< options.binaryContentTypes.size();i++) {
  526. if(ctype.toLowerCase().contains(options.binaryContentTypes.getString(i).toLowerCase())) {
  527. isCustomBinary = true;
  528. break;
  529. }
  530. }
  531. }
  532. return (!(isJSON || isText)) || isCustomBinary;
  533. }
  534. private String getHeaderIgnoreCases(Headers headers, String field) {
  535. String val = headers.get(field);
  536. if(val != null) return val;
  537. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  538. }
  539. private String getHeaderIgnoreCases(HashMap<String,String> headers, String field) {
  540. String val = headers.get(field);
  541. if(val != null) return val;
  542. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  543. }
  544. private void emitStateEvent(WritableMap args) {
  545. RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  546. .emit(RNFetchBlobConst.EVENT_HTTP_STATE, args);
  547. }
  548. @Override
  549. public void onReceive(Context context, Intent intent) {
  550. String action = intent.getAction();
  551. if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
  552. Context appCtx = RNFetchBlob.RCTContext.getApplicationContext();
  553. long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
  554. if (id == this.downloadManagerId) {
  555. DownloadManager.Query query = new DownloadManager.Query();
  556. query.setFilterById(downloadManagerId);
  557. DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
  558. dm.query(query);
  559. Cursor c = dm.query(query);
  560. String filePath = null;
  561. // the file exists in media content database
  562. if (c.moveToFirst()) {
  563. String contentUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
  564. Uri uri = Uri.parse(contentUri);
  565. Cursor cursor = appCtx.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
  566. // use default destination of DownloadManager
  567. if (cursor != null) {
  568. cursor.moveToFirst();
  569. filePath = cursor.getString(0);
  570. cursor.close();
  571. if(filePath != null) {
  572. this.callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, filePath);
  573. return;
  574. }
  575. }
  576. }
  577. // When the file is not found in media content database, check if custom path exists
  578. if (options.addAndroidDownloads.hasKey("path")) {
  579. try {
  580. String customDest = options.addAndroidDownloads.getString("path");
  581. boolean exists = new File(customDest).exists();
  582. if(!exists)
  583. throw new Exception("Download manager download failed, the file does not downloaded to destination.");
  584. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, customDest);
  585. } catch(Exception ex) {
  586. this.callback.invoke(ex.getLocalizedMessage(), null, null);
  587. }
  588. }
  589. else
  590. this.callback.invoke("Download manager could not resolve downloaded file path.", RNFetchBlobConst.RNFB_RESPONSE_PATH, null);
  591. }
  592. }
  593. }
  594. }