No Description

index.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. // Copyright 2016 wkh237@github. All rights reserved.
  2. // Use of this source code is governed by a MIT-style license that can be
  3. // found in the LICENSE file.
  4. import {
  5. NativeModules,
  6. DeviceEventEmitter,
  7. NativeAppEventEmitter,
  8. Platform,
  9. AppState,
  10. } from 'react-native'
  11. import type {
  12. RNFetchBlobNative,
  13. RNFetchBlobConfig,
  14. RNFetchBlobStream,
  15. RNFetchBlobResponseInfo
  16. } from './types'
  17. import URIUtil from './utils/uri'
  18. //import StatefulPromise from './class/StatefulPromise.js'
  19. import fs from './fs'
  20. import getUUID from './utils/uuid'
  21. import base64 from 'base-64'
  22. import polyfill from './polyfill'
  23. import _ from 'lodash'
  24. import android from './android'
  25. import ios from './ios'
  26. import JSONStream from './json-stream'
  27. const {
  28. RNFetchBlobSession,
  29. readStream,
  30. createFile,
  31. unlink,
  32. exists,
  33. mkdir,
  34. session,
  35. writeStream,
  36. readFile,
  37. ls,
  38. isDir,
  39. mv,
  40. cp
  41. } = fs
  42. const Blob = polyfill.Blob
  43. const emitter = DeviceEventEmitter
  44. const RNFetchBlob = NativeModules.RNFetchBlob
  45. // when app resumes, check if there's any expired network task and trigger
  46. // their .expire event
  47. if(Platform.OS === 'ios') {
  48. AppState.addEventListener('change', (e) => {
  49. if(e === 'active')
  50. RNFetchBlob.emitExpiredEvent(()=>{})
  51. })
  52. }
  53. // register message channel event handler.
  54. emitter.addListener("RNFetchBlobMessage", (e) => {
  55. if(e.event === 'warn') {
  56. console.warn(e.detail)
  57. }
  58. else if (e.event === 'error') {
  59. throw e.detail
  60. }
  61. else {
  62. console.log("RNFetchBlob native message", e.detail)
  63. }
  64. })
  65. // Show warning if native module not detected
  66. if(!RNFetchBlob || !RNFetchBlob.fetchBlobForm || !RNFetchBlob.fetchBlob) {
  67. console.warn(
  68. 'rn-fetch-blob could not find valid native module.',
  69. 'please make sure you have linked native modules using `rnpm link`,',
  70. 'and restart RN packager or manually compile IOS/Android project.'
  71. )
  72. }
  73. function wrap(path:string):string {
  74. const prefix = path.startsWith('content://') ? 'RNFetchBlob-content://' : 'RNFetchBlob-file://'
  75. return prefix + path
  76. }
  77. /**
  78. * Calling this method will inject configurations into followed `fetch` method.
  79. * @param {RNFetchBlobConfig} options
  80. * Fetch API configurations, contains the following options :
  81. * @property {boolean} fileCache
  82. * When fileCache is `true`, response data will be saved in
  83. * storage with a random generated file name, rather than
  84. * a BASE64 encoded string.
  85. * @property {string} appendExt
  86. * Set this property to change file extension of random-
  87. * generated file name.
  88. * @property {string} path
  89. * If this property has a valid string format, resonse data
  90. * will be saved to specific file path. Default string format
  91. * is : `RNFetchBlob-file://path-to-file`
  92. * @property {string} key
  93. * If this property is set, it will be converted to md5, to
  94. * check if a file with this name exists.
  95. * If it exists, the absolute path is returned (no network
  96. * activity takes place )
  97. * If it doesn't exist, the file is downloaded as usual
  98. * @property {number} timeout
  99. * Request timeout in millionseconds, by default it's 60000ms.
  100. * @property {boolean} followRedirect
  101. * Follow redirects automatically, default true
  102. * @property {boolean} trusty
  103. * Trust all certificates
  104. * @property {boolean} wifiOnly
  105. * Only do requests through WiFi. Android SDK 21 or above only.
  106. *
  107. * @return {function} This method returns a `fetch` method instance.
  108. */
  109. function config (options:RNFetchBlobConfig) {
  110. return { fetch : fetch.bind(options) }
  111. }
  112. /**
  113. * Fetch from file system, use the same interface as RNFB.fetch
  114. * @param {RNFetchBlobConfig} [options={}] Fetch configurations
  115. * @param {string} method Should be one of `get`, `post`, `put`
  116. * @param {string} url A file URI string
  117. * @param {string} headers Arguments of file system API
  118. * @param {any} body Data to put or post to file systen.
  119. * @return {Promise}
  120. */
  121. function fetchFile(options = {}, method, url, headers = {}, body):Promise {
  122. if(!URIUtil.isFileURI(url)) {
  123. throw `could not fetch file from an invalid URI : ${url}`
  124. }
  125. url = URIUtil.unwrapFileURI(url)
  126. let promise = null
  127. let cursor = 0
  128. let total = -1
  129. let cacheData = ''
  130. let info = null
  131. let _progress, _uploadProgress, _stateChange
  132. switch(method.toLowerCase()) {
  133. case 'post':
  134. break
  135. case 'put':
  136. break
  137. // read data from file system
  138. default:
  139. promise = fs.stat(url)
  140. .then((stat) => {
  141. total = stat.size
  142. return fs.readStream(url,
  143. headers.encoding || 'utf8',
  144. Math.floor(headers.bufferSize) || 409600,
  145. Math.floor(headers.interval) || 100
  146. )
  147. })
  148. .then((stream) => new Promise((resolve, reject) => {
  149. stream.open()
  150. info = {
  151. state : "2",
  152. headers : { 'source' : 'system-fs' },
  153. status : 200,
  154. respType : 'text',
  155. rnfbEncode : headers.encoding || 'utf8'
  156. }
  157. _stateChange(info)
  158. stream.onData((chunk) => {
  159. _progress && _progress(cursor, total, chunk)
  160. if(headers.noCache)
  161. return
  162. cacheData += chunk
  163. })
  164. stream.onError((err) => { reject(err) })
  165. stream.onEnd(() => {
  166. resolve(new FetchBlobResponse(null, info, cacheData))
  167. })
  168. }))
  169. break
  170. }
  171. promise.progress = (fn) => {
  172. _progress = fn
  173. return promise
  174. }
  175. promise.stateChange = (fn) => {
  176. _stateChange = fn
  177. return promise
  178. }
  179. promise.uploadProgress = (fn) => {
  180. _uploadProgress = fn
  181. return promise
  182. }
  183. return promise
  184. }
  185. /**
  186. * Create a HTTP request by settings, the `this` context is a `RNFetchBlobConfig` object.
  187. * @param {string} method HTTP method, should be `GET`, `POST`, `PUT`, `DELETE`
  188. * @param {string} url Request target url string.
  189. * @param {object} headers HTTP request headers.
  190. * @param {string} body
  191. * Request body, can be either a BASE64 encoded data string,
  192. * or a file path with prefix `RNFetchBlob-file://` (can be changed)
  193. * @return {Promise}
  194. * This promise instance also contains a Customized method `progress`for
  195. * register progress event handler.
  196. */
  197. function fetch(...args:any):Promise {
  198. // create task ID for receiving progress event
  199. let taskId = getUUID()
  200. let options = this || {}
  201. let subscription, subscriptionUpload, stateEvent, partEvent
  202. let respInfo = {}
  203. let [method, url, headers, body] = [...args]
  204. // # 241 normalize null or undefined headers, in case nil or null string
  205. // pass to native context
  206. headers = _.reduce(headers, (result, value, key) => {
  207. result[key] = value || ''
  208. return result
  209. }, {});
  210. // fetch from file system
  211. if(URIUtil.isFileURI(url)) {
  212. return fetchFile(options, method, url, headers, body)
  213. }
  214. let promiseResolve;
  215. let promiseReject;
  216. // from remote HTTP(S)
  217. let promise = new Promise((resolve, reject) => {
  218. promiseResolve = resolve;
  219. promiseReject = reject;
  220. let nativeMethodName = Array.isArray(body) ? 'fetchBlobForm' : 'fetchBlob'
  221. // on progress event listener
  222. subscription = emitter.addListener('RNFetchBlobProgress', (e) => {
  223. if(e.taskId === taskId && promise.onProgress) {
  224. promise.onProgress(e.written, e.total, e.chunk)
  225. }
  226. })
  227. subscriptionUpload = emitter.addListener('RNFetchBlobProgress-upload', (e) => {
  228. if(e.taskId === taskId && promise.onUploadProgress) {
  229. promise.onUploadProgress(e.written, e.total)
  230. }
  231. })
  232. stateEvent = emitter.addListener('RNFetchBlobState', (e) => {
  233. if(e.taskId === taskId)
  234. respInfo = e
  235. promise.onStateChange && promise.onStateChange(e)
  236. })
  237. subscription = emitter.addListener('RNFetchBlobExpire', (e) => {
  238. if(e.taskId === taskId && promise.onExpire) {
  239. promise.onExpire(e)
  240. }
  241. })
  242. partEvent = emitter.addListener('RNFetchBlobServerPush', (e) => {
  243. if(e.taskId === taskId && promise.onPartData) {
  244. promise.onPartData(e.chunk)
  245. }
  246. })
  247. // When the request body comes from Blob polyfill, we should use special its ref
  248. // as the request body
  249. if( body instanceof Blob && body.isRNFetchBlobPolyfill) {
  250. body = body.getRNFetchBlobRef()
  251. }
  252. let req = RNFetchBlob[nativeMethodName]
  253. /**
  254. * Send request via native module, the response callback accepts three arguments
  255. * @callback
  256. * @param err {any} Error message or object, when the request success, this
  257. * parameter should be `null`.
  258. * @param rawType { 'utf8' | 'base64' | 'path'} RNFB request will be stored
  259. * as UTF8 string, BASE64 string, or a file path reference
  260. * in JS context, and this parameter indicates which one
  261. * dose the response data presents.
  262. * @param data {string} Response data or its reference.
  263. */
  264. req(options, taskId, method, url, headers || {}, body, (err, rawType, data) => {
  265. // task done, remove event listeners
  266. subscription.remove()
  267. subscriptionUpload.remove()
  268. stateEvent.remove()
  269. partEvent.remove()
  270. delete promise['progress']
  271. delete promise['uploadProgress']
  272. delete promise['stateChange']
  273. delete promise['part']
  274. delete promise['cancel']
  275. // delete promise['expire']
  276. promise.cancel = () => {}
  277. if(err)
  278. reject(new Error(err, respInfo))
  279. else {
  280. // response data is saved to storage, create a session for it
  281. if(options.path || options.fileCache || options.addAndroidDownloads
  282. || options.key || options.auto && respInfo.respType === 'blob') {
  283. if(options.session)
  284. session(options.session).add(data)
  285. }
  286. respInfo.rnfbEncode = rawType
  287. resolve(new FetchBlobResponse(taskId, respInfo, data))
  288. }
  289. })
  290. })
  291. // extend Promise object, add `progress`, `uploadProgress`, and `cancel`
  292. // method for register progress event handler and cancel request.
  293. // Add second parameter for performance purpose #140
  294. // When there's only one argument pass to this method, use default `interval`
  295. // and `count`, otherwise use the given on.
  296. // TODO : code refactor, move `uploadProgress` and `progress` to StatefulPromise
  297. promise.progress = (...args) => {
  298. let interval = 250
  299. let count = -1
  300. let fn = () => {}
  301. if(args.length === 2) {
  302. interval = args[0].interval || interval
  303. count = args[0].count || count
  304. fn = args[1]
  305. }
  306. else {
  307. fn = args[0]
  308. }
  309. promise.onProgress = fn
  310. RNFetchBlob.enableProgressReport(taskId, interval, count)
  311. return promise
  312. }
  313. promise.uploadProgress = (...args) => {
  314. let interval = 250
  315. let count = -1
  316. let fn = () => {}
  317. if(args.length === 2) {
  318. interval = args[0].interval || interval
  319. count = args[0].count || count
  320. fn = args[1]
  321. }
  322. else {
  323. fn = args[0]
  324. }
  325. promise.onUploadProgress = fn
  326. RNFetchBlob.enableUploadProgressReport(taskId, interval, count)
  327. return promise
  328. }
  329. promise.part = (fn) => {
  330. promise.onPartData = fn
  331. return promise
  332. }
  333. promise.stateChange = (fn) => {
  334. promise.onStateChange = fn
  335. return promise
  336. }
  337. promise.expire = (fn) => {
  338. promise.onExpire = fn
  339. return promise
  340. }
  341. promise.cancel = (fn) => {
  342. fn = fn || function(){}
  343. subscription.remove()
  344. subscriptionUpload.remove()
  345. stateEvent.remove()
  346. RNFetchBlob.cancelRequest(taskId, fn)
  347. promiseReject(new Error("canceled"))
  348. }
  349. promise.taskId = taskId
  350. return promise
  351. }
  352. /**
  353. * RNFetchBlob response object class.
  354. */
  355. class FetchBlobResponse {
  356. taskId : string;
  357. path : () => string | null;
  358. type : 'base64' | 'path' | 'utf8';
  359. data : any;
  360. blob : (contentType:string, sliceSize:number) => Promise<Blob>;
  361. text : () => string | Promise<any>;
  362. json : () => any;
  363. base64 : () => any;
  364. flush : () => void;
  365. respInfo : RNFetchBlobResponseInfo;
  366. session : (name:string) => RNFetchBlobSession | null;
  367. readFile : (encode: 'base64' | 'utf8' | 'ascii') => ?Promise<any>;
  368. readStream : (
  369. encode: 'utf8' | 'ascii' | 'base64',
  370. ) => RNFetchBlobStream | null;
  371. constructor(taskId:string, info:RNFetchBlobResponseInfo, data:any) {
  372. this.data = data
  373. this.taskId = taskId
  374. this.type = info.rnfbEncode
  375. this.respInfo = info
  376. this.info = ():RNFetchBlobResponseInfo => {
  377. return this.respInfo
  378. }
  379. this.array = ():Promise<Array> => {
  380. let cType = info.headers['Content-Type'] || info.headers['content-type']
  381. return new Promise((resolve, reject) => {
  382. switch(this.type) {
  383. case 'base64':
  384. // TODO : base64 to array buffer
  385. break
  386. case 'path':
  387. fs.readFile(this.data, 'ascii').then(resolve)
  388. break
  389. default:
  390. // TODO : text to array buffer
  391. break
  392. }
  393. })
  394. }
  395. /**
  396. * Convert result to javascript RNFetchBlob object.
  397. * @return {Promise<Blob>} Return a promise resolves Blob object.
  398. */
  399. this.blob = ():Promise<Blob> => {
  400. let Blob = polyfill.Blob
  401. let cType = info.headers['Content-Type'] || info.headers['content-type']
  402. return new Promise((resolve, reject) => {
  403. switch(this.type) {
  404. case 'base64':
  405. Blob.build(this.data, { type : cType + ';BASE64' }).then(resolve)
  406. break
  407. case 'path':
  408. polyfill.Blob.build(wrap(this.data), { type : cType }).then(resolve)
  409. break
  410. default:
  411. polyfill.Blob.build(this.data, { type : 'text/plain' }).then(resolve)
  412. break
  413. }
  414. })
  415. }
  416. /**
  417. * Convert result to text.
  418. * @return {string} Decoded base64 string.
  419. */
  420. this.text = ():string | Promise<any> => {
  421. let res = this.data
  422. switch(this.type) {
  423. case 'base64':
  424. return base64.decode(this.data)
  425. case 'path':
  426. return fs.readFile(this.data, 'base64').then((b64) => Promise.resolve(base64.decode(b64)))
  427. default:
  428. return this.data
  429. }
  430. }
  431. /**
  432. * Convert result to JSON object.
  433. * @return {object} Parsed javascript object.
  434. */
  435. this.json = ():any => {
  436. switch(this.type) {
  437. case 'base64':
  438. return JSON.parse(base64.decode(this.data))
  439. case 'path':
  440. return fs.readFile(this.data, 'utf8')
  441. .then((text) => Promise.resolve(JSON.parse(text)))
  442. default:
  443. return JSON.parse(this.data)
  444. }
  445. }
  446. /**
  447. * Return BASE64 string directly.
  448. * @return {string} BASE64 string of response body.
  449. */
  450. this.base64 = ():string | Promise<any> => {
  451. switch(this.type) {
  452. case 'base64':
  453. return this.data
  454. case 'path':
  455. return fs.readFile(this.data, 'base64')
  456. default:
  457. return base64.encode(this.data)
  458. }
  459. }
  460. /**
  461. * Remove cahced file
  462. * @return {Promise}
  463. */
  464. this.flush = () => {
  465. let path = this.path()
  466. if(!path || this.type !== 'path')
  467. return
  468. return unlink(path)
  469. }
  470. /**
  471. * get path of response temp file
  472. * @return {string} File path of temp file.
  473. */
  474. this.path = () => {
  475. if(this.type === 'path')
  476. return this.data
  477. return null
  478. }
  479. this.session = (name:string):RNFetchBlobSession | null => {
  480. if(this.type === 'path')
  481. return session(name).add(this.data)
  482. else {
  483. console.warn('only file paths can be add into session.')
  484. return null
  485. }
  486. }
  487. /**
  488. * Start read stream from cached file
  489. * @param {String} encoding Encode type, should be one of `base64`, `ascii`, `utf8`.
  490. * @return {void}
  491. */
  492. this.readStream = (encoding: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
  493. if(this.type === 'path') {
  494. return readStream(this.data, encoding)
  495. }
  496. else {
  497. console.warn('RNFetchblob', 'this response data does not contains any available stream')
  498. return null
  499. }
  500. }
  501. /**
  502. * Read file content with given encoding, if the response does not contains
  503. * a file path, show warning message
  504. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  505. * @return {String}
  506. */
  507. this.readFile = (encoding: 'base64' | 'utf8' | 'ascii') => {
  508. if(this.type === 'path') {
  509. return readFile(this.data, encoding)
  510. }
  511. else {
  512. console.warn('RNFetchblob', 'this response does not contains a readable file')
  513. return null
  514. }
  515. }
  516. }
  517. }
  518. export default {
  519. fetch,
  520. base64,
  521. android,
  522. ios,
  523. config,
  524. session,
  525. fs,
  526. wrap,
  527. polyfill,
  528. JSONStream
  529. }