Açıklama Yok

RNFetchBlobReq.java 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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. if(responseFormat == ResponseFormat.BASE64) {
  453. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_BASE64, android.util.Base64.encodeToString(b, Base64.NO_WRAP));
  454. return;
  455. }
  456. String utf8 = new String(b);
  457. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, utf8);
  458. }
  459. } catch (IOException e) {
  460. callback.invoke("RNFetchBlob failed to encode response data to BASE64 string.", null);
  461. }
  462. break;
  463. case FileStorage:
  464. try {
  465. // In order to write response data to `destPath` we have to invoke this method.
  466. // It uses customized response body which is able to report download progress
  467. // and write response data to destination path.
  468. resp.body().bytes();
  469. } catch (Exception ignored) {
  470. // ignored.printStackTrace();
  471. }
  472. this.destPath = this.destPath.replace("?append=true", "");
  473. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, this.destPath);
  474. break;
  475. default:
  476. try {
  477. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, new String(resp.body().bytes(), "UTF-8"));
  478. } catch (IOException e) {
  479. callback.invoke("RNFetchBlob failed to encode response data to UTF8 string.", null);
  480. }
  481. break;
  482. }
  483. // if(!resp.isSuccessful())
  484. resp.body().close();
  485. releaseTaskResource();
  486. }
  487. /**
  488. * Invoke this method to enable download progress reporting.
  489. * @param taskId Task ID of the HTTP task.
  490. * @return Task ID of the target task
  491. */
  492. public static RNFetchBlobProgressConfig getReportProgress(String taskId) {
  493. if(!progressReport.containsKey(taskId)) return null;
  494. return progressReport.get(taskId);
  495. }
  496. /**
  497. * Invoke this method to enable download progress reporting.
  498. * @param taskId Task ID of the HTTP task.
  499. * @return Task ID of the target task
  500. */
  501. public static RNFetchBlobProgressConfig getReportUploadProgress(String taskId) {
  502. if(!uploadProgressReport.containsKey(taskId)) return null;
  503. return uploadProgressReport.get(taskId);
  504. }
  505. /**
  506. * Create response information object, contains status code, headers, etc.
  507. * @param resp Response object
  508. * @param isBlobResp If the response is binary data
  509. * @return Get RCT bridge object contains response information.
  510. */
  511. private WritableMap getResponseInfo(Response resp, boolean isBlobResp) {
  512. WritableMap info = Arguments.createMap();
  513. info.putInt("status", resp.code());
  514. info.putString("state", "2");
  515. info.putString("taskId", this.taskId);
  516. info.putBoolean("timeout", timeout);
  517. WritableMap headers = Arguments.createMap();
  518. for(int i =0;i< resp.headers().size();i++) {
  519. headers.putString(resp.headers().name(i), resp.headers().value(i));
  520. }
  521. WritableArray redirectList = Arguments.createArray();
  522. for(String r : redirects) {
  523. redirectList.pushString(r);
  524. }
  525. info.putArray("redirects", redirectList);
  526. info.putMap("headers", headers);
  527. Headers h = resp.headers();
  528. if(isBlobResp) {
  529. info.putString("respType", "blob");
  530. }
  531. else if(getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("text/")) {
  532. info.putString("respType", "text");
  533. }
  534. else if(getHeaderIgnoreCases(h, "content-type").contains("application/json")) {
  535. info.putString("respType", "json");
  536. }
  537. else {
  538. info.putString("respType", "");
  539. }
  540. return info;
  541. }
  542. /**
  543. * Check if response data is binary data.
  544. * @param resp OkHttp response.
  545. * @return If the response data contains binary bytes
  546. */
  547. private boolean isBlobResponse(Response resp) {
  548. Headers h = resp.headers();
  549. String ctype = getHeaderIgnoreCases(h, "Content-Type");
  550. boolean isText = !ctype.equalsIgnoreCase("text/");
  551. boolean isJSON = !ctype.equalsIgnoreCase("application/json");
  552. boolean isCustomBinary = false;
  553. if(options.binaryContentTypes != null) {
  554. for(int i = 0; i< options.binaryContentTypes.size();i++) {
  555. if(ctype.toLowerCase().contains(options.binaryContentTypes.getString(i).toLowerCase())) {
  556. isCustomBinary = true;
  557. break;
  558. }
  559. }
  560. }
  561. return (!(isJSON || isText)) || isCustomBinary;
  562. }
  563. private String getHeaderIgnoreCases(Headers headers, String field) {
  564. String val = headers.get(field);
  565. if(val != null) return val;
  566. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  567. }
  568. private String getHeaderIgnoreCases(HashMap<String,String> headers, String field) {
  569. String val = headers.get(field);
  570. if(val != null) return val;
  571. String lowerCasedValue = headers.get(field.toLowerCase());
  572. return lowerCasedValue == null ? "" : lowerCasedValue;
  573. }
  574. private void emitStateEvent(WritableMap args) {
  575. RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  576. .emit(RNFetchBlobConst.EVENT_HTTP_STATE, args);
  577. }
  578. @Override
  579. public void onReceive(Context context, Intent intent) {
  580. String action = intent.getAction();
  581. if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
  582. Context appCtx = RNFetchBlob.RCTContext.getApplicationContext();
  583. long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
  584. if (id == this.downloadManagerId) {
  585. releaseTaskResource(); // remove task ID from task map
  586. DownloadManager.Query query = new DownloadManager.Query();
  587. query.setFilterById(downloadManagerId);
  588. DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
  589. dm.query(query);
  590. Cursor c = dm.query(query);
  591. String filePath = null;
  592. // the file exists in media content database
  593. if (c.moveToFirst()) {
  594. // #297 handle failed request
  595. int statusCode = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
  596. if(statusCode == DownloadManager.STATUS_FAILED) {
  597. this.callback.invoke("Download manager failed to download from " + this.url + ". Status Code = " + statusCode, null, null);
  598. return;
  599. }
  600. String contentUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
  601. if ( contentUri != null &&
  602. options.addAndroidDownloads.hasKey("mime") &&
  603. options.addAndroidDownloads.getString("mime").contains("image")) {
  604. Uri uri = Uri.parse(contentUri);
  605. Cursor cursor = appCtx.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
  606. // use default destination of DownloadManager
  607. if (cursor != null) {
  608. cursor.moveToFirst();
  609. filePath = cursor.getString(0);
  610. cursor.close();
  611. }
  612. }
  613. }
  614. // When the file is not found in media content database, check if custom path exists
  615. if (options.addAndroidDownloads.hasKey("path")) {
  616. try {
  617. String customDest = options.addAndroidDownloads.getString("path");
  618. boolean exists = new File(customDest).exists();
  619. if(!exists)
  620. throw new Exception("Download manager download failed, the file does not downloaded to destination.");
  621. else
  622. this.callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, customDest);
  623. } catch(Exception ex) {
  624. ex.printStackTrace();
  625. this.callback.invoke(ex.getLocalizedMessage(), null);
  626. }
  627. }
  628. else {
  629. if(filePath == null)
  630. this.callback.invoke("Download manager could not resolve downloaded file path.", RNFetchBlobConst.RNFB_RESPONSE_PATH, null);
  631. else
  632. this.callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, filePath);
  633. }
  634. }
  635. }
  636. }
  637. public static OkHttpClient.Builder enableTls12OnPreLollipop(OkHttpClient.Builder client) {
  638. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
  639. try {
  640. // Code from https://stackoverflow.com/a/40874952/544779
  641. TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  642. trustManagerFactory.init((KeyStore) null);
  643. TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  644. if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
  645. throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
  646. }
  647. X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
  648. SSLContext sslContext = SSLContext.getInstance("SSL");
  649. sslContext.init(null, new TrustManager[] { trustManager }, null);
  650. SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
  651. client.sslSocketFactory(sslSocketFactory, trustManager);
  652. ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
  653. .tlsVersions(TlsVersion.TLS_1_2)
  654. .build();
  655. List< ConnectionSpec > specs = new ArrayList < > ();
  656. specs.add(cs);
  657. specs.add(ConnectionSpec.COMPATIBLE_TLS);
  658. specs.add(ConnectionSpec.CLEARTEXT);
  659. client.connectionSpecs(specs);
  660. } catch (Exception exc) {
  661. FLog.e("OkHttpClientProvider", "Error while enabling TLS 1.2", exc);
  662. }
  663. }
  664. return client;
  665. }
  666. }