Ingen beskrivning

index.js 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. const {
  22. RNFetchBlobSession,
  23. readStream,
  24. createFile,
  25. unlink,
  26. exists,
  27. mkdir,
  28. session,
  29. writeStream,
  30. readFile,
  31. ls,
  32. isDir,
  33. mv,
  34. cp
  35. } = fs
  36. import polyfill from './polyfill'
  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. if(err)
  138. reject(new Error(err, data))
  139. else {
  140. let rnfbEncode = 'base64'
  141. // response data is saved to storage
  142. if(options.path || options.fileCache || options.addAndroidDownloads
  143. || options.key || options.auto && info.respType === 'blob') {
  144. rnfbEncode = 'path'
  145. if(options.session)
  146. session(options.session).add(data)
  147. }
  148. info = info || {}
  149. info.rnfbEncode = rnfbEncode
  150. resolve(new FetchBlobResponse(taskId, info, data))
  151. }
  152. })
  153. })
  154. // extend Promise object, add `progress`, `uploadProgress`, and `cancel`
  155. // method for register progress event handler and cancel request.
  156. promise.progress = (fn) => {
  157. promise.onProgress = fn
  158. return promise
  159. }
  160. promise.uploadProgress = (fn) => {
  161. promise.onUploadProgress = fn
  162. return promise
  163. }
  164. promise.stateChange = (fn) => {
  165. promise.onStateChange = fn
  166. return promise
  167. }
  168. promise.cancel = (fn) => {
  169. fn = fn || function(){}
  170. subscription.remove()
  171. subscriptionUpload.remove()
  172. stateEvent.remove()
  173. RNFetchBlob.cancelRequest(taskId, fn)
  174. }
  175. promise.taskId = taskId
  176. return promise
  177. }
  178. /**
  179. * RNFetchBlob response object class.
  180. */
  181. class FetchBlobResponse {
  182. taskId : string;
  183. path : () => string | null;
  184. type : 'base64' | 'path';
  185. data : any;
  186. blob : (contentType:string, sliceSize:number) => null;
  187. text : () => string;
  188. json : () => any;
  189. base64 : () => any;
  190. flush : () => void;
  191. respInfo : RNFetchBlobResponseInfo;
  192. session : (name:string) => RNFetchBlobSession | null;
  193. readFile : (encode: 'base64' | 'utf8' | 'ascii') => ?Promise;
  194. readStream : (
  195. encode: 'utf8' | 'ascii' | 'base64',
  196. ) => RNFetchBlobStream | null;
  197. constructor(taskId:string, info:RNFetchBlobResponseInfo, data:any) {
  198. this.data = data
  199. this.taskId = taskId
  200. this.type = info.rnfbEncode
  201. this.respInfo = info
  202. this.info = ():RNFetchBlobResponseInfo => {
  203. return this.respInfo
  204. }
  205. /**
  206. * Convert result to javascript Blob object.
  207. * @param {string} contentType MIME type of the blob object.
  208. * @param {number} sliceSize Slice size.
  209. * @return {blob} Return Blob object.
  210. */
  211. this.blob = (contentType:string, sliceSize:number) => {
  212. console.warn('FetchBlobResponse.blob() is deprecated and has no funtionality.')
  213. return this
  214. }
  215. /**
  216. * Convert result to text.
  217. * @return {string} Decoded base64 string.
  218. */
  219. this.text = ():string => {
  220. return base64.decode(this.data)
  221. }
  222. /**
  223. * Convert result to JSON object.
  224. * @return {object} Parsed javascript object.
  225. */
  226. this.json = ():any => {
  227. return JSON.parse(base64.decode(this.data))
  228. }
  229. /**
  230. * Return BASE64 string directly.
  231. * @return {string} BASE64 string of response body.
  232. */
  233. this.base64 = ():string => {
  234. return this.data
  235. }
  236. /**
  237. * Remove cahced file
  238. * @return {Promise}
  239. */
  240. this.flush = () => {
  241. let path = this.path()
  242. if(!path)
  243. return
  244. return unlink(path)
  245. }
  246. /**
  247. * get path of response temp file
  248. * @return {string} File path of temp file.
  249. */
  250. this.path = () => {
  251. if(this.type === 'path')
  252. return this.data
  253. return null
  254. }
  255. this.session = (name:string):RNFetchBlobSession | null => {
  256. if(this.type === 'path')
  257. return session(name).add(this.data)
  258. else {
  259. console.warn('only file paths can be add into session.')
  260. return null
  261. }
  262. }
  263. /**
  264. * Start read stream from cached file
  265. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  266. * @param {Function} fn On data event handler
  267. * @return {void}
  268. */
  269. this.readStream = (encode: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
  270. if(this.type === 'path') {
  271. return readStream(this.data, encode)
  272. }
  273. else {
  274. console.warn('RNFetchblob', 'this response data does not contains any available stream')
  275. return null
  276. }
  277. }
  278. /**
  279. * Read file content with given encoding, if the response does not contains
  280. * a file path, show warning message
  281. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  282. * @return {String}
  283. */
  284. this.readFile = (encode: 'base64' | 'utf8' | 'ascii') => {
  285. if(this.type === 'path') {
  286. encode = encode || 'utf8'
  287. return readFile(this.data, encode)
  288. }
  289. else {
  290. console.warn('RNFetchblob', 'this response does not contains a readable file')
  291. return null
  292. }
  293. }
  294. }
  295. }
  296. export default {
  297. fetch,
  298. base64,
  299. config,
  300. session,
  301. fs,
  302. wrap,
  303. polyfill
  304. }