Nenhuma descrição

index.js 12KB

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