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