Нема описа

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. import {
  5. NativeModules,
  6. DeviceEventEmitter,
  7. Platform,
  8. NativeAppEventEmitter,
  9. } from 'react-native'
  10. import RNFetchBlobSession from './class/RNFetchBlobSession'
  11. import RNFetchBlobWriteStream from './class/RNFetchBlobWriteStream'
  12. import RNFetchBlobReadStream from './class/RNFetchBlobReadStream'
  13. import RNFetchBlobFile from './class/RNFetchBlobFile'
  14. import type {
  15. RNFetchBlobNative,
  16. RNFetchBlobConfig,
  17. RNFetchBlobStream
  18. } from './types'
  19. const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob
  20. const emitter = DeviceEventEmitter
  21. const dirs = {
  22. DocumentDir : RNFetchBlob.DocumentDir,
  23. CacheDir : RNFetchBlob.CacheDir,
  24. PictureDir : RNFetchBlob.PictureDir,
  25. MusicDir : RNFetchBlob.MusicDir,
  26. MovieDir : RNFetchBlob.MovieDir,
  27. DownloadDir : RNFetchBlob.DownloadDir,
  28. DCIMDir : RNFetchBlob.DCIMDir,
  29. SDCardDir : RNFetchBlob.SDCardDir,
  30. MainBundleDir : RNFetchBlob.MainBundleDir
  31. }
  32. /**
  33. * Get a file cache session
  34. * @param {string} name Stream ID
  35. * @return {RNFetchBlobSession}
  36. */
  37. function session(name:string):RNFetchBlobSession {
  38. let s = RNFetchBlobSession.getSession(name)
  39. if(s)
  40. return new RNFetchBlobSession(name)
  41. else {
  42. RNFetchBlobSession.setSession(name, [])
  43. return new RNFetchBlobSession(name, [])
  44. }
  45. }
  46. function asset(path:string):string {
  47. if(Platform.OS === 'ios') {
  48. // path from camera roll
  49. if(/^assets-library\:\/\//.test(path))
  50. return path
  51. }
  52. return 'bundle-assets://' + path
  53. }
  54. function createFile(path:string, data:string, encoding: 'base64' | 'ascii' | 'utf8'):Promise {
  55. encoding = encoding || 'utf8'
  56. return new Promise((resolve, reject) => {
  57. let handler = (err) => {
  58. if(err)
  59. reject(new Error(err))
  60. else
  61. resolve()
  62. }
  63. if(encoding.toLowerCase() === 'ascii') {
  64. if(Array.isArray(data))
  65. RNFetchBlob.createFileASCII(path, data, handler)
  66. else
  67. reject(new Error('`data` of ASCII file must be an array contains numbers'))
  68. }
  69. else {
  70. RNFetchBlob.createFile(path, data, encoding, handler)
  71. }
  72. })
  73. }
  74. /**
  75. * Create write stream to a file.
  76. * @param {string} path Target path of file stream.
  77. * @param {string} encoding Encoding of input data.
  78. * @param {bool} append A flag represent if data append to existing ones.
  79. * @return {Promise<WriteStream>} A promise resolves a `WriteStream` object.
  80. */
  81. function writeStream(
  82. path : string,
  83. encoding : 'utf8' | 'ascii' | 'base64',
  84. append? : ?bool,
  85. ):Promise<RNFetchBlobWriteStream> {
  86. if(!path)
  87. throw Error('RNFetchBlob could not open file stream with empty `path`')
  88. encoding = encoding || 'utf8'
  89. append = append || false
  90. return new Promise((resolve, reject) => {
  91. RNFetchBlob.writeStream(path, encoding || 'base64', append || false, (err, streamId:string) => {
  92. if(err)
  93. reject(new Error(err))
  94. else
  95. resolve(new RNFetchBlobWriteStream(streamId, encoding))
  96. })
  97. })
  98. }
  99. /**
  100. * Create file stream from file at `path`.
  101. * @param {string} path The file path.
  102. * @param {string} encoding Data encoding, should be one of `base64`, `utf8`, `ascii`
  103. * @param {boolean} bufferSize Size of stream buffer.
  104. * @return {RNFetchBlobStream} RNFetchBlobStream stream instance.
  105. */
  106. function readStream(
  107. path : string,
  108. encoding : 'utf8' | 'ascii' | 'base64',
  109. bufferSize? : ?number,
  110. tick : ?number = 10
  111. ):Promise<RNFetchBlobReadStream> {
  112. return Promise.resolve(new RNFetchBlobReadStream(path, encoding, bufferSize, tick))
  113. }
  114. /**
  115. * Create a directory.
  116. * @param {string} path Path of directory to be created
  117. * @return {Promise}
  118. */
  119. function mkdir(path:string):Promise {
  120. return new Promise((resolve, reject) => {
  121. RNFetchBlob.mkdir(path, (err, res) => {
  122. if(err)
  123. reject(new Error(err))
  124. else
  125. resolve()
  126. })
  127. })
  128. }
  129. /**
  130. * Wrapper method of readStream.
  131. * @param {string} path Path of the file.
  132. * @param {'base64' | 'utf8' | 'ascii'} encoding Encoding of read stream.
  133. * @return {Promise<Array<number> | string>}
  134. */
  135. function readFile(path:string, encoding:string, bufferSize:?number):Promise<any> {
  136. if(typeof path !== 'string')
  137. return Promise.reject(new Error('Invalid argument "path" '))
  138. return RNFetchBlob.readFile(path, encoding)
  139. }
  140. /**
  141. * Write data to file.
  142. * @param {string} path Path of the file.
  143. * @param {string | number[]} data Data to write to the file.
  144. * @param {string} encoding Encoding of data (Optional).
  145. * @return {Promise}
  146. */
  147. function writeFile(path:string, data:string | Array<number>, encoding:?string):Promise {
  148. encoding = encoding || 'utf8'
  149. if(typeof path !== 'string')
  150. return Promise.reject('Invalid argument "path" ')
  151. if(encoding.toLocaleLowerCase() === 'ascii') {
  152. if(!Array.isArray(data))
  153. Promise.reject(new Error(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`))
  154. else
  155. return RNFetchBlob.writeFileArray(path, data, false);
  156. } else {
  157. if(typeof data !== 'string')
  158. Promise.reject(new Error(`Expected "data" is a String when encoding is "utf8" or "base64", however got ${typeof data}`))
  159. else
  160. return RNFetchBlob.writeFile(path, encoding, data, false);
  161. }
  162. }
  163. function appendFile(path:string, data:string | Array<number>, encoding:?string):Promise {
  164. encoding = encoding || 'utf8'
  165. if(typeof path !== 'string')
  166. return Promise.reject('Invalid argument "path" ')
  167. if(encoding.toLocaleLowerCase() === 'ascii') {
  168. if(!Array.isArray(data))
  169. Promise.reject(new Error(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`))
  170. else
  171. return RNFetchBlob.writeFileArray(path, data, true);
  172. } else {
  173. if(typeof data !== 'string')
  174. Promise.reject(new Error(`Expected "data" is a String when encoding is "utf8" or "base64", however got ${typeof data}`))
  175. else
  176. return RNFetchBlob.writeFile(path, encoding, data, true);
  177. }
  178. }
  179. /**
  180. * Show statistic data of a path.
  181. * @param {string} path Target path
  182. * @return {RNFetchBlobFile}
  183. */
  184. function stat(path:string):Promise<RNFetchBlobFile> {
  185. return new Promise((resolve, reject) => {
  186. RNFetchBlob.stat(path, (err, stat) => {
  187. if(err)
  188. reject(new Error(err))
  189. else {
  190. if(stat) {
  191. stat.size = parseInt(stat.size)
  192. stat.lastModified = parseInt(stat.lastModified)
  193. }
  194. resolve(stat)
  195. }
  196. })
  197. })
  198. }
  199. /**
  200. * Android only method, request media scanner to scan the file.
  201. * @param {Array<Object<string, string>>} Array contains Key value pairs with key `path` and `mime`.
  202. * @return {Promise}
  203. */
  204. function scanFile(pairs:any):Promise {
  205. return new Promise((resolve, reject) => {
  206. RNFetchBlob.scanFile(pairs, (err) => {
  207. if(err)
  208. reject(new Error(err))
  209. else
  210. resolve()
  211. })
  212. })
  213. }
  214. function cp(path:string, dest:string):Promise<boolean> {
  215. return new Promise((resolve, reject) => {
  216. RNFetchBlob.cp(path, dest, (err, res) => {
  217. if(err)
  218. reject(new Error(err))
  219. else
  220. resolve(res)
  221. })
  222. })
  223. }
  224. function mv(path:string, dest:string):Promise<boolean> {
  225. return new Promise((resolve, reject) => {
  226. RNFetchBlob.mv(path, dest, (err, res) => {
  227. if(err)
  228. reject(new Error(err))
  229. else
  230. resolve(res)
  231. })
  232. })
  233. }
  234. function lstat(path:string):Promise<Array<RNFetchBlobFile>> {
  235. return new Promise((resolve, reject) => {
  236. RNFetchBlob.lstat(path, (err, stat) => {
  237. if(err)
  238. reject(new Error(err))
  239. else
  240. resolve(stat)
  241. })
  242. })
  243. }
  244. function ls(path:string):Promise<Array<String>> {
  245. return new Promise((resolve, reject) => {
  246. RNFetchBlob.ls(path, (err, res) => {
  247. if(err)
  248. reject(new Error(err))
  249. else
  250. resolve(res)
  251. })
  252. })
  253. }
  254. /**
  255. * Remove file at path.
  256. * @param {string} path:string Path of target file.
  257. * @return {Promise}
  258. */
  259. function unlink(path:string):Promise {
  260. return new Promise((resolve, reject) => {
  261. RNFetchBlob.unlink(path, (err) => {
  262. if(err) {
  263. reject(new Error(err))
  264. }
  265. else
  266. resolve()
  267. })
  268. })
  269. }
  270. /**
  271. * Check if file exists and if it is a folder.
  272. * @param {string} path Path to check
  273. * @return {Promise<bool, bool>}
  274. */
  275. function exists(path:string):Promise<bool, bool> {
  276. return new Promise((resolve, reject) => {
  277. try {
  278. RNFetchBlob.exists(path, (exist) => {
  279. resolve(exist)
  280. })
  281. } catch(err) {
  282. reject(new Error(err))
  283. }
  284. })
  285. }
  286. function slice(src:string, dest:string, start:number, end:number):Promise {
  287. let p = Promise.resolve()
  288. let size = 0
  289. function normalize(num, size) {
  290. if(num < 0)
  291. return Math.max(0, size + num)
  292. if(!num && num !== 0)
  293. return size
  294. return num
  295. }
  296. if(start < 0 || end < 0 || !start || !end) {
  297. p = p.then(() => stat(src))
  298. .then((stat) => {
  299. size = Math.floor(stat.size)
  300. start = normalize(start || 0, size)
  301. end = normalize(end, size)
  302. return Promise.resolve()
  303. })
  304. }
  305. return p.then(() => RNFetchBlob.slice(src, dest, start, end))
  306. }
  307. function isDir(path:string):Promise<bool, bool> {
  308. return new Promise((resolve, reject) => {
  309. try {
  310. RNFetchBlob.exists(path, (exist, isDir) => {
  311. resolve(isDir)
  312. })
  313. } catch(err) {
  314. reject(new Error(err))
  315. }
  316. })
  317. }
  318. function df():Promise<{ free : number, total : number }> {
  319. return new Promise((resolve, reject) => {
  320. RNFetchBlob.df((err, stat) => {
  321. if(err)
  322. reject(err)
  323. else
  324. resolve(stat)
  325. })
  326. })
  327. }
  328. export default {
  329. RNFetchBlobSession,
  330. unlink,
  331. mkdir,
  332. session,
  333. ls,
  334. readStream,
  335. mv,
  336. cp,
  337. writeStream,
  338. writeFile,
  339. appendFile,
  340. readFile,
  341. exists,
  342. createFile,
  343. isDir,
  344. stat,
  345. lstat,
  346. scanFile,
  347. dirs,
  348. slice,
  349. asset,
  350. df
  351. }