No Description

RNFetchBlobReq.java 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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;
  528. try {
  529. rnFetchBlobFileResp = (RNFetchBlobFileResp) responseBody;
  530. } catch (ClassCastException ex) {
  531. // unexpected response type
  532. if (responseBody != null) {
  533. String responseBodyString = null;
  534. try {
  535. boolean isBufferDataExists = responseBody.source().buffer().size() > 0;
  536. boolean isContentExists = responseBody.contentLength() > 0;
  537. if (isBufferDataExists && isContentExists) {
  538. responseBodyString = responseBody.string();
  539. }
  540. } catch(IOException exception) {
  541. exception.printStackTrace();
  542. }
  543. callback.invoke("Unexpected FileStorage response file: " + responseBodyString, null);
  544. } else {
  545. callback.invoke("Unexpected FileStorage response with no file.", null);
  546. }
  547. return;
  548. }
  549. if(rnFetchBlobFileResp != null && !rnFetchBlobFileResp.isDownloadComplete()){
  550. callback.invoke("Download interrupted.", null);
  551. }
  552. else {
  553. this.destPath = this.destPath.replace("?append=true", "");
  554. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, this.destPath);
  555. }
  556. break;
  557. default:
  558. try {
  559. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, new String(resp.body().bytes(), "UTF-8"));
  560. } catch (IOException e) {
  561. callback.invoke("RNFetchBlob failed to encode response data to UTF8 string.", null);
  562. }
  563. break;
  564. }
  565. // if(!resp.isSuccessful())
  566. resp.body().close();
  567. releaseTaskResource();
  568. }
  569. /**
  570. * Invoke this method to enable download progress reporting.
  571. * @param taskId Task ID of the HTTP task.
  572. * @return Task ID of the target task
  573. */
  574. public static RNFetchBlobProgressConfig getReportProgress(String taskId) {
  575. if(!progressReport.containsKey(taskId)) return null;
  576. return progressReport.get(taskId);
  577. }
  578. /**
  579. * Invoke this method to enable download progress reporting.
  580. * @param taskId Task ID of the HTTP task.
  581. * @return Task ID of the target task
  582. */
  583. public static RNFetchBlobProgressConfig getReportUploadProgress(String taskId) {
  584. if(!uploadProgressReport.containsKey(taskId)) return null;
  585. return uploadProgressReport.get(taskId);
  586. }
  587. /**
  588. * Create response information object, contains status code, headers, etc.
  589. * @param resp Response object
  590. * @param isBlobResp If the response is binary data
  591. * @return Get RCT bridge object contains response information.
  592. */
  593. private WritableMap getResponseInfo(Response resp, boolean isBlobResp) {
  594. WritableMap info = Arguments.createMap();
  595. info.putInt("status", resp.code());
  596. info.putString("state", "2");
  597. info.putString("taskId", this.taskId);
  598. info.putBoolean("timeout", timeout);
  599. WritableMap headers = Arguments.createMap();
  600. for(int i =0;i< resp.headers().size();i++) {
  601. headers.putString(resp.headers().name(i), resp.headers().value(i));
  602. }
  603. WritableArray redirectList = Arguments.createArray();
  604. for(String r : redirects) {
  605. redirectList.pushString(r);
  606. }
  607. info.putArray("redirects", redirectList);
  608. info.putMap("headers", headers);
  609. Headers h = resp.headers();
  610. if(isBlobResp) {
  611. info.putString("respType", "blob");
  612. }
  613. else if(getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("text/")) {
  614. info.putString("respType", "text");
  615. }
  616. else if(getHeaderIgnoreCases(h, "content-type").contains("application/json")) {
  617. info.putString("respType", "json");
  618. }
  619. else {
  620. info.putString("respType", "");
  621. }
  622. return info;
  623. }
  624. /**
  625. * Check if response data is binary data.
  626. * @param resp OkHttp response.
  627. * @return If the response data contains binary bytes
  628. */
  629. private boolean isBlobResponse(Response resp) {
  630. Headers h = resp.headers();
  631. String ctype = getHeaderIgnoreCases(h, "Content-Type");
  632. boolean isText = !ctype.equalsIgnoreCase("text/");
  633. boolean isJSON = !ctype.equalsIgnoreCase("application/json");
  634. boolean isCustomBinary = false;
  635. if(options.binaryContentTypes != null) {
  636. for(int i = 0; i< options.binaryContentTypes.size();i++) {
  637. if(ctype.toLowerCase().contains(options.binaryContentTypes.getString(i).toLowerCase())) {
  638. isCustomBinary = true;
  639. break;
  640. }
  641. }
  642. }
  643. return (!(isJSON || isText)) || isCustomBinary;
  644. }
  645. private String getHeaderIgnoreCases(Headers headers, String field) {
  646. String val = headers.get(field);
  647. if(val != null) return val;
  648. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  649. }
  650. private String getHeaderIgnoreCases(HashMap<String,String> headers, String field) {
  651. String val = headers.get(field);
  652. if(val != null) return val;
  653. String lowerCasedValue = headers.get(field.toLowerCase());
  654. return lowerCasedValue == null ? "" : lowerCasedValue;
  655. }
  656. private void emitStateEvent(WritableMap args) {
  657. RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  658. .emit(RNFetchBlobConst.EVENT_HTTP_STATE, args);
  659. }
  660. @Override
  661. public void onReceive(Context context, Intent intent) {
  662. String action = intent.getAction();
  663. if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
  664. Context appCtx = RNFetchBlob.RCTContext.getApplicationContext();
  665. long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
  666. if (id == this.downloadManagerId) {
  667. releaseTaskResource(); // remove task ID from task map
  668. DownloadManager.Query query = new DownloadManager.Query();
  669. query.setFilterById(downloadManagerId);
  670. DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
  671. dm.query(query);
  672. Cursor c = dm.query(query);
  673. // #236 unhandled null check for DownloadManager.query() return value
  674. if (c == null) {
  675. this.callback.invoke("Download manager failed to download from " + this.url + ". Query was unsuccessful ", null, null);
  676. return;
  677. }
  678. String filePath = null;
  679. try {
  680. // the file exists in media content database
  681. if (c.moveToFirst()) {
  682. // #297 handle failed request
  683. int statusCode = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
  684. if(statusCode == DownloadManager.STATUS_FAILED) {
  685. this.callback.invoke("Download manager failed to download from " + this.url + ". Status Code = " + statusCode, null, null);
  686. return;
  687. }
  688. String contentUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
  689. if ( contentUri != null &&
  690. options.addAndroidDownloads.hasKey("mime") &&
  691. options.addAndroidDownloads.getString("mime").contains("image")) {
  692. Uri uri = Uri.parse(contentUri);
  693. Cursor cursor = appCtx.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
  694. // use default destination of DownloadManager
  695. if (cursor != null) {
  696. cursor.moveToFirst();
  697. filePath = cursor.getString(0);
  698. cursor.close();
  699. }
  700. }
  701. }
  702. } finally {
  703. if (c != null) {
  704. c.close();
  705. }
  706. }
  707. // When the file is not found in media content database, check if custom path exists
  708. if (options.addAndroidDownloads.hasKey("path")) {
  709. try {
  710. String customDest = options.addAndroidDownloads.getString("path");
  711. boolean exists = new File(customDest).exists();
  712. if(!exists)
  713. throw new Exception("Download manager download failed, the file does not downloaded to destination.");
  714. else
  715. this.callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, customDest);
  716. } catch(Exception ex) {
  717. ex.printStackTrace();
  718. this.callback.invoke(ex.getLocalizedMessage(), null);
  719. }
  720. }
  721. else {
  722. if(filePath == null)
  723. this.callback.invoke("Download manager could not resolve downloaded file path.", RNFetchBlobConst.RNFB_RESPONSE_PATH, null);
  724. else
  725. this.callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, filePath);
  726. }
  727. }
  728. }
  729. }
  730. public static OkHttpClient.Builder enableTls12OnPreLollipop(OkHttpClient.Builder client) {
  731. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
  732. try {
  733. // Code from https://stackoverflow.com/a/40874952/544779
  734. TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  735. trustManagerFactory.init((KeyStore) null);
  736. TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  737. if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
  738. throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
  739. }
  740. X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
  741. SSLContext sslContext = SSLContext.getInstance("SSL");
  742. sslContext.init(null, new TrustManager[] { trustManager }, null);
  743. SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
  744. client.sslSocketFactory(sslSocketFactory, trustManager);
  745. ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
  746. .tlsVersions(TlsVersion.TLS_1_2)
  747. .build();
  748. List< ConnectionSpec > specs = new ArrayList < > ();
  749. specs.add(cs);
  750. specs.add(ConnectionSpec.COMPATIBLE_TLS);
  751. specs.add(ConnectionSpec.CLEARTEXT);
  752. client.connectionSpecs(specs);
  753. } catch (Exception exc) {
  754. FLog.e("OkHttpClientProvider", "Error while enabling TLS 1.2", exc);
  755. }
  756. }
  757. return client;
  758. }
  759. }