Keine Beschreibung

index.js 12KB

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