Nav apraksta

index.js 16KB

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