Keine Beschreibung

RNFetchBlobReq.java 32KB

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