Нема описа

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