Aucune description

index.js 16KB

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