No Description

RNFetchBlobReq.java 35KB

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