No Description

RNFetchBlobReq.java 32KB

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