説明なし

index.js 12KB

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