Nenhuma descrição

index.js 9.7KB

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