No Description

RNFetchBlobReq.java 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. options.overwrite);
  296. break;
  297. default:
  298. extended = new RNFetchBlobDefaultResp(
  299. RNFetchBlob.RCTContext,
  300. taskId,
  301. originalResponse.body(),
  302. options.increment);
  303. break;
  304. }
  305. return originalResponse.newBuilder().body(extended).build();
  306. }
  307. catch(SocketException e) {
  308. timeout = true;
  309. }
  310. catch (SocketTimeoutException e ){
  311. timeout = true;
  312. RNFetchBlobUtils.emitWarningEvent("RNFetchBlob error when sending request : " + e.getLocalizedMessage());
  313. } catch(Exception ex) {
  314. }
  315. return chain.proceed(chain.request());
  316. }
  317. });
  318. if(options.timeout >= 0) {
  319. clientBuilder.connectTimeout(options.timeout, TimeUnit.MILLISECONDS);
  320. clientBuilder.readTimeout(options.timeout, TimeUnit.MILLISECONDS);
  321. }
  322. clientBuilder.connectionPool(pool);
  323. clientBuilder.retryOnConnectionFailure(false);
  324. clientBuilder.followRedirects(options.followRedirect);
  325. clientBuilder.followSslRedirects(options.followRedirect);
  326. OkHttpClient client = clientBuilder.retryOnConnectionFailure(true).build();
  327. Call call = client.newCall(req);
  328. taskTable.put(taskId, call);
  329. call.enqueue(new okhttp3.Callback() {
  330. @Override
  331. public void onFailure(Call call, IOException e) {
  332. cancelTask(taskId);
  333. if(respInfo == null) {
  334. respInfo = Arguments.createMap();
  335. }
  336. // check if this error caused by socket timeout
  337. if(e.getClass().equals(SocketTimeoutException.class)) {
  338. respInfo.putBoolean("timeout", true);
  339. callback.invoke("request timed out.", null, null);
  340. }
  341. else
  342. callback.invoke(e.getLocalizedMessage(), null, null);
  343. releaseTaskResource();
  344. }
  345. @Override
  346. public void onResponse(Call call, Response response) throws IOException {
  347. ReadableMap notifyConfig = options.addAndroidDownloads;
  348. // Download manager settings
  349. if(notifyConfig != null ) {
  350. String title = "", desc = "", mime = "text/plain";
  351. boolean scannable = false, notification = false;
  352. if(notifyConfig.hasKey("title"))
  353. title = options.addAndroidDownloads.getString("title");
  354. if(notifyConfig.hasKey("description"))
  355. desc = notifyConfig.getString("description");
  356. if(notifyConfig.hasKey("mime"))
  357. mime = notifyConfig.getString("mime");
  358. if(notifyConfig.hasKey("mediaScannable"))
  359. scannable = notifyConfig.getBoolean("mediaScannable");
  360. if(notifyConfig.hasKey("notification"))
  361. notification = notifyConfig.getBoolean("notification");
  362. DownloadManager dm = (DownloadManager)RNFetchBlob.RCTContext.getSystemService(RNFetchBlob.RCTContext.DOWNLOAD_SERVICE);
  363. dm.addCompletedDownload(title, desc, scannable, mime, destPath, contentLength, notification);
  364. }
  365. done(response);
  366. }
  367. });
  368. } catch (Exception error) {
  369. error.printStackTrace();
  370. releaseTaskResource();
  371. callback.invoke("RNFetchBlob request error: " + error.getMessage() + error.getCause());
  372. }
  373. }
  374. /**
  375. * Remove cached information of the HTTP task
  376. */
  377. private void releaseTaskResource() {
  378. if(taskTable.containsKey(taskId))
  379. taskTable.remove(taskId);
  380. if(uploadProgressReport.containsKey(taskId))
  381. uploadProgressReport.remove(taskId);
  382. if(progressReport.containsKey(taskId))
  383. progressReport.remove(taskId);
  384. if(requestBody != null)
  385. requestBody.clearRequestBody();
  386. }
  387. /**
  388. * Send response data back to javascript context.
  389. * @param resp OkHttp response object
  390. */
  391. private void done(Response resp) {
  392. boolean isBlobResp = isBlobResponse(resp);
  393. emitStateEvent(getResponseInfo(resp, isBlobResp));
  394. switch (responseType) {
  395. case KeepInMemory:
  396. try {
  397. // For XMLHttpRequest, automatic response data storing strategy, when response
  398. // data is considered as binary data, write it to file system
  399. if(isBlobResp && options.auto) {
  400. String dest = RNFetchBlobFS.getTmpPath(ctx, taskId);
  401. InputStream ins = resp.body().byteStream();
  402. FileOutputStream os = new FileOutputStream(new File(dest));
  403. int read;
  404. byte [] buffer = new byte[10240];
  405. while ((read = ins.read(buffer)) != -1) {
  406. os.write(buffer, 0, read);
  407. }
  408. ins.close();
  409. os.flush();
  410. os.close();
  411. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, dest);
  412. }
  413. // response data directly pass to JS context as string.
  414. else {
  415. // #73 Check if the response data contains valid UTF8 string, since BASE64
  416. // encoding will somehow break the UTF8 string format, to encode UTF8
  417. // string correctly, we should do URL encoding before BASE64.
  418. byte[] b = resp.body().bytes();
  419. CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
  420. if(responseFormat == ResponseFormat.BASE64) {
  421. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_BASE64, android.util.Base64.encodeToString(b, Base64.NO_WRAP));
  422. return;
  423. }
  424. try {
  425. encoder.encode(ByteBuffer.wrap(b).asCharBuffer());
  426. // if the data contains invalid characters the following lines will be
  427. // skipped.
  428. String utf8 = new String(b);
  429. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, utf8);
  430. }
  431. // This usually mean the data is contains invalid unicode characters, it's
  432. // binary data
  433. catch(CharacterCodingException ignored) {
  434. if(responseFormat == ResponseFormat.UTF8) {
  435. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, "");
  436. }
  437. else {
  438. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_BASE64, android.util.Base64.encodeToString(b, Base64.NO_WRAP));
  439. }
  440. }
  441. }
  442. } catch (IOException e) {
  443. callback.invoke("RNFetchBlob failed to encode response data to BASE64 string.", null);
  444. }
  445. break;
  446. case FileStorage:
  447. try {
  448. // In order to write response data to `destPath` we have to invoke this method.
  449. // It uses customized response body which is able to report download progress
  450. // and write response data to destination path.
  451. resp.body().bytes();
  452. } catch (Exception ignored) {
  453. // ignored.printStackTrace();
  454. }
  455. this.destPath = this.destPath.replace("?append=true", "");
  456. try {
  457. long expectedLength = resp.body().contentLength();
  458. // when response contains Content-Length, check if the stream length is correct
  459. if(expectedLength > 0) {
  460. long actualLength = new File(this.destPath).length();
  461. if(actualLength != expectedLength) {
  462. callback.invoke("RNFetchBlob failed to write data to storage : expected " + expectedLength + " bytes but got " + actualLength + " bytes", null);
  463. }
  464. else {
  465. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, this.destPath);
  466. }
  467. }
  468. else {
  469. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, this.destPath);
  470. }
  471. }
  472. catch (Exception err) {
  473. callback.invoke(err.getMessage());
  474. err.printStackTrace();
  475. }
  476. break;
  477. default:
  478. try {
  479. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, new String(resp.body().bytes(), "UTF-8"));
  480. } catch (IOException e) {
  481. callback.invoke("RNFetchBlob failed to encode response data to UTF8 string.", null);
  482. }
  483. break;
  484. }
  485. // if(!resp.isSuccessful())
  486. resp.body().close();
  487. releaseTaskResource();
  488. }
  489. /**
  490. * Invoke this method to enable download progress reporting.
  491. * @param taskId Task ID of the HTTP task.
  492. * @return Task ID of the target task
  493. */
  494. public static RNFetchBlobProgressConfig getReportProgress(String taskId) {
  495. if(!progressReport.containsKey(taskId)) return null;
  496. return progressReport.get(taskId);
  497. }
  498. /**
  499. * Invoke this method to enable download progress reporting.
  500. * @param taskId Task ID of the HTTP task.
  501. * @return Task ID of the target task
  502. */
  503. public static RNFetchBlobProgressConfig getReportUploadProgress(String taskId) {
  504. if(!uploadProgressReport.containsKey(taskId)) return null;
  505. return uploadProgressReport.get(taskId);
  506. }
  507. /**
  508. * Create response information object, contains status code, headers, etc.
  509. * @param resp Response object
  510. * @param isBlobResp If the response is binary data
  511. * @return Get RCT bridge object contains response information.
  512. */
  513. private WritableMap getResponseInfo(Response resp, boolean isBlobResp) {
  514. WritableMap info = Arguments.createMap();
  515. info.putInt("status", resp.code());
  516. info.putString("state", "2");
  517. info.putString("taskId", this.taskId);
  518. info.putBoolean("timeout", timeout);
  519. WritableMap headers = Arguments.createMap();
  520. for(int i =0;i< resp.headers().size();i++) {
  521. headers.putString(resp.headers().name(i), resp.headers().value(i));
  522. }
  523. WritableArray redirectList = Arguments.createArray();
  524. for(String r : redirects) {
  525. redirectList.pushString(r);
  526. }
  527. info.putArray("redirects", redirectList);
  528. info.putMap("headers", headers);
  529. Headers h = resp.headers();
  530. if(isBlobResp) {
  531. info.putString("respType", "blob");
  532. }
  533. else if(getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("text/")) {
  534. info.putString("respType", "text");
  535. }
  536. else if(getHeaderIgnoreCases(h, "content-type").contains("application/json")) {
  537. info.putString("respType", "json");
  538. }
  539. else {
  540. info.putString("respType", "");
  541. }
  542. return info;
  543. }
  544. /**
  545. * Check if response data is binary data.
  546. * @param resp OkHttp response.
  547. * @return If the response data contains binary bytes
  548. */
  549. private boolean isBlobResponse(Response resp) {
  550. Headers h = resp.headers();
  551. String ctype = getHeaderIgnoreCases(h, "Content-Type");
  552. boolean isText = !ctype.equalsIgnoreCase("text/");
  553. boolean isJSON = !ctype.equalsIgnoreCase("application/json");
  554. boolean isCustomBinary = false;
  555. if(options.binaryContentTypes != null) {
  556. for(int i = 0; i< options.binaryContentTypes.size();i++) {
  557. if(ctype.toLowerCase().contains(options.binaryContentTypes.getString(i).toLowerCase())) {
  558. isCustomBinary = true;
  559. break;
  560. }
  561. }
  562. }
  563. return (!(isJSON || isText)) || isCustomBinary;
  564. }
  565. private String getHeaderIgnoreCases(Headers headers, String field) {
  566. String val = headers.get(field);
  567. if(val != null) return val;
  568. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  569. }
  570. private String getHeaderIgnoreCases(HashMap<String,String> headers, String field) {
  571. String val = headers.get(field);
  572. if(val != null) return val;
  573. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  574. }
  575. private void emitStateEvent(WritableMap args) {
  576. RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  577. .emit(RNFetchBlobConst.EVENT_HTTP_STATE, args);
  578. }
  579. @Override
  580. public void onReceive(Context context, Intent intent) {
  581. String action = intent.getAction();
  582. if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
  583. Context appCtx = RNFetchBlob.RCTContext.getApplicationContext();
  584. long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
  585. if (id == this.downloadManagerId) {
  586. DownloadManager.Query query = new DownloadManager.Query();
  587. query.setFilterById(downloadManagerId);
  588. DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
  589. dm.query(query);
  590. Cursor c = dm.query(query);
  591. String error = null;
  592. String filePath = null;
  593. // the file exists in media content database
  594. if (c.moveToFirst()) {
  595. String contentUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
  596. Uri uri = Uri.parse(contentUri);
  597. Cursor cursor = appCtx.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
  598. // use default destination of DownloadManager
  599. if (cursor != null) {
  600. cursor.moveToFirst();
  601. filePath = cursor.getString(0);
  602. }
  603. }
  604. // When the file is not found in media content database, check if custom path exists
  605. if (options.addAndroidDownloads.hasKey("path")) {
  606. try {
  607. String customDest = options.addAndroidDownloads.getString("path");
  608. boolean exists = new File(customDest).exists();
  609. if(!exists)
  610. throw new Exception("Download manager download failed, the file does not downloaded to destination.");
  611. else
  612. this.callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, customDest);
  613. } catch(Exception ex) {
  614. error = ex.getLocalizedMessage();
  615. }
  616. }
  617. else {
  618. if(filePath == null)
  619. this.callback.invoke("Download manager could not resolve downloaded file path.", RNFetchBlobConst.RNFB_RESPONSE_PATH, null);
  620. else
  621. this.callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, filePath);
  622. }
  623. }
  624. }
  625. }
  626. }