Aucune description

RNFetchBlobReq.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 android.util.Log;
  11. import com.RNFetchBlob.Response.RNFetchBlobDefaultResp;
  12. import com.RNFetchBlob.Response.RNFetchBlobFileResp;
  13. import com.facebook.react.bridge.Arguments;
  14. import com.facebook.react.bridge.Callback;
  15. import com.facebook.react.bridge.ReactApplicationContext;
  16. import com.facebook.react.bridge.ReadableArray;
  17. import com.facebook.react.bridge.ReadableMap;
  18. import com.facebook.react.bridge.ReadableMapKeySetIterator;
  19. import com.facebook.react.bridge.WritableMap;
  20. import com.facebook.react.modules.core.DeviceEventManagerModule;
  21. import java.io.ByteArrayInputStream;
  22. import java.io.File;
  23. import java.io.FileInputStream;
  24. import java.io.FileOutputStream;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.net.MalformedURLException;
  28. import java.net.SocketTimeoutException;
  29. import java.net.URL;
  30. import java.util.HashMap;
  31. import java.util.concurrent.TimeUnit;
  32. import okhttp3.Call;
  33. import okhttp3.Headers;
  34. import okhttp3.Interceptor;
  35. import okhttp3.MediaType;
  36. import okhttp3.OkHttpClient;
  37. import okhttp3.Request;
  38. import okhttp3.RequestBody;
  39. import okhttp3.Response;
  40. import okhttp3.ResponseBody;
  41. import okhttp3.FormBody;
  42. import okhttp3.internal.framed.Header;
  43. import okhttp3.internal.http.OkHeaders;
  44. /**
  45. * Created by wkh237 on 2016/6/21.
  46. */
  47. public class RNFetchBlobReq extends BroadcastReceiver implements Runnable {
  48. enum RequestType {
  49. Form,
  50. SingleFile,
  51. AsIs,
  52. WithoutBody,
  53. Others
  54. };
  55. enum ResponseType {
  56. KeepInMemory,
  57. FileStorage
  58. };
  59. static HashMap<String, Call> taskTable = new HashMap<>();
  60. MediaType contentType = RNFetchBlobConst.MIME_OCTET;
  61. ReactApplicationContext ctx;
  62. RNFetchBlobConfig options;
  63. String taskId;
  64. String method;
  65. String url;
  66. String rawRequestBody;
  67. String destPath;
  68. ReadableArray rawRequestBodyArray;
  69. ReadableMap headers;
  70. Callback callback;
  71. long contentLength;
  72. long downloadManagerId;
  73. RequestType requestType;
  74. ResponseType responseType;
  75. boolean timeout = false;
  76. public RNFetchBlobReq(ReadableMap options, String taskId, String method, String url, ReadableMap headers, String body, ReadableArray arrayBody, final Callback callback) {
  77. this.method = method;
  78. this.options = new RNFetchBlobConfig(options);
  79. this.taskId = taskId;
  80. this.url = url;
  81. this.headers = headers;
  82. this.callback = callback;
  83. this.rawRequestBody = body;
  84. this.rawRequestBodyArray = arrayBody;
  85. if(this.options.fileCache || this.options.path != null)
  86. responseType = ResponseType.FileStorage;
  87. else
  88. responseType = ResponseType.KeepInMemory;
  89. if (body != null)
  90. requestType = RequestType.SingleFile;
  91. else if (arrayBody != null)
  92. requestType = RequestType.Form;
  93. else
  94. requestType = RequestType.WithoutBody;
  95. }
  96. public static void cancelTask(String taskId) {
  97. if(taskTable.containsKey(taskId)) {
  98. Call call = taskTable.get(taskId);
  99. call.cancel();
  100. taskTable.remove(taskId);
  101. }
  102. }
  103. @Override
  104. public void run() {
  105. // use download manager instead of default HTTP implementation
  106. if (options.addAndroidDownloads != null && options.addAndroidDownloads.hasKey("useDownloadManager")) {
  107. if (options.addAndroidDownloads.getBoolean("useDownloadManager")) {
  108. Uri uri = Uri.parse(url);
  109. DownloadManager.Request req = new DownloadManager.Request(uri);
  110. req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  111. if (options.addAndroidDownloads.hasKey("title")) {
  112. req.setTitle(options.addAndroidDownloads.getString("title"));
  113. }
  114. if (options.addAndroidDownloads.hasKey("description")) {
  115. req.setDescription(options.addAndroidDownloads.getString("description"));
  116. }
  117. // set headers
  118. ReadableMapKeySetIterator it = headers.keySetIterator();
  119. while (it.hasNextKey()) {
  120. String key = it.nextKey();
  121. req.addRequestHeader(key, headers.getString(key));
  122. }
  123. Context appCtx = RNFetchBlob.RCTContext.getApplicationContext();
  124. DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
  125. downloadManagerId = dm.enqueue(req);
  126. appCtx.registerReceiver(this, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
  127. return;
  128. }
  129. }
  130. // find cached result if `key` property exists
  131. String cacheKey = this.taskId;
  132. String ext = this.options.appendExt != "" ? "." + this.options.appendExt : "";
  133. if (this.options.key != null) {
  134. cacheKey = RNFetchBlobUtils.getMD5(this.options.key);
  135. if (cacheKey == null) {
  136. cacheKey = this.taskId;
  137. }
  138. File file = new File(RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext);
  139. if (file.exists()) {
  140. callback.invoke(null, file.getAbsolutePath());
  141. return;
  142. }
  143. }
  144. if(this.options.path != null)
  145. this.destPath = this.options.path;
  146. else if(this.options.fileCache == true)
  147. this.destPath = RNFetchBlobFS.getTmpPath(RNFetchBlob.RCTContext, cacheKey) + ext;
  148. OkHttpClient.Builder clientBuilder;
  149. try {
  150. // use trusty SSL socket
  151. if (this.options.trusty) {
  152. clientBuilder = RNFetchBlobUtils.getUnsafeOkHttpClient();
  153. } else {
  154. clientBuilder = new OkHttpClient.Builder();
  155. }
  156. final Request.Builder builder = new Request.Builder();
  157. try {
  158. builder.url(new URL(url));
  159. } catch (MalformedURLException e) {
  160. e.printStackTrace();
  161. }
  162. HashMap<String, String> mheaders = new HashMap<>();
  163. // set headers
  164. if (headers != null) {
  165. ReadableMapKeySetIterator it = headers.keySetIterator();
  166. while (it.hasNextKey()) {
  167. String key = it.nextKey();
  168. String value = headers.getString(key);
  169. builder.header(key, value);
  170. mheaders.put(key,value);
  171. }
  172. }
  173. if(method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
  174. String cType = getHeaderIgnoreCases(mheaders, "content-type").toLowerCase();
  175. if(cType == null) {
  176. builder.header("Content-Type", "application/octet-stream");
  177. requestType = RequestType.SingleFile;
  178. }
  179. if(rawRequestBody != null) {
  180. if(rawRequestBody.startsWith(RNFetchBlobConst.FILE_PREFIX)) {
  181. requestType = RequestType.SingleFile;
  182. }
  183. else if (cType.contains(";base64") || cType.startsWith("application/octet")) {
  184. requestType = RequestType.SingleFile;
  185. } else {
  186. requestType = RequestType.AsIs;
  187. }
  188. }
  189. }
  190. else {
  191. requestType = RequestType.WithoutBody;
  192. }
  193. // set request body
  194. switch (requestType) {
  195. case SingleFile:
  196. builder.method(method, new RNFetchBlobBody(
  197. taskId,
  198. requestType,
  199. rawRequestBody,
  200. MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type"))
  201. ));
  202. break;
  203. case AsIs:
  204. builder.method(method, new RNFetchBlobBody(
  205. taskId,
  206. requestType,
  207. rawRequestBody,
  208. MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type"))
  209. ));
  210. break;
  211. case Form:
  212. builder.method(method, new RNFetchBlobBody(
  213. taskId,
  214. requestType,
  215. rawRequestBodyArray,
  216. MediaType.parse("multipart/form-data; boundary=RNFetchBlob-" + taskId)
  217. ));
  218. break;
  219. case WithoutBody:
  220. builder.method(method, null);
  221. break;
  222. }
  223. final Request req = builder.build();
  224. // create response handler
  225. clientBuilder.addInterceptor(new Interceptor() {
  226. @Override
  227. public Response intercept(Chain chain) throws IOException {
  228. try {
  229. Response originalResponse = chain.proceed(req);
  230. ResponseBody extended;
  231. switch (responseType) {
  232. case KeepInMemory:
  233. extended = new RNFetchBlobDefaultResp(
  234. RNFetchBlob.RCTContext,
  235. taskId,
  236. originalResponse.body());
  237. break;
  238. case FileStorage:
  239. extended = new RNFetchBlobFileResp(
  240. RNFetchBlob.RCTContext,
  241. taskId,
  242. originalResponse.body(),
  243. destPath);
  244. break;
  245. default:
  246. extended = new RNFetchBlobDefaultResp(
  247. RNFetchBlob.RCTContext,
  248. taskId,
  249. originalResponse.body());
  250. break;
  251. }
  252. return originalResponse.newBuilder().body(extended).build();
  253. } catch(SocketTimeoutException ex) {
  254. timeout = true;
  255. }
  256. return chain.proceed(chain.request());
  257. }
  258. });
  259. if(options.timeout != -1) {
  260. clientBuilder.connectTimeout(options.timeout, TimeUnit.SECONDS);
  261. }
  262. OkHttpClient client = clientBuilder.build();
  263. Call call = client.newCall(req);
  264. taskTable.put(taskId, call);
  265. call.enqueue(new okhttp3.Callback() {
  266. @Override
  267. public void onFailure(Call call, IOException e) {
  268. callback.invoke(e.getLocalizedMessage(), null);
  269. }
  270. @Override
  271. public void onResponse(Call call, Response response) throws IOException {
  272. ReadableMap notifyConfig = options.addAndroidDownloads;
  273. // Download manager settings
  274. if(notifyConfig != null ) {
  275. String title = "", desc = "", mime = "text/plain";
  276. boolean scannable = false, notification = false;
  277. if(notifyConfig.hasKey("title"))
  278. title = options.addAndroidDownloads.getString("title");
  279. if(notifyConfig.hasKey("description"))
  280. desc = notifyConfig.getString("description");
  281. if(notifyConfig.hasKey("mime"))
  282. mime = notifyConfig.getString("mime");
  283. if(notifyConfig.hasKey("mediaScannable"))
  284. scannable = notifyConfig.getBoolean("mediaScannable");
  285. if(notifyConfig.hasKey("notification"))
  286. notification = notifyConfig.getBoolean("notification");
  287. DownloadManager dm = (DownloadManager)RNFetchBlob.RCTContext.getSystemService(RNFetchBlob.RCTContext.DOWNLOAD_SERVICE);
  288. dm.addCompletedDownload(title, desc, scannable, mime, destPath, contentLength, notification);
  289. }
  290. done(response);
  291. }
  292. });
  293. } catch (Exception error) {
  294. error.printStackTrace();
  295. taskTable.remove(taskId);
  296. callback.invoke("RNFetchBlob request error: " + error.getMessage() + error.getCause());
  297. }
  298. }
  299. /**
  300. * Send response data back to javascript context.
  301. * @param resp OkHttp response object
  302. */
  303. private void done(Response resp) {
  304. emitStateEvent(getResponseInfo(resp));
  305. switch (responseType) {
  306. case KeepInMemory:
  307. try {
  308. // For XMLHttpRequest, automatic response data storing strategy, when response
  309. // header is not `application/json` or `text/plain`, write response data to
  310. // file system.
  311. if(isBlobResponse(resp) && options.auto == true) {
  312. String dest = RNFetchBlobFS.getTmpPath(ctx, taskId);
  313. InputStream ins = resp.body().byteStream();
  314. FileOutputStream os = new FileOutputStream(new File(dest));
  315. byte [] buffer = new byte[10240];
  316. int read = ins.read(buffer);
  317. os.write(buffer,0,read);
  318. while(read > 0) {
  319. os.write(buffer,0,read);
  320. read = ins.read(buffer);
  321. }
  322. ins.close();
  323. os.close();
  324. WritableMap info = getResponseInfo(resp);
  325. callback.invoke(null, info, dest);
  326. }
  327. else {
  328. byte[] b = resp.body().bytes();
  329. callback.invoke(null, getResponseInfo(resp), android.util.Base64.encodeToString(b, Base64.NO_WRAP));
  330. }
  331. } catch (IOException e) {
  332. callback.invoke("RNFetchBlob failed to encode response data to BASE64 string.", null);
  333. }
  334. break;
  335. case FileStorage:
  336. try{
  337. resp.body().bytes();
  338. } catch (Exception ignored) {
  339. }
  340. callback.invoke(null, getResponseInfo(resp), this.destPath);
  341. break;
  342. default:
  343. try {
  344. callback.invoke(null, getResponseInfo(resp), new String(resp.body().bytes(), "UTF-8"));
  345. } catch (IOException e) {
  346. callback.invoke("RNFetchBlob failed to encode response data to UTF8 string.", null);
  347. }
  348. break;
  349. }
  350. if(taskTable.containsKey(taskId))
  351. taskTable.remove(taskId);
  352. }
  353. private WritableMap getResponseInfo(Response resp) {
  354. WritableMap info = Arguments.createMap();
  355. info.putInt("status", resp.code());
  356. info.putString("state", "2");
  357. info.putString("taskId", this.taskId);
  358. info.putBoolean("timeout", timeout);
  359. WritableMap headers = Arguments.createMap();
  360. for(int i =0;i< resp.headers().size();i++) {
  361. headers.putString(resp.headers().name(i), resp.headers().value(i));
  362. }
  363. info.putMap("headers", headers);
  364. Headers h = resp.headers();
  365. if(getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("text/plain")) {
  366. info.putString("respType", "text");
  367. }
  368. else if(getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("application/json")) {
  369. info.putString("respType", "json");
  370. }
  371. else if(getHeaderIgnoreCases(h, "content-type").length() < 1) {
  372. info.putString("respType", "blob");
  373. }
  374. else {
  375. info.putString("respType", "text");
  376. }
  377. return info;
  378. }
  379. private boolean isBlobResponse(Response resp) {
  380. Headers h = resp.headers();
  381. boolean isText = !getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("text/");
  382. boolean isJSON = !getHeaderIgnoreCases(h, "content-type").equalsIgnoreCase("application/json");
  383. return !(isJSON || isText);
  384. }
  385. private String getHeaderIgnoreCases(Headers headers, String field) {
  386. String val = headers.get(field);
  387. if(val != null) return val;
  388. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  389. }
  390. private String getHeaderIgnoreCases(HashMap<String,String> headers, String field) {
  391. String val = headers.get(field);
  392. if(val != null) return val;
  393. return headers.get(field.toLowerCase()) == null ? "" : headers.get(field.toLowerCase());
  394. }
  395. private void emitStateEvent(WritableMap args) {
  396. RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  397. .emit(RNFetchBlobConst.EVENT_HTTP_STATE, args);
  398. }
  399. @Override
  400. public void onReceive(Context context, Intent intent) {
  401. String action = intent.getAction();
  402. if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
  403. Context appCtx = RNFetchBlob.RCTContext.getApplicationContext();
  404. long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
  405. if (id == this.downloadManagerId) {
  406. DownloadManager.Query query = new DownloadManager.Query();
  407. query.setFilterById(downloadManagerId);
  408. DownloadManager dm = (DownloadManager) appCtx.getSystemService(Context.DOWNLOAD_SERVICE);
  409. dm.query(query);
  410. Cursor c = dm.query(query);
  411. if (c.moveToFirst()) {
  412. String contentUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
  413. Uri uri = Uri.parse(contentUri);
  414. Cursor cursor = appCtx.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
  415. if (cursor != null) {
  416. cursor.moveToFirst();
  417. String filePath = cursor.getString(0);
  418. cursor.close();
  419. this.callback.invoke(null, null, filePath);
  420. }
  421. else
  422. this.callback.invoke(null, null, null);
  423. }
  424. }
  425. }
  426. }
  427. }