Нема описа

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. * Returns the path for the app group.
  131. * @param {string} groupName Name of app group
  132. * @return {Promise}
  133. */
  134. function pathForAppGroup(groupName:string):Promise {
  135. return RNFetchBlob.pathForAppGroup(groupName);
  136. }
  137. /**
  138. * Wrapper method of readStream.
  139. * @param {string} path Path of the file.
  140. * @param {'base64' | 'utf8' | 'ascii'} encoding Encoding of read stream.
  141. * @return {Promise<Array<number> | string>}
  142. */
  143. function readFile(path:string, encoding:string, bufferSize:?number):Promise<any> {
  144. if(typeof path !== 'string')
  145. return Promise.reject(new Error('Invalid argument "path" '))
  146. return RNFetchBlob.readFile(path, encoding)
  147. }
  148. /**
  149. * Write data to file.
  150. * @param {string} path Path of the file.
  151. * @param {string | number[]} data Data to write to the file.
  152. * @param {string} encoding Encoding of data (Optional).
  153. * @return {Promise}
  154. */
  155. function writeFile(path:string, data:string | Array<number>, encoding:?string):Promise {
  156. encoding = encoding || 'utf8'
  157. if(typeof path !== 'string')
  158. return Promise.reject('Invalid argument "path" ')
  159. if(encoding.toLocaleLowerCase() === 'ascii') {
  160. if(!Array.isArray(data))
  161. Promise.reject(new Error(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`))
  162. else
  163. return RNFetchBlob.writeFileArray(path, data, false);
  164. } else {
  165. if(typeof data !== 'string')
  166. Promise.reject(new Error(`Expected "data" is a String when encoding is "utf8" or "base64", however got ${typeof data}`))
  167. else
  168. return RNFetchBlob.writeFile(path, encoding, data, false);
  169. }
  170. }
  171. function appendFile(path:string, data:string | Array<number>, encoding:?string):Promise {
  172. encoding = encoding || 'utf8'
  173. if(typeof path !== 'string')
  174. return Promise.reject('Invalid argument "path" ')
  175. if(encoding.toLocaleLowerCase() === 'ascii') {
  176. if(!Array.isArray(data))
  177. Promise.reject(new Error(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`))
  178. else
  179. return RNFetchBlob.writeFileArray(path, data, true);
  180. } else {
  181. if(typeof data !== 'string')
  182. Promise.reject(new Error(`Expected "data" is a String when encoding is "utf8" or "base64", however got ${typeof data}`))
  183. else
  184. return RNFetchBlob.writeFile(path, encoding, data, true);
  185. }
  186. }
  187. /**
  188. * Show statistic data of a path.
  189. * @param {string} path Target path
  190. * @return {RNFetchBlobFile}
  191. */
  192. function stat(path:string):Promise<RNFetchBlobFile> {
  193. return new Promise((resolve, reject) => {
  194. RNFetchBlob.stat(path, (err, stat) => {
  195. if(err)
  196. reject(new Error(err))
  197. else {
  198. if(stat) {
  199. stat.size = parseInt(stat.size)
  200. stat.lastModified = parseInt(stat.lastModified)
  201. }
  202. resolve(stat)
  203. }
  204. })
  205. })
  206. }
  207. /**
  208. * Android only method, request media scanner to scan the file.
  209. * @param {Array<Object<string, string>>} Array contains Key value pairs with key `path` and `mime`.
  210. * @return {Promise}
  211. */
  212. function scanFile(pairs:any):Promise {
  213. return new Promise((resolve, reject) => {
  214. RNFetchBlob.scanFile(pairs, (err) => {
  215. if(err)
  216. reject(new Error(err))
  217. else
  218. resolve()
  219. })
  220. })
  221. }
  222. function cp(path:string, dest:string):Promise<boolean> {
  223. return new Promise((resolve, reject) => {
  224. RNFetchBlob.cp(path, dest, (err, res) => {
  225. if(err)
  226. reject(new Error(err))
  227. else
  228. resolve(res)
  229. })
  230. })
  231. }
  232. function mv(path:string, dest:string):Promise<boolean> {
  233. return new Promise((resolve, reject) => {
  234. RNFetchBlob.mv(path, dest, (err, res) => {
  235. if(err)
  236. reject(new Error(err))
  237. else
  238. resolve(res)
  239. })
  240. })
  241. }
  242. function lstat(path:string):Promise<Array<RNFetchBlobFile>> {
  243. return new Promise((resolve, reject) => {
  244. RNFetchBlob.lstat(path, (err, stat) => {
  245. if(err)
  246. reject(new Error(err))
  247. else
  248. resolve(stat)
  249. })
  250. })
  251. }
  252. function ls(path:string):Promise<Array<String>> {
  253. return new Promise((resolve, reject) => {
  254. RNFetchBlob.ls(path, (err, res) => {
  255. if(err)
  256. reject(new Error(err))
  257. else
  258. resolve(res)
  259. })
  260. })
  261. }
  262. /**
  263. * Remove file at path.
  264. * @param {string} path:string Path of target file.
  265. * @return {Promise}
  266. */
  267. function unlink(path:string):Promise {
  268. return new Promise((resolve, reject) => {
  269. RNFetchBlob.unlink(path, (err) => {
  270. if(err) {
  271. reject(new Error(err))
  272. }
  273. else
  274. resolve()
  275. })
  276. })
  277. }
  278. /**
  279. * Check if file exists and if it is a folder.
  280. * @param {string} path Path to check
  281. * @return {Promise<bool, bool>}
  282. */
  283. function exists(path:string):Promise<bool, bool> {
  284. return new Promise((resolve, reject) => {
  285. try {
  286. RNFetchBlob.exists(path, (exist) => {
  287. resolve(exist)
  288. })
  289. } catch(err) {
  290. reject(new Error(err))
  291. }
  292. })
  293. }
  294. function slice(src:string, dest:string, start:number, end:number):Promise {
  295. let p = Promise.resolve()
  296. let size = 0
  297. function normalize(num, size) {
  298. if(num < 0)
  299. return Math.max(0, size + num)
  300. if(!num && num !== 0)
  301. return size
  302. return num
  303. }
  304. if(start < 0 || end < 0 || !start || !end) {
  305. p = p.then(() => stat(src))
  306. .then((stat) => {
  307. size = Math.floor(stat.size)
  308. start = normalize(start || 0, size)
  309. end = normalize(end, size)
  310. return Promise.resolve()
  311. })
  312. }
  313. return p.then(() => RNFetchBlob.slice(src, dest, start, end))
  314. }
  315. function isDir(path:string):Promise<bool, bool> {
  316. return new Promise((resolve, reject) => {
  317. try {
  318. RNFetchBlob.exists(path, (exist, isDir) => {
  319. resolve(isDir)
  320. })
  321. } catch(err) {
  322. reject(new Error(err))
  323. }
  324. })
  325. }
  326. function df():Promise<{ free : number, total : number }> {
  327. return new Promise((resolve, reject) => {
  328. RNFetchBlob.df((err, stat) => {
  329. if(err)
  330. reject(err)
  331. else
  332. resolve(stat)
  333. })
  334. })
  335. }
  336. export default {
  337. RNFetchBlobSession,
  338. unlink,
  339. mkdir,
  340. session,
  341. ls,
  342. readStream,
  343. mv,
  344. cp,
  345. writeStream,
  346. writeFile,
  347. appendFile,
  348. pathForAppGroup,
  349. readFile,
  350. exists,
  351. createFile,
  352. isDir,
  353. stat,
  354. lstat,
  355. scanFile,
  356. dirs,
  357. slice,
  358. asset,
  359. df
  360. }