Ei kuvausta

index.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. if(err)
  159. reject(new Error(err, respInfo))
  160. else {
  161. // response data is saved to storage, create a session for it
  162. if(options.path || options.fileCache || options.addAndroidDownloads
  163. || options.key || options.auto && respInfo.respType === 'blob') {
  164. if(options.session)
  165. session(options.session).add(data)
  166. }
  167. respInfo.rnfbEncode = rawType
  168. resolve(new FetchBlobResponse(taskId, respInfo, data))
  169. }
  170. })
  171. })
  172. // extend Promise object, add `progress`, `uploadProgress`, and `cancel`
  173. // method for register progress event handler and cancel request.
  174. promise.progress = (fn) => {
  175. promise.onProgress = fn
  176. RNFetchBlob.enableProgressReport(taskId)
  177. return promise
  178. }
  179. promise.uploadProgress = (fn) => {
  180. promise.onUploadProgress = fn
  181. RNFetchBlob.enableUploadProgressReport(taskId)
  182. return promise
  183. }
  184. promise.stateChange = (fn) => {
  185. promise.onStateChange = fn
  186. return promise
  187. }
  188. promise.cancel = (fn) => {
  189. fn = fn || function(){}
  190. subscription.remove()
  191. subscriptionUpload.remove()
  192. stateEvent.remove()
  193. RNFetchBlob.cancelRequest(taskId, fn)
  194. }
  195. promise.taskId = taskId
  196. return promise
  197. }
  198. /**
  199. * RNFetchBlob response object class.
  200. */
  201. class FetchBlobResponse {
  202. taskId : string;
  203. path : () => string | null;
  204. type : 'base64' | 'path' | 'utf8';
  205. data : any;
  206. blob : (contentType:string, sliceSize:number) => null;
  207. text : () => string;
  208. json : () => any;
  209. base64 : () => any;
  210. flush : () => void;
  211. respInfo : RNFetchBlobResponseInfo;
  212. session : (name:string) => RNFetchBlobSession | null;
  213. readFile : (encode: 'base64' | 'utf8' | 'ascii') => ?Promise;
  214. readStream : (
  215. encode: 'utf8' | 'ascii' | 'base64',
  216. ) => RNFetchBlobStream | null;
  217. constructor(taskId:string, info:RNFetchBlobResponseInfo, data:any) {
  218. this.data = data
  219. this.taskId = taskId
  220. this.type = info.rnfbEncode
  221. this.respInfo = info
  222. this.info = ():RNFetchBlobResponseInfo => {
  223. return this.respInfo
  224. }
  225. /**
  226. * Convert result to javascript RNFetchBlob object.
  227. * @return {Promise<Blob>} Return a promise resolves Blob object.
  228. */
  229. this.blob = ():Promise<Blob> => {
  230. let Blob = polyfill.Blob
  231. let cType = info.headers['Content-Type'] || info.headers['content-type']
  232. return new Promise((resolve, reject) => {
  233. switch(this.type) {
  234. case 'base64':
  235. Blob.build(this.data, { type : cType + ';BASE64' }).then(resolve)
  236. break
  237. case 'path':
  238. polyfill.Blob.build(wrap(this.data), { type : cType }).then(resolve)
  239. break
  240. default:
  241. polyfill.Blob.build(this.data, { type : 'text/plain' }).then(resolve)
  242. break
  243. }
  244. })
  245. }
  246. /**
  247. * Convert result to text.
  248. * @return {string} Decoded base64 string.
  249. */
  250. this.text = ():string => {
  251. let res = this.data
  252. switch(this.type) {
  253. case 'base64':
  254. return base64.decode(this.data)
  255. break
  256. case 'path':
  257. return fs.readFile(this.data, 'base64').then((b64) => Promise.resolve(base64.decode(b64)))
  258. break
  259. default:
  260. return this.data
  261. break
  262. }
  263. }
  264. /**
  265. * Convert result to JSON object.
  266. * @return {object} Parsed javascript object.
  267. */
  268. this.json = ():any => {
  269. switch(this.type) {
  270. case 'base64':
  271. return JSON.parse(base64.decode(this.data))
  272. break
  273. case 'path':
  274. return fs.readFile(this.data, 'utf8')
  275. .then((text) => Promise.resolve(JSON.parse(text)))
  276. break
  277. default:
  278. return JSON.parse(this.data)
  279. break
  280. }
  281. }
  282. /**
  283. * Return BASE64 string directly.
  284. * @return {string} BASE64 string of response body.
  285. */
  286. this.base64 = ():string => {
  287. switch(this.type) {
  288. case 'base64':
  289. return this.data
  290. break
  291. case 'path':
  292. return fs.readFile(this.data, 'base64')
  293. break
  294. default:
  295. return base64.encode(this.data)
  296. break
  297. }
  298. }
  299. /**
  300. * Remove cahced file
  301. * @return {Promise}
  302. */
  303. this.flush = () => {
  304. let path = this.path()
  305. if(!path || this.type !== 'path')
  306. return
  307. return unlink(path)
  308. }
  309. /**
  310. * get path of response temp file
  311. * @return {string} File path of temp file.
  312. */
  313. this.path = () => {
  314. if(this.type === 'path')
  315. return this.data
  316. return null
  317. }
  318. this.session = (name:string):RNFetchBlobSession | null => {
  319. if(this.type === 'path')
  320. return session(name).add(this.data)
  321. else {
  322. console.warn('only file paths can be add into session.')
  323. return null
  324. }
  325. }
  326. /**
  327. * Start read stream from cached file
  328. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  329. * @param {Function} fn On data event handler
  330. * @return {void}
  331. */
  332. this.readStream = (encode: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
  333. if(this.type === 'path') {
  334. return readStream(this.data, encode)
  335. }
  336. else {
  337. console.warn('RNFetchblob', 'this response data does not contains any available stream')
  338. return null
  339. }
  340. }
  341. /**
  342. * Read file content with given encoding, if the response does not contains
  343. * a file path, show warning message
  344. * @param {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
  345. * @return {String}
  346. */
  347. this.readFile = (encode: 'base64' | 'utf8' | 'ascii') => {
  348. if(this.type === 'path') {
  349. encode = encode || 'utf8'
  350. return readFile(this.data, encode)
  351. }
  352. else {
  353. console.warn('RNFetchblob', 'this response does not contains a readable file')
  354. return null
  355. }
  356. }
  357. }
  358. }
  359. export default {
  360. fetch,
  361. base64,
  362. android,
  363. config,
  364. session,
  365. fs,
  366. wrap,
  367. polyfill
  368. }