暫無描述

index.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. *
  85. * @return {function} This method returns a `fetch` method instance.
  86. */
  87. function config (options:RNFetchBlobConfig) {
  88. return { fetch : fetch.bind(options) }
  89. }
  90. /**
  91. * Create a HTTP request by settings, the `this` context is a `RNFetchBlobConfig` object.
  92. * @param {string} method HTTP method, should be `GET`, `POST`, `PUT`, `DELETE`
  93. * @param {string} url Request target url string.
  94. * @param {object} headers HTTP request headers.
  95. * @param {string} body
  96. * Request body, can be either a BASE64 encoded data string,
  97. * or a file path with prefix `RNFetchBlob-file://` (can be changed)
  98. * @return {Promise}
  99. * This promise instance also contains a Customized method `progress`for
  100. * register progress event handler.
  101. */
  102. function fetch(...args:any):Promise {
  103. // create task ID for receiving progress event
  104. let taskId = getUUID()
  105. let options = this || {}
  106. let subscription, subscriptionUpload, stateEvent
  107. let respInfo = {}
  108. let promise = new Promise((resolve, reject) => {
  109. let [method, url, headers, body] = [...args]
  110. let nativeMethodName = Array.isArray(body) ? 'fetchBlobForm' : 'fetchBlob'
  111. // on progress event listener
  112. subscription = emitter.addListener('RNFetchBlobProgress', (e) => {
  113. if(e.taskId === taskId && promise.onProgress) {
  114. promise.onProgress(e.written, e.total)
  115. }
  116. })
  117. subscriptionUpload = emitter.addListener('RNFetchBlobProgress-upload', (e) => {
  118. if(e.taskId === taskId && promise.onUploadProgress) {
  119. promise.onUploadProgress(e.written, e.total)
  120. }
  121. })
  122. stateEvent = emitter.addListener('RNFetchBlobState', (e) => {
  123. respInfo = e
  124. if(e.taskId === taskId && promise.onStateChange) {
  125. promise.onStateChange(e)
  126. }
  127. })
  128. // When the request body comes from Blob polyfill, we should use special its ref
  129. // as the request body
  130. if( body instanceof Blob && body.isRNFetchBlobPolyfill) {
  131. body = body.getRNFetchBlobRef()
  132. }
  133. let req = RNFetchBlob[nativeMethodName]
  134. req(options, taskId, method, url, headers || {}, body, (err, unsused, data) => {
  135. // task done, remove event listener
  136. subscription.remove()
  137. subscriptionUpload.remove()
  138. stateEvent.remove()
  139. if(err)
  140. reject(new Error(err, respInfo))
  141. else {
  142. let rnfbEncode = 'base64'
  143. // response data is saved to storage
  144. if(options.path || options.fileCache || options.addAndroidDownloads
  145. || options.key || options.auto && respInfo.respType === 'blob') {
  146. rnfbEncode = 'path'
  147. if(options.session)
  148. session(options.session).add(data)
  149. }
  150. respInfo.rnfbEncode = rnfbEncode
  151. resolve(new FetchBlobResponse(taskId, respInfo, data))
  152. }
  153. })
  154. })
  155. // extend Promise object, add `progress`, `uploadProgress`, and `cancel`
  156. // method for register progress event handler and cancel request.
  157. promise.progress = (fn) => {
  158. promise.onProgress = fn
  159. RNFetchBlob.enableProgressReport(taskId)
  160. return promise
  161. }
  162. promise.uploadProgress = (fn) => {
  163. promise.onUploadProgress = fn
  164. RNFetchBlob.enableUploadProgressReport(taskId)
  165. return promise
  166. }
  167. promise.stateChange = (fn) => {
  168. promise.onStateChange = fn
  169. return promise
  170. }
  171. promise.cancel = (fn) => {
  172. fn = fn || function(){}
  173. subscription.remove()
  174. subscriptionUpload.remove()
  175. stateEvent.remove()
  176. RNFetchBlob.cancelRequest(taskId, fn)
  177. }
  178. promise.taskId = taskId
  179. return promise
  180. }
  181. /**
  182. * RNFetchBlob response object class.
  183. */
  184. class FetchBlobResponse {
  185. taskId : string;
  186. path : () => string | null;
  187. type : 'base64' | 'path';
  188. data : any;
  189. blob : (contentType:string, sliceSize:number) => null;
  190. text : () => string;
  191. json : () => any;
  192. base64 : () => any;
  193. flush : () => void;
  194. respInfo : RNFetchBlobResponseInfo;
  195. session : (name:string) => RNFetchBlobSession | null;
  196. readFile : (encode: 'base64' | 'utf8' | 'ascii') => ?Promise;
  197. readStream : (
  198. encode: 'utf8' | 'ascii' | 'base64',
  199. ) => RNFetchBlobStream | null;
  200. constructor(taskId:string, info:RNFetchBlobResponseInfo, data:any) {
  201. this.data = data
  202. this.taskId = taskId
  203. this.type = info.rnfbEncode
  204. this.respInfo = info
  205. this.info = ():RNFetchBlobResponseInfo => {
  206. return this.respInfo
  207. }
  208. /**
  209. * Convert result to javascript RNFetchBlob object.
  210. * @return {Promise<Blob>} Return a promise resolves Blob object.
  211. */
  212. this.blob = ():Promise<Blob> => {
  213. return new Promise((resolve, reject) => {
  214. if(this.type === 'base64') {
  215. try {
  216. let b = new polyfill.Blob(this.data, 'application/octet-stream;BASE64')
  217. b.onCreated(() => {
  218. resolve(b)
  219. })
  220. } catch(err) {
  221. reject(err)
  222. }
  223. }
  224. else {
  225. polyfill.Blob.build(wrap(this.data))
  226. .then((b) => {
  227. resolve(b)
  228. })
  229. }
  230. })
  231. }
  232. /**
  233. * Convert result to text.
  234. * @return {string} Decoded base64 string.
  235. */
  236. this.text = ():string => {
  237. let res = this.data
  238. try {
  239. res = base64.decode(this.data)
  240. res = decodeURIComponent(res)
  241. } catch(err) {
  242. console.warn(err)
  243. res = ''
  244. }
  245. return res
  246. }
  247. /**
  248. * Convert result to JSON object.
  249. * @return {object} Parsed javascript object.
  250. */
  251. this.json = ():any => {
  252. let res = this.data
  253. try {
  254. res = base64.decode(this.data)
  255. res = decodeURIComponent(res)
  256. res = JSON.parse(res)
  257. } catch(err) {
  258. console.warn(err)
  259. res = {}
  260. }
  261. return res
  262. }
  263. /**
  264. * Return BASE64 string directly.
  265. * @return {string} BASE64 string of response body.
  266. */
  267. this.base64 = ():string => {
  268. return this.data
  269. }
  270. /**
  271. * Remove cahced file
  272. * @return {Promise}
  273. */
  274. this.flush = () => {
  275. let path = this.path()
  276. if(!path)
  277. return
  278. return unlink(path)
  279. }
  280. /**
  281. * get path of response temp file
  282. * @return {string} File path of temp file.
  283. */
  284. this.path = () => {
  285. if(this.type === 'path')
  286. return this.data
  287. return null
  288. }
  289. this.session = (name:string):RNFetchBlobSession | null => {
  290. if(this.type === 'path')
  291. return session(name).add(this.data)
  292. else {
  293. console.warn('only file paths can be add into session.')
  294. return null
  295. }
  296. }
  297. /**
  298. * Start read stream from cached file
  299. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  300. * @param {Function} fn On data event handler
  301. * @return {void}
  302. */
  303. this.readStream = (encode: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
  304. if(this.type === 'path') {
  305. return readStream(this.data, encode)
  306. }
  307. else {
  308. console.warn('RNFetchblob', 'this response data does not contains any available stream')
  309. return null
  310. }
  311. }
  312. /**
  313. * Read file content with given encoding, if the response does not contains
  314. * a file path, show warning message
  315. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  316. * @return {String}
  317. */
  318. this.readFile = (encode: 'base64' | 'utf8' | 'ascii') => {
  319. if(this.type === 'path') {
  320. encode = encode || 'utf8'
  321. return readFile(this.data, encode)
  322. }
  323. else {
  324. console.warn('RNFetchblob', 'this response does not contains a readable file')
  325. return null
  326. }
  327. }
  328. }
  329. }
  330. export default {
  331. fetch,
  332. base64,
  333. config,
  334. session,
  335. fs,
  336. wrap,
  337. polyfill
  338. }