Нема описа

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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, partEvent
  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. partEvent = emitter.addListener('RNFetchBlobServerPush', (e) => {
  220. if(e.taskId === taskId && promise.onPartData) {
  221. promise.onPartData(e.chunk)
  222. }
  223. })
  224. // When the request body comes from Blob polyfill, we should use special its ref
  225. // as the request body
  226. if( body instanceof Blob && body.isRNFetchBlobPolyfill) {
  227. body = body.getRNFetchBlobRef()
  228. }
  229. let req = RNFetchBlob[nativeMethodName]
  230. /**
  231. * Send request via native module, the response callback accepts three arguments
  232. * @callback
  233. * @param err {any} Error message or object, when the request success, this
  234. * parameter should be `null`.
  235. * @param rawType { 'utf8' | 'base64' | 'path'} RNFB request will be stored
  236. * as UTF8 string, BASE64 string, or a file path reference
  237. * in JS context, and this parameter indicates which one
  238. * dose the response data presents.
  239. * @param data {string} Response data or its reference.
  240. */
  241. req(options, taskId, method, url, headers || {}, body, (err, rawType, data) => {
  242. // task done, remove event listeners
  243. subscription.remove()
  244. subscriptionUpload.remove()
  245. stateEvent.remove()
  246. partEvent.remove()
  247. delete promise['progress']
  248. delete promise['uploadProgress']
  249. delete promise['stateChange']
  250. delete promise['part']
  251. delete promise['cancel']
  252. // delete promise['expire']
  253. promise.cancel = () => {}
  254. if(err)
  255. reject(new Error(err, respInfo))
  256. else {
  257. // response data is saved to storage, create a session for it
  258. if(options.path || options.fileCache || options.addAndroidDownloads
  259. || options.key || options.auto && respInfo.respType === 'blob') {
  260. if(options.session)
  261. session(options.session).add(data)
  262. }
  263. respInfo.rnfbEncode = rawType
  264. resolve(new FetchBlobResponse(taskId, respInfo, data))
  265. }
  266. })
  267. })
  268. // extend Promise object, add `progress`, `uploadProgress`, and `cancel`
  269. // method for register progress event handler and cancel request.
  270. // Add second parameter for performance purpose #140
  271. // When there's only one argument pass to this method, use default `interval`
  272. // and `count`, otherwise use the given on.
  273. // TODO : code refactor, move `uploadProgress` and `progress` to StatefulPromise
  274. promise.progress = (...args) => {
  275. let interval = 250
  276. let count = -1
  277. let fn = () => {}
  278. if(args.length === 2) {
  279. interval = args[0].interval || interval
  280. count = args[0].count || count
  281. fn = args[1]
  282. }
  283. else {
  284. fn = args[0]
  285. }
  286. promise.onProgress = fn
  287. RNFetchBlob.enableProgressReport(taskId, interval, count)
  288. return promise
  289. }
  290. promise.uploadProgress = (...args) => {
  291. let interval = 250
  292. let count = -1
  293. let fn = () => {}
  294. if(args.length === 2) {
  295. interval = args[0].interval || interval
  296. count = args[0].count || count
  297. fn = args[1]
  298. }
  299. else {
  300. fn = args[0]
  301. }
  302. promise.onUploadProgress = fn
  303. RNFetchBlob.enableUploadProgressReport(taskId, interval, count)
  304. return promise
  305. }
  306. promise.part = (fn) => {
  307. promise.onPartData = fn
  308. return promise
  309. }
  310. promise.stateChange = (fn) => {
  311. promise.onStateChange = fn
  312. return promise
  313. }
  314. promise.expire = (fn) => {
  315. promise.onExpire = fn
  316. return promise
  317. }
  318. promise.cancel = (fn) => {
  319. fn = fn || function(){}
  320. subscription.remove()
  321. subscriptionUpload.remove()
  322. stateEvent.remove()
  323. RNFetchBlob.cancelRequest(taskId, fn)
  324. }
  325. promise.taskId = taskId
  326. return promise
  327. }
  328. /**
  329. * RNFetchBlob response object class.
  330. */
  331. class FetchBlobResponse {
  332. taskId : string;
  333. path : () => string | null;
  334. type : 'base64' | 'path' | 'utf8';
  335. data : any;
  336. blob : (contentType:string, sliceSize:number) => Promise<Blob>;
  337. text : () => string | Promise<any>;
  338. json : () => any;
  339. base64 : () => any;
  340. flush : () => void;
  341. respInfo : RNFetchBlobResponseInfo;
  342. session : (name:string) => RNFetchBlobSession | null;
  343. readFile : (encode: 'base64' | 'utf8' | 'ascii') => ?Promise<any>;
  344. readStream : (
  345. encode: 'utf8' | 'ascii' | 'base64',
  346. ) => RNFetchBlobStream | null;
  347. constructor(taskId:string, info:RNFetchBlobResponseInfo, data:any) {
  348. this.data = data
  349. this.taskId = taskId
  350. this.type = info.rnfbEncode
  351. this.respInfo = info
  352. this.info = ():RNFetchBlobResponseInfo => {
  353. return this.respInfo
  354. }
  355. this.array = ():Promise<Array> => {
  356. let cType = info.headers['Content-Type'] || info.headers['content-type']
  357. return new Promise((resolve, reject) => {
  358. switch(this.type) {
  359. case 'base64':
  360. // TODO : base64 to array buffer
  361. break
  362. case 'path':
  363. fs.readFile(this.data, 'ascii').then(resolve)
  364. break
  365. default:
  366. // TODO : text to array buffer
  367. break
  368. }
  369. })
  370. }
  371. /**
  372. * Convert result to javascript RNFetchBlob object.
  373. * @return {Promise<Blob>} Return a promise resolves Blob object.
  374. */
  375. this.blob = ():Promise<Blob> => {
  376. let Blob = polyfill.Blob
  377. let cType = info.headers['Content-Type'] || info.headers['content-type']
  378. return new Promise((resolve, reject) => {
  379. switch(this.type) {
  380. case 'base64':
  381. Blob.build(this.data, { type : cType + ';BASE64' }).then(resolve)
  382. break
  383. case 'path':
  384. polyfill.Blob.build(wrap(this.data), { type : cType }).then(resolve)
  385. break
  386. default:
  387. polyfill.Blob.build(this.data, { type : 'text/plain' }).then(resolve)
  388. break
  389. }
  390. })
  391. }
  392. /**
  393. * Convert result to text.
  394. * @return {string} Decoded base64 string.
  395. */
  396. this.text = ():string | Promise<any> => {
  397. let res = this.data
  398. switch(this.type) {
  399. case 'base64':
  400. return base64.decode(this.data)
  401. case 'path':
  402. return fs.readFile(this.data, 'base64').then((b64) => Promise.resolve(base64.decode(b64)))
  403. default:
  404. return this.data
  405. }
  406. }
  407. /**
  408. * Convert result to JSON object.
  409. * @return {object} Parsed javascript object.
  410. */
  411. this.json = ():any => {
  412. switch(this.type) {
  413. case 'base64':
  414. return JSON.parse(base64.decode(this.data))
  415. case 'path':
  416. return fs.readFile(this.data, 'utf8')
  417. .then((text) => Promise.resolve(JSON.parse(text)))
  418. default:
  419. return JSON.parse(this.data)
  420. }
  421. }
  422. /**
  423. * Return BASE64 string directly.
  424. * @return {string} BASE64 string of response body.
  425. */
  426. this.base64 = ():string | Promise<any> => {
  427. switch(this.type) {
  428. case 'base64':
  429. return this.data
  430. case 'path':
  431. return fs.readFile(this.data, 'base64')
  432. default:
  433. return base64.encode(this.data)
  434. }
  435. }
  436. /**
  437. * Remove cahced file
  438. * @return {Promise}
  439. */
  440. this.flush = () => {
  441. let path = this.path()
  442. if(!path || this.type !== 'path')
  443. return
  444. return unlink(path)
  445. }
  446. /**
  447. * get path of response temp file
  448. * @return {string} File path of temp file.
  449. */
  450. this.path = () => {
  451. if(this.type === 'path')
  452. return this.data
  453. return null
  454. }
  455. this.session = (name:string):RNFetchBlobSession | null => {
  456. if(this.type === 'path')
  457. return session(name).add(this.data)
  458. else {
  459. console.warn('only file paths can be add into session.')
  460. return null
  461. }
  462. }
  463. /**
  464. * Start read stream from cached file
  465. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  466. * @param {Function} fn On data event handler
  467. * @return {void}
  468. */
  469. this.readStream = (encode: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
  470. if(this.type === 'path') {
  471. return readStream(this.data, encode)
  472. }
  473. else {
  474. console.warn('RNFetchblob', 'this response data does not contains any available stream')
  475. return null
  476. }
  477. }
  478. /**
  479. * Read file content with given encoding, if the response does not contains
  480. * a file path, show warning message
  481. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  482. * @return {String}
  483. */
  484. this.readFile = (encode: 'base64' | 'utf8' | 'ascii') => {
  485. if(this.type === 'path') {
  486. encode = encode || 'utf8'
  487. return readFile(this.data, encode)
  488. }
  489. else {
  490. console.warn('RNFetchblob', 'this response does not contains a readable file')
  491. return null
  492. }
  493. }
  494. }
  495. }
  496. export default {
  497. fetch,
  498. base64,
  499. android,
  500. ios,
  501. config,
  502. session,
  503. fs,
  504. wrap,
  505. polyfill,
  506. JSONStream
  507. }