No Description

RNFetchBlobReq.java 33KB

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