No Description

RNFetchBlobReq.java 36KB

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