No Description

index.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. AppState,
  10. } from 'react-native'
  11. import type {
  12. RNFetchBlobNative,
  13. RNFetchBlobConfig,
  14. RNFetchBlobStream,
  15. RNFetchBlobResponseInfo
  16. } from './types'
  17. import URIUtil from './utils/uri'
  18. //import StatefulPromise from './class/StatefulPromise.js'
  19. import fs from './fs'
  20. import getUUID from './utils/uuid'
  21. import base64 from 'base-64'
  22. import polyfill from './polyfill'
  23. import _ from 'lodash'
  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 = NativeModules.RNFetchBlob
  45. // when app resumes, check if there's any expired network task and trigger
  46. // their .expire event
  47. if(Platform.OS === 'ios') {
  48. AppState.addEventListener('change', (e) => {
  49. if(e === 'active')
  50. RNFetchBlob.emitExpiredEvent(()=>{})
  51. })
  52. }
  53. // register message channel event handler.
  54. emitter.addListener("RNFetchBlobMessage", (e) => {
  55. if(e.event === 'warn') {
  56. console.warn(e.detail)
  57. }
  58. else if (e.event === 'error') {
  59. throw e.detail
  60. }
  61. else {
  62. console.log("RNFetchBlob native message", e.detail)
  63. }
  64. })
  65. // Show warning if native module not detected
  66. if(!RNFetchBlob || !RNFetchBlob.fetchBlobForm || !RNFetchBlob.fetchBlob) {
  67. console.warn(
  68. 'rn-fetch-blob could not find valid native module.',
  69. 'please make sure you have linked native modules using `rnpm link`,',
  70. 'and restart RN packager or manually compile IOS/Android project.'
  71. )
  72. }
  73. function wrap(path:string):string {
  74. const prefix = path.startsWith('content://') ? 'RNFetchBlob-content://' : 'RNFetchBlob-file://'
  75. return prefix + 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. let promiseResolve;
  209. let promiseReject;
  210. // from remote HTTP(S)
  211. let promise = new Promise((resolve, reject) => {
  212. promiseResolve = resolve;
  213. promiseReject = reject;
  214. let nativeMethodName = Array.isArray(body) ? 'fetchBlobForm' : 'fetchBlob'
  215. // on progress event listener
  216. subscription = emitter.addListener('RNFetchBlobProgress', (e) => {
  217. if(e.taskId === taskId && promise.onProgress) {
  218. promise.onProgress(e.written, e.total, e.chunk)
  219. }
  220. })
  221. subscriptionUpload = emitter.addListener('RNFetchBlobProgress-upload', (e) => {
  222. if(e.taskId === taskId && promise.onUploadProgress) {
  223. promise.onUploadProgress(e.written, e.total)
  224. }
  225. })
  226. stateEvent = emitter.addListener('RNFetchBlobState', (e) => {
  227. if(e.taskId === taskId)
  228. respInfo = e
  229. promise.onStateChange && promise.onStateChange(e)
  230. })
  231. subscription = emitter.addListener('RNFetchBlobExpire', (e) => {
  232. if(e.taskId === taskId && promise.onExpire) {
  233. promise.onExpire(e)
  234. }
  235. })
  236. partEvent = emitter.addListener('RNFetchBlobServerPush', (e) => {
  237. if(e.taskId === taskId && promise.onPartData) {
  238. promise.onPartData(e.chunk)
  239. }
  240. })
  241. // When the request body comes from Blob polyfill, we should use special its ref
  242. // as the request body
  243. if( body instanceof Blob && body.isRNFetchBlobPolyfill) {
  244. body = body.getRNFetchBlobRef()
  245. }
  246. let req = RNFetchBlob[nativeMethodName]
  247. /**
  248. * Send request via native module, the response callback accepts three arguments
  249. * @callback
  250. * @param err {any} Error message or object, when the request success, this
  251. * parameter should be `null`.
  252. * @param rawType { 'utf8' | 'base64' | 'path'} RNFB request will be stored
  253. * as UTF8 string, BASE64 string, or a file path reference
  254. * in JS context, and this parameter indicates which one
  255. * dose the response data presents.
  256. * @param data {string} Response data or its reference.
  257. */
  258. req(options, taskId, method, url, headers || {}, body, (err, rawType, data) => {
  259. // task done, remove event listeners
  260. subscription.remove()
  261. subscriptionUpload.remove()
  262. stateEvent.remove()
  263. partEvent.remove()
  264. delete promise['progress']
  265. delete promise['uploadProgress']
  266. delete promise['stateChange']
  267. delete promise['part']
  268. delete promise['cancel']
  269. // delete promise['expire']
  270. promise.cancel = () => {}
  271. if(err)
  272. reject(new Error(err, respInfo))
  273. else {
  274. // response data is saved to storage, create a session for it
  275. if(options.path || options.fileCache || options.addAndroidDownloads
  276. || options.key || options.auto && respInfo.respType === 'blob') {
  277. if(options.session)
  278. session(options.session).add(data)
  279. }
  280. respInfo.rnfbEncode = rawType
  281. resolve(new FetchBlobResponse(taskId, respInfo, data))
  282. }
  283. })
  284. })
  285. // extend Promise object, add `progress`, `uploadProgress`, and `cancel`
  286. // method for register progress event handler and cancel request.
  287. // Add second parameter for performance purpose #140
  288. // When there's only one argument pass to this method, use default `interval`
  289. // and `count`, otherwise use the given on.
  290. // TODO : code refactor, move `uploadProgress` and `progress` to StatefulPromise
  291. promise.progress = (...args) => {
  292. let interval = 250
  293. let count = -1
  294. let fn = () => {}
  295. if(args.length === 2) {
  296. interval = args[0].interval || interval
  297. count = args[0].count || count
  298. fn = args[1]
  299. }
  300. else {
  301. fn = args[0]
  302. }
  303. promise.onProgress = fn
  304. RNFetchBlob.enableProgressReport(taskId, interval, count)
  305. return promise
  306. }
  307. promise.uploadProgress = (...args) => {
  308. let interval = 250
  309. let count = -1
  310. let fn = () => {}
  311. if(args.length === 2) {
  312. interval = args[0].interval || interval
  313. count = args[0].count || count
  314. fn = args[1]
  315. }
  316. else {
  317. fn = args[0]
  318. }
  319. promise.onUploadProgress = fn
  320. RNFetchBlob.enableUploadProgressReport(taskId, interval, count)
  321. return promise
  322. }
  323. promise.part = (fn) => {
  324. promise.onPartData = fn
  325. return promise
  326. }
  327. promise.stateChange = (fn) => {
  328. promise.onStateChange = fn
  329. return promise
  330. }
  331. promise.expire = (fn) => {
  332. promise.onExpire = fn
  333. return promise
  334. }
  335. promise.cancel = (fn) => {
  336. fn = fn || function(){}
  337. subscription.remove()
  338. subscriptionUpload.remove()
  339. stateEvent.remove()
  340. RNFetchBlob.cancelRequest(taskId, fn)
  341. promiseReject(new Error("canceled"))
  342. }
  343. promise.taskId = taskId
  344. return promise
  345. }
  346. /**
  347. * RNFetchBlob response object class.
  348. */
  349. class FetchBlobResponse {
  350. taskId : string;
  351. path : () => string | null;
  352. type : 'base64' | 'path' | 'utf8';
  353. data : any;
  354. blob : (contentType:string, sliceSize:number) => Promise<Blob>;
  355. text : () => string | Promise<any>;
  356. json : () => any;
  357. base64 : () => any;
  358. flush : () => void;
  359. respInfo : RNFetchBlobResponseInfo;
  360. session : (name:string) => RNFetchBlobSession | null;
  361. readFile : (encode: 'base64' | 'utf8' | 'ascii') => ?Promise<any>;
  362. readStream : (
  363. encode: 'utf8' | 'ascii' | 'base64',
  364. ) => RNFetchBlobStream | null;
  365. constructor(taskId:string, info:RNFetchBlobResponseInfo, data:any) {
  366. this.data = data
  367. this.taskId = taskId
  368. this.type = info.rnfbEncode
  369. this.respInfo = info
  370. this.info = ():RNFetchBlobResponseInfo => {
  371. return this.respInfo
  372. }
  373. this.array = ():Promise<Array> => {
  374. let cType = info.headers['Content-Type'] || info.headers['content-type']
  375. return new Promise((resolve, reject) => {
  376. switch(this.type) {
  377. case 'base64':
  378. // TODO : base64 to array buffer
  379. break
  380. case 'path':
  381. fs.readFile(this.data, 'ascii').then(resolve)
  382. break
  383. default:
  384. // TODO : text to array buffer
  385. break
  386. }
  387. })
  388. }
  389. /**
  390. * Convert result to javascript RNFetchBlob object.
  391. * @return {Promise<Blob>} Return a promise resolves Blob object.
  392. */
  393. this.blob = ():Promise<Blob> => {
  394. let Blob = polyfill.Blob
  395. let cType = info.headers['Content-Type'] || info.headers['content-type']
  396. return new Promise((resolve, reject) => {
  397. switch(this.type) {
  398. case 'base64':
  399. Blob.build(this.data, { type : cType + ';BASE64' }).then(resolve)
  400. break
  401. case 'path':
  402. polyfill.Blob.build(wrap(this.data), { type : cType }).then(resolve)
  403. break
  404. default:
  405. polyfill.Blob.build(this.data, { type : 'text/plain' }).then(resolve)
  406. break
  407. }
  408. })
  409. }
  410. /**
  411. * Convert result to text.
  412. * @return {string} Decoded base64 string.
  413. */
  414. this.text = ():string | Promise<any> => {
  415. let res = this.data
  416. switch(this.type) {
  417. case 'base64':
  418. return base64.decode(this.data)
  419. case 'path':
  420. return fs.readFile(this.data, 'base64').then((b64) => Promise.resolve(base64.decode(b64)))
  421. default:
  422. return this.data
  423. }
  424. }
  425. /**
  426. * Convert result to JSON object.
  427. * @return {object} Parsed javascript object.
  428. */
  429. this.json = ():any => {
  430. switch(this.type) {
  431. case 'base64':
  432. return JSON.parse(base64.decode(this.data))
  433. case 'path':
  434. return fs.readFile(this.data, 'utf8')
  435. .then((text) => Promise.resolve(JSON.parse(text)))
  436. default:
  437. return JSON.parse(this.data)
  438. }
  439. }
  440. /**
  441. * Return BASE64 string directly.
  442. * @return {string} BASE64 string of response body.
  443. */
  444. this.base64 = ():string | Promise<any> => {
  445. switch(this.type) {
  446. case 'base64':
  447. return this.data
  448. case 'path':
  449. return fs.readFile(this.data, 'base64')
  450. default:
  451. return base64.encode(this.data)
  452. }
  453. }
  454. /**
  455. * Remove cahced file
  456. * @return {Promise}
  457. */
  458. this.flush = () => {
  459. let path = this.path()
  460. if(!path || this.type !== 'path')
  461. return
  462. return unlink(path)
  463. }
  464. /**
  465. * get path of response temp file
  466. * @return {string} File path of temp file.
  467. */
  468. this.path = () => {
  469. if(this.type === 'path')
  470. return this.data
  471. return null
  472. }
  473. this.session = (name:string):RNFetchBlobSession | null => {
  474. if(this.type === 'path')
  475. return session(name).add(this.data)
  476. else {
  477. console.warn('only file paths can be add into session.')
  478. return null
  479. }
  480. }
  481. /**
  482. * Start read stream from cached file
  483. * @param {String} encoding Encode type, should be one of `base64`, `ascii`, `utf8`.
  484. * @return {void}
  485. */
  486. this.readStream = (encoding: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
  487. if(this.type === 'path') {
  488. return readStream(this.data, encoding)
  489. }
  490. else {
  491. console.warn('RNFetchblob', 'this response data does not contains any available stream')
  492. return null
  493. }
  494. }
  495. /**
  496. * Read file content with given encoding, if the response does not contains
  497. * a file path, show warning message
  498. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  499. * @return {String}
  500. */
  501. this.readFile = (encoding: 'base64' | 'utf8' | 'ascii') => {
  502. if(this.type === 'path') {
  503. return readFile(this.data, encoding)
  504. }
  505. else {
  506. console.warn('RNFetchblob', 'this response does not contains a readable file')
  507. return null
  508. }
  509. }
  510. }
  511. }
  512. export default {
  513. fetch,
  514. base64,
  515. android,
  516. ios,
  517. config,
  518. session,
  519. fs,
  520. wrap,
  521. polyfill,
  522. JSONStream
  523. }