Açıklama Yok

index.js 14KB

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