Ei kuvausta

RNFetchBlobReq.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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.util.Base64;
  10. import com.RNFetchBlob.Response.RNFetchBlobDefaultResp;
  11. import com.RNFetchBlob.Response.RNFetchBlobFileResp;
  12. import com.facebook.react.bridge.Arguments;
  13. import com.facebook.react.bridge.Callback;
  14. import com.facebook.react.bridge.ReactApplicationContext;
  15. import com.facebook.react.bridge.ReadableArray;
  16. import com.facebook.react.bridge.ReadableMap;
  17. import com.facebook.react.bridge.ReadableMapKeySetIterator;
  18. import com.facebook.react.bridge.WritableMap;
  19. import com.facebook.react.modules.core.DeviceEventManagerModule;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.net.MalformedURLException;
  25. import java.net.SocketTimeoutException;
  26. import java.net.URL;
  27. import java.net.URLEncoder;
  28. import java.nio.ByteBuffer;
  29. import java.nio.CharBuffer;
  30. import java.nio.charset.CharacterCodingException;
  31. import java.nio.charset.Charset;
  32. import java.nio.charset.CharsetEncoder;
  33. import java.util.HashMap;
  34. import java.util.concurrent.TimeUnit;
  35. import okhttp3.Call;
  36. import okhttp3.ConnectionPool;
  37. import okhttp3.Headers;
  38. import okhttp3.Interceptor;
  39. import okhttp3.MediaType;
  40. import okhttp3.OkHttpClient;
  41. import okhttp3.Request;
  42. import okhttp3.RequestBody;
  43. import okhttp3.Response;
  44. import okhttp3.ResponseBody;
  45. /**
  46. * Created by wkh237 on 2016/6/21.
  47. */
  48. public class RNFetchBlobReq extends BroadcastReceiver implements Runnable {
  49. enum RequestType {
  50. Form,
  51. SingleFile,
  52. AsIs,
  53. WithoutBody,
  54. Others
  55. };
  56. enum ResponseType {
  57. KeepInMemory,
  58. FileStorage
  59. };
  60. public static HashMap<String, Call> taskTable = new HashMap<>();
  61. static HashMap<String, Boolean> progressReport = new HashMap<>();
  62. static HashMap<String, Boolean> uploadProgressReport = new HashMap<>();
  63. static ConnectionPool pool = new ConnectionPool();
  64. ReactApplicationContext ctx;
  65. RNFetchBlobConfig options;
  66. String taskId;
  67. String method;
  68. String url;
  69. String rawRequestBody;
  70. String destPath;
  71. ReadableArray rawRequestBodyArray;
  72. ReadableMap headers;
  73. Callback callback;
  74. long contentLength;
  75. long downloadManagerId;
  76. RequestType requestType;
  77. ResponseType responseType;
  78. WritableMap respInfo;
  79. boolean timeout = false;
  80. public RNFetchBlobReq(ReadableMap options, String taskId, String method, String url, ReadableMap headers, String body, ReadableArray arrayBody, final Callback callback) {
  81. this.method = method.toUpperCase();
  82. this.options = new RNFetchBlobConfig(options);
  83. this.taskId = taskId;
  84. this.url = url;
  85. this.headers = headers;
  86. this.callback = callback;
  87. this.rawRequestBody = body;
  88. this.rawRequestBodyArray = arrayBody;
  89. if(this.options.fileCache || this.options.path != null)
  90. responseType = ResponseType.FileStorage;
  91. else
  92. responseType = ResponseType.KeepInMemory;
  93. if (body != null)
  94. requestType = RequestType.SingleFile;
  95. else if (arrayBody != null)
  96. requestType = RequestType.Form;
  97. else
  98. requestType = RequestType.WithoutBody;
  99. }
  100. public static void cancelTask(String taskId) {
  101. if(taskTable.containsKey(taskId)) {
  102. Call call = taskTable.get(taskId);
  103. call.cancel();
  104. taskTable.remove(taskId);
  105. }
  106. }
  107. @Override
  108. public void run() {
  109. // use download manager instead of default HTTP implementation
  110. if (options.addAndroidDownloads != null && options.addAndroidDownloads.hasKey("useDownloadManager")) {
  111. if (options.addAndroidDownloads.getBoolean("useDownloadManager")) {
  112. Uri uri = Uri.parse(url);
  113. DownloadManager.Request req = new DownloadManager.Request(uri);
  114. req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  115. if (options.addAndroidDownloads.hasKey("title")) {
  116. req.setTitle(options.addAndroidDownloads.getString("title"));
  117. }
  118. if (options.addAndroidDownloads.hasKey("description")) {
  119. req.setDescription(options.addAndroidDownloads.getString("description"));
  120. }
  121. // set headers
  122. ReadableMapKeySetIterator it = headers.keySetIterator();
  123. while (it.hasNextKey()) {
  124. String key = it.nextKey();
  125. req.addRequestHeader(key, headers.getString(key));
  126. }
  127. Context appCtx = RNFetchBlob.RCTContext.getApplicationContext();
  128. DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
  129. downloadManagerId = dm.enqueue(req);
  130. appCtx.registerReceiver(this, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
  131. return;
  132. }
  133. }
  134. // find cached result if `key` property exists
  135. String cacheKey = this.taskId;
  136. String ext = this.options.appendExt != "" ? "." + this.options.appendExt : "";
  137. if (this.options.key != null) {
  138. cacheKey = RNFetchBlobUtils.getMD5(this.options.key);
  139. if (cacheKey == null) {
  140. cacheKey = this.taskId;
  141. }
  142. File file = new File(RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext);
  143. if (file.exists()) {
  144. callback.invoke(null, file.getAbsolutePath());
  145. return;
  146. }
  147. }
  148. if(this.options.path != null)
  149. this.destPath = this.options.path;
  150. else if(this.options.fileCache == true)
  151. this.destPath = RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext;
  152. OkHttpClient.Builder clientBuilder;
  153. try {
  154. // use trusty SSL socket
  155. if (this.options.trusty) {
  156. clientBuilder = RNFetchBlobUtils.getUnsafeOkHttpClient();
  157. } else {
  158. clientBuilder = new OkHttpClient.Builder();
  159. }
  160. final Request.Builder builder = new Request.Builder();
  161. try {
  162. builder.url(new URL(url));
  163. } catch (MalformedURLException e) {
  164. e.printStackTrace();
  165. }
  166. HashMap<String, String> mheaders = new HashMap<>();
  167. // set headers
  168. if (headers != null) {
  169. ReadableMapKeySetIterator it = headers.keySetIterator();
  170. while (it.hasNextKey()) {
  171. String key = it.nextKey();
  172. String value = headers.getString(key);
  173. builder.header(key, value);
  174. mheaders.put(key,value);
  175. }
  176. }
  177. if(method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
  178. String cType = getHeaderIgnoreCases(mheaders, "Content-Type").toLowerCase();
  179. if(cType == null) {
  180. builder.header("Content-Type", "application/octet-stream");
  181. requestType = RequestType.SingleFile;
  182. }
  183. if(rawRequestBody != null) {
  184. if(rawRequestBody.startsWith(RNFetchBlobConst.FILE_PREFIX)) {
  185. requestType = RequestType.SingleFile;
  186. }
  187. else if (cType.toLowerCase().contains(";base64") || cType.toLowerCase().startsWith("application/octet")) {
  188. requestType = RequestType.SingleFile;
  189. } else {
  190. requestType = RequestType.AsIs;
  191. }
  192. }
  193. }
  194. else {
  195. requestType = RequestType.WithoutBody;
  196. }
  197. // set request body
  198. switch (requestType) {
  199. case SingleFile:
  200. builder.method(method, new RNFetchBlobBody(
  201. taskId,
  202. requestType,
  203. rawRequestBody,
  204. MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type"))
  205. ));
  206. break;
  207. case AsIs:
  208. builder.method(method, new RNFetchBlobBody(
  209. taskId,
  210. requestType,
  211. rawRequestBody,
  212. MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type"))
  213. ));
  214. break;
  215. case Form:
  216. builder.method(method, new RNFetchBlobBody(
  217. taskId,
  218. requestType,
  219. rawRequestBodyArray,
  220. MediaType.parse("multipart/form-data; boundary=RNFetchBlob-" + taskId)
  221. ));
  222. break;
  223. case WithoutBody:
  224. if(method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT"))
  225. {
  226. builder.method(method, RequestBody.create(null, new byte[0]));
  227. }
  228. else
  229. builder.method(method, null);
  230. break;
  231. }
  232. final Request req = builder.build();
  233. // Create response body depends on the responseType
  234. clientBuilder.addInterceptor(new Interceptor() {
  235. @Override
  236. public Response intercept(Chain chain) throws IOException {
  237. try {
  238. Response originalResponse = chain.proceed(req);
  239. ResponseBody extended;
  240. switch (responseType) {
  241. case KeepInMemory:
  242. extended = new RNFetchBlobDefaultResp(
  243. RNFetchBlob.RCTContext,
  244. taskId,
  245. originalResponse.body());
  246. break;
  247. case FileStorage:
  248. extended = new RNFetchBlobFileResp(
  249. RNFetchBlob.RCTContext,
  250. taskId,
  251. originalResponse.body(),
  252. destPath);
  253. break;
  254. default:
  255. extended = new RNFetchBlobDefaultResp(
  256. RNFetchBlob.RCTContext,
  257. taskId,
  258. originalResponse.body());
  259. break;
  260. }
  261. return originalResponse.newBuilder().body(extended).build();
  262. } catch(Exception ex) {
  263. timeout = true;
  264. }
  265. return chain.proceed(chain.request());
  266. }
  267. });
  268. if(options.timeout >= 0) {
  269. clientBuilder.connectTimeout(options.timeout, TimeUnit.MILLISECONDS);
  270. clientBuilder.readTimeout(options.timeout, TimeUnit.MILLISECONDS);
  271. }
  272. clientBuilder.connectionPool(pool);
  273. clientBuilder.retryOnConnectionFailure(false);
  274. clientBuilder.followRedirects(true);
  275. OkHttpClient client = clientBuilder.build();
  276. Call call = client.newCall(req);
  277. taskTable.put(taskId, call);
  278. call.enqueue(new okhttp3.Callback() {
  279. @Override
  280. public void onFailure(Call call, IOException e) {
  281. cancelTask(taskId);
  282. if(respInfo == null) {
  283. respInfo = Arguments.createMap();
  284. }
  285. // check if this error caused by socket timeout
  286. if(e.getClass().equals(SocketTimeoutException.class)) {
  287. respInfo.putBoolean("timeout", true);
  288. callback.invoke("request timed out.", null, null);
  289. }
  290. else
  291. callback.invoke(e.getLocalizedMessage(), null, null);
  292. removeTaskInfo();
  293. }
  294. @Override
  295. public void onResponse(Call call, Response response) throws IOException {
  296. ReadableMap notifyConfig = options.addAndroidDownloads;
  297. // Download manager settings
  298. if(notifyConfig != null ) {
  299. String title = "", desc = "", mime = "text/plain";
  300. boolean scannable = false, notification = false;
  301. if(notifyConfig.hasKey("title"))
  302. title = options.addAndroidDownloads.getString("title");
  303. if(notifyConfig.hasKey("description"))
  304. desc = notifyConfig.getString("description");
  305. if(notifyConfig.hasKey("mime"))
  306. mime = notifyConfig.getString("mime");
  307. if(notifyConfig.hasKey("mediaScannable"))
  308. scannable = notifyConfig.getBoolean("mediaScannable");
  309. if(notifyConfig.hasKey("notification"))
  310. notification = notifyConfig.getBoolean("notification");
  311. DownloadManager dm = (DownloadManager)RNFetchBlob.RCTContext.getSystemService(RNFetchBlob.RCTContext.DOWNLOAD_SERVICE);
  312. dm.addCompletedDownload(title, desc, scannable, mime, destPath, contentLength, notification);
  313. }
  314. done(response);
  315. }
  316. });
  317. } catch (Exception error) {
  318. error.printStackTrace();
  319. taskTable.remove(taskId);
  320. callback.invoke("RNFetchBlob request error: " + error.getMessage() + error.getCause());
  321. }
  322. }
  323. /**
  324. * Remove cached information of the HTTP task
  325. */
  326. private void removeTaskInfo() {
  327. if(taskTable.containsKey(taskId))
  328. taskTable.remove(taskId);
  329. if(uploadProgressReport.containsKey(taskId))
  330. uploadProgressReport.remove(taskId);
  331. if(progressReport.containsKey(taskId))
  332. progressReport.remove(taskId);
  333. }
  334. /**
  335. * Send response data back to javascript context.
  336. * @param resp OkHttp response object
  337. */
  338. private void done(Response resp) {
  339. boolean isBlobResp = isBlobResponse(resp);
  340. emitStateEvent(getResponseInfo(resp, isBlobResp));
  341. switch (responseType) {
  342. case KeepInMemory:
  343. try {
  344. // For XMLHttpRequest, automatic response data storing strategy, when response
  345. // data is considered as binary data, write it to file system
  346. if(isBlobResp && options.auto == true) {
  347. String dest = RNFetchBlobFS.getTmpPath(ctx, taskId);
  348. InputStream ins = resp.body().byteStream();
  349. FileOutputStream os = new FileOutputStream(new File(dest));
  350. int read;
  351. byte [] buffer = new byte[10240];
  352. while ((read = ins.read(buffer)) != -1) {
  353. os.write(buffer, 0, read);
  354. }
  355. ins.close();
  356. os.flush();
  357. os.close();
  358. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, dest);
  359. }
  360. // response data directly pass to JS context as string.
  361. else {
  362. // #73 Check if the response data contains valid UTF8 string, since BASE64
  363. // encoding will somehow break the UTF8 string format, to encode UTF8
  364. // string correctly, we should do URL encoding before BASE64.
  365. byte[] b = resp.body().bytes();
  366. CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
  367. try {
  368. encoder.encode(ByteBuffer.wrap(b).asCharBuffer());
  369. // if the data contains invalid characters the following lines will be
  370. // skipped.
  371. String utf8 = new String(b);
  372. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, utf8);
  373. }
  374. // This usually mean the data is contains invalid unicode characters, it's
  375. // binary data
  376. catch(CharacterCodingException ignored) {
  377. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_BASE64, android.util.Base64.encodeToString(b, Base64.NO_WRAP));
  378. }
  379. }
  380. } catch (IOException e) {
  381. callback.invoke("RNFetchBlob failed to encode response data to BASE64 string.", null);
  382. }
  383. break;
  384. case FileStorage:
  385. try {
  386. // In order to write response data to `destPath` we have to invoke this method.
  387. // It uses customized response body which is able to report download progress
  388. // and write response data to destination path.
  389. resp.body().bytes();
  390. } catch (Exception ignored) {}
  391. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_PATH, this.destPath);
  392. break;
  393. default:
  394. try {
  395. callback.invoke(null, RNFetchBlobConst.RNFB_RESPONSE_UTF8, new String(resp.body().bytes(), "UTF-8"));
  396. } catch (IOException e) {
  397. callback.invoke("RNFetchBlob failed to encode response data to UTF8 string.", null);
  398. }
  399. break;
  400. }
  401. removeTaskInfo();
  402. }
  403. /**
  404. * Invoke this method to enable download progress reporting.
  405. * @param taskId Task ID of the HTTP task.
  406. * @return Task ID of the target task
  407. */
  408. public static boolean isReportProgress(String taskId) {
  409. if(!progressReport.containsKey(taskId)) return false;
  410. return progressReport.get(taskId);
  411. }
  412. /**
  413. * Invoke this method to enable download progress reporting.
  414. * @param taskId Task ID of the HTTP task.
  415. * @return Task ID of the target task
  416. */
  417. public static boolean isReportUploadProgress(String taskId) {
  418. if(!uploadProgressReport.containsKey(taskId)) return false;
  419. return uploadProgressReport.get(taskId);
  420. }
  421. /**
  422. * Create response information object, conatins status code, headers, etc.
  423. * @param resp
  424. * @param isBlobResp
  425. * @return
  426. */
  427. private WritableMap getResponseInfo(Response resp, boolean isBlobResp) {
  428. WritableMap info = Arguments.createMap();
  429. info.putInt("status", resp.code());
  430. info.putString("state", "2");
  431. info.putString("taskId", this.taskId);
  432. info.putBoolean("timeout", timeout);
  433. WritableMap headers = Arguments.createMap();
  434. for(int i =0;i< resp.headers().size();i++) {
  435. headers.putString(resp.headers().name(i), resp.headers().value(i));
  436. }
  437. info.putMap("headers", headers);
  438. Headers h = resp.headers();
  439. if(isBlobResp) {
  440. info.putString("respType", "blob");
  441. }
  442. else if(getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("text/")) {
  443. info.putString("respType", "text");
  444. }
  445. else if(getHeaderIgnoreCases(h, "content-type").contains("application/json")) {
  446. info.putString("respType", "json");
  447. }
  448. else {
  449. info.putString("respType", "");
  450. }
  451. return info;
  452. }
  453. /**
  454. * Check if response data is binary data.
  455. * @param resp OkHttp response.
  456. * @return
  457. */
  458. private boolean isBlobResponse(Response resp) {
  459. Headers h = resp.headers();
  460. String ctype = getHeaderIgnoreCases(h, "Content-Type");
  461. boolean isText = !ctype.equalsIgnoreCase("text/");
  462. boolean isJSON = !ctype.equalsIgnoreCase("application/json");
  463. boolean isCustomBinary = false;
  464. if(options.binaryContentTypes != null) {
  465. for(int i = 0; i< options.binaryContentTypes.size();i++) {
  466. if(ctype.toLowerCase().contains(options.binaryContentTypes.getString(i).toLowerCase())) {
  467. isCustomBinary = true;
  468. break;
  469. }
  470. }
  471. }
  472. return (!(isJSON || isText)) || isCustomBinary;
  473. }
  474. private String getHeaderIgnoreCases(Headers headers, String field) {
  475. String val = headers.get(field);
  476. if(val != null) return val;
  477. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  478. }
  479. private String getHeaderIgnoreCases(HashMap<String,String> headers, String field) {
  480. String val = headers.get(field);
  481. if(val != null) return val;
  482. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  483. }
  484. private void emitStateEvent(WritableMap args) {
  485. RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  486. .emit(RNFetchBlobConst.EVENT_HTTP_STATE, args);
  487. }
  488. @Override
  489. public void onReceive(Context context, Intent intent) {
  490. String action = intent.getAction();
  491. if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
  492. Context appCtx = RNFetchBlob.RCTContext.getApplicationContext();
  493. long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
  494. if (id == this.downloadManagerId) {
  495. DownloadManager.Query query = new DownloadManager.Query();
  496. query.setFilterById(downloadManagerId);
  497. DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
  498. dm.query(query);
  499. Cursor c = dm.query(query);
  500. if (c.moveToFirst()) {
  501. String contentUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
  502. Uri uri = Uri.parse(contentUri);
  503. Cursor cursor = appCtx.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
  504. if (cursor != null) {
  505. cursor.moveToFirst();
  506. String filePath = cursor.getString(0);
  507. cursor.close();
  508. this.callback.invoke(null, null, filePath);
  509. }
  510. else
  511. this.callback.invoke(null, null, null);
  512. }
  513. }
  514. }
  515. }
  516. }