No Description

index.js 9.2KB

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