No Description

RNFetchBlobReq.java 32KB

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