Açıklama Yok

index.js 12KB

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