Geen omschrijving

index.js 16KB

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