暫無描述

index.js 11KB

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