Keine Beschreibung

index.js 16KB

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