Keine Beschreibung

RNFetchBlobReq.java 32KB

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