Нет описания

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