Keine Beschreibung

RNFetchBlobReq.java 28KB

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