1import pathConst from '@/constants/pathConst'; 2import FastImage from 'react-native-fast-image'; 3import { 4 copyFile, 5 downloadFile, 6 exists, 7 mkdir, 8 PicturesDirectoryPath, 9 readDir, 10 unlink, 11 writeFile, 12} from 'react-native-fs'; 13 14const basePath = `${PicturesDirectoryPath}/MusicFree/`; 15export async function saveToGallery(src: string) { 16 const fileName = `${basePath}${Date.now()}.png`; 17 if (!(await exists(basePath))) { 18 await mkdir(basePath); 19 } 20 if (await exists(src)) { 21 try { 22 await copyFile(src, fileName); 23 } catch (e) { 24 console.log('... ', e); 25 } 26 } 27 if (src.startsWith('http')) { 28 await downloadFile({ 29 fromUrl: src, 30 toFile: fileName, 31 background: true, 32 }); 33 } 34 if (src.startsWith('data')) { 35 await writeFile(fileName, src); 36 } 37} 38 39export function sizeFormatter(bytes: number) { 40 if (bytes === 0) return '0B'; 41 let k = 1024, 42 sizes = ['B', 'KB', 'MB', 'GB'], 43 i = Math.floor(Math.log(bytes) / Math.log(k)); 44 return (bytes / Math.pow(k, i)).toFixed(1) + sizes[i]; 45} 46 47export async function checkAndCreateDir(path: string) { 48 const filePath = path; 49 if (!(await exists(filePath))) { 50 await mkdir(filePath); 51 } 52} 53 54async function getFolderSize(path: string): Promise<number> { 55 let size = 0; 56 try { 57 const fns = await readDir(path); 58 for (let fn of fns) { 59 if (fn.isFile()) { 60 size += fn.size; 61 } 62 // todo: 可以改成并行 promise.all 63 if (fn.isDirectory()) { 64 size += await getFolderSize(fn.path); 65 } 66 } 67 } catch {} 68 return size; 69} 70 71export async function getCacheSize( 72 type: 'music' | 'lyric' | 'image', 73): Promise<number> { 74 if (type === 'music') { 75 return getFolderSize(pathConst.musicCachePath); 76 } else if (type === 'lyric') { 77 return getFolderSize(pathConst.lrcCachePath); 78 } else if (type === 'image') { 79 return getFolderSize(pathConst.imageCachePath); 80 } 81 throw new Error(); 82} 83 84export async function clearCache(type: 'music' | 'lyric' | 'image') { 85 if (type === 'music') { 86 try { 87 if (await exists(pathConst.musicCachePath)) { 88 return unlink(pathConst.musicCachePath); 89 } 90 } catch {} 91 } else if (type === 'lyric') { 92 try { 93 const lrcs = readDir(pathConst.lrcCachePath); 94 return Promise.all((await lrcs).map(_ => unlink(_.path))); 95 } catch {} 96 } else if (type === 'image') { 97 return FastImage.clearDiskCache(); 98 } 99} 100