暫無描述

index.js 14KB

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