暂无描述

index.js 14KB

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