暂无描述

RNFetchBlobReq.java 29KB

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