暫無描述

RNFetchBlobReq.java 34KB

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