xref: /MusicFree/src/core/localMusicSheet.ts (revision bb9b2f7b266b5f0bb3e2e270c0624a6be855daf5)
10e4173cdS猫头猫import {internalSerializeKey, StorageKeys} from '@/constants/commonConst';
28423b2d4S猫头猫import mp3Util, {IBasicMeta} from '@/native/mp3Util';
388772aabS猫头猫import {
488772aabS猫头猫    getInternalData,
588772aabS猫头猫    InternalDataType,
688772aabS猫头猫    isSameMediaItem,
788772aabS猫头猫} from '@/utils/mediaItem';
8afb5c234S猫头猫import StateMapper from '@/utils/stateMapper';
9afb5c234S猫头猫import {getStorage, setStorage} from '@/utils/storage';
10806b2764S猫头猫import {nanoid} from 'nanoid';
110e4173cdS猫头猫import {useEffect, useState} from 'react';
12cd669353S猫头猫import {FileStat, FileSystem} from 'react-native-file-access';
13afb5c234S猫头猫
14afb5c234S猫头猫let localSheet: IMusic.IMusicItem[] = [];
15afb5c234S猫头猫const localSheetStateMapper = new StateMapper(() => localSheet);
16afb5c234S猫头猫
17afb5c234S猫头猫export async function setup() {
1888772aabS猫头猫    const sheet = await getStorage(StorageKeys.LocalMusicSheet);
1988772aabS猫头猫    if (sheet) {
2088772aabS猫头猫        let validSheet = [];
2188772aabS猫头猫        for (let musicItem of sheet) {
2288772aabS猫头猫            const localPath = getInternalData<string>(
2388772aabS猫头猫                musicItem,
2488772aabS猫头猫                InternalDataType.LOCALPATH,
2588772aabS猫头猫            );
2688772aabS猫头猫            if (localPath && (await FileSystem.exists(localPath))) {
2788772aabS猫头猫                validSheet.push(musicItem);
2888772aabS猫头猫            }
2988772aabS猫头猫        }
3088772aabS猫头猫        if (validSheet.length !== sheet.length) {
3188772aabS猫头猫            await setStorage(StorageKeys.LocalMusicSheet, validSheet);
3288772aabS猫头猫        }
3388772aabS猫头猫        localSheet = validSheet;
34afb5c234S猫头猫    } else {
35afb5c234S猫头猫        await setStorage(StorageKeys.LocalMusicSheet, []);
36afb5c234S猫头猫    }
37afb5c234S猫头猫    localSheetStateMapper.notify();
38afb5c234S猫头猫}
39afb5c234S猫头猫
40afb5c234S猫头猫export async function addMusic(
41afb5c234S猫头猫    musicItem: IMusic.IMusicItem | IMusic.IMusicItem[],
42afb5c234S猫头猫) {
43afb5c234S猫头猫    if (!Array.isArray(musicItem)) {
44afb5c234S猫头猫        musicItem = [musicItem];
45afb5c234S猫头猫    }
46afb5c234S猫头猫    let newSheet = [...localSheet];
47afb5c234S猫头猫    musicItem.forEach(mi => {
48afb5c234S猫头猫        if (localSheet.findIndex(_ => isSameMediaItem(mi, _)) === -1) {
49afb5c234S猫头猫            newSheet.push(mi);
50afb5c234S猫头猫        }
51afb5c234S猫头猫    });
52afb5c234S猫头猫    await setStorage(StorageKeys.LocalMusicSheet, newSheet);
53afb5c234S猫头猫    localSheet = newSheet;
54afb5c234S猫头猫    localSheetStateMapper.notify();
55afb5c234S猫头猫}
56afb5c234S猫头猫
57dc160d50S猫头猫function addMusicDraft(musicItem: IMusic.IMusicItem | IMusic.IMusicItem[]) {
58dc160d50S猫头猫    if (!Array.isArray(musicItem)) {
59dc160d50S猫头猫        musicItem = [musicItem];
60dc160d50S猫头猫    }
61dc160d50S猫头猫    let newSheet = [...localSheet];
62dc160d50S猫头猫    musicItem.forEach(mi => {
63dc160d50S猫头猫        if (localSheet.findIndex(_ => isSameMediaItem(mi, _)) === -1) {
64dc160d50S猫头猫            newSheet.push(mi);
65dc160d50S猫头猫        }
66dc160d50S猫头猫    });
67dc160d50S猫头猫    localSheet = newSheet;
68dc160d50S猫头猫    localSheetStateMapper.notify();
69dc160d50S猫头猫}
70dc160d50S猫头猫
71dc160d50S猫头猫async function saveLocalSheet() {
72dc160d50S猫头猫    await setStorage(StorageKeys.LocalMusicSheet, localSheet);
73dc160d50S猫头猫}
74dc160d50S猫头猫
75afb5c234S猫头猫export async function removeMusic(
76afb5c234S猫头猫    musicItem: IMusic.IMusicItem,
77afb5c234S猫头猫    deleteOriginalFile = false,
78afb5c234S猫头猫) {
79afb5c234S猫头猫    const idx = localSheet.findIndex(_ => isSameMediaItem(_, musicItem));
80afb5c234S猫头猫    let newSheet = [...localSheet];
81afb5c234S猫头猫    if (idx !== -1) {
82e65882dbS猫头猫        const localMusicItem = localSheet[idx];
83afb5c234S猫头猫        newSheet.splice(idx, 1);
84e65882dbS猫头猫        const localPath =
85e65882dbS猫头猫            musicItem[internalSerializeKey]?.localPath ??
86e65882dbS猫头猫            localMusicItem[internalSerializeKey]?.localPath;
87e65882dbS猫头猫        if (deleteOriginalFile && localPath) {
88e65882dbS猫头猫            await FileSystem.unlink(localPath);
89afb5c234S猫头猫        }
90afb5c234S猫头猫    }
91afb5c234S猫头猫    localSheet = newSheet;
92afb5c234S猫头猫    localSheetStateMapper.notify();
93afb5c234S猫头猫}
94afb5c234S猫头猫
95afb5c234S猫头猫function parseFilename(fn: string): Partial<IMusic.IMusicItem> | null {
96afb5c234S猫头猫    const data = fn.slice(0, fn.lastIndexOf('.')).split('@');
97afb5c234S猫头猫    const [platform, id, title, artist] = data;
98afb5c234S猫头猫    if (!platform || !id) {
99afb5c234S猫头猫        return null;
100afb5c234S猫头猫    }
101afb5c234S猫头猫    return {
102afb5c234S猫头猫        id,
103afb5c234S猫头猫        platform,
104afb5c234S猫头猫        title,
105afb5c234S猫头猫        artist,
106afb5c234S猫头猫    };
107afb5c234S猫头猫}
108afb5c234S猫头猫
109cd669353S猫头猫function localMediaFilter(_: FileStat) {
110cd669353S猫头猫    return (
111cd669353S猫头猫        _.filename.endsWith('.mp3') ||
112cd669353S猫头猫        _.filename.endsWith('.flac') ||
113d17d2b77S猫头猫        _.filename.endsWith('.wma') ||
114d17d2b77S猫头猫        _.filename.endsWith('.wav') ||
115d17d2b77S猫头猫        _.filename.endsWith('.m4a') ||
11674d0cf81S猫头猫        _.filename.endsWith('.ogg') ||
11795f955b7S猫头猫        _.filename.endsWith('.acc') ||
1188fd127b4S猫头猫        _.filename.endsWith('.aac') ||
119dc160d50S猫头猫        _.filename.endsWith('.ape') ||
120dc160d50S猫头猫        _.filename.endsWith('.m4s')
121cd669353S猫头猫    );
122cd669353S猫头猫}
123cd669353S猫头猫
124806b2764S猫头猫let importToken: string | null = null;
125806b2764S猫头猫// 获取本地的文件列表
126806b2764S猫头猫async function getMusicStats(folderPaths: string[]) {
127806b2764S猫头猫    const _importToken = nanoid();
128806b2764S猫头猫    importToken = _importToken;
129806b2764S猫头猫    const musicList: FileStat[] = [];
130806b2764S猫头猫    let peek: string | undefined;
131806b2764S猫头猫    let dirFiles: FileStat[] = [];
132806b2764S猫头猫    while (folderPaths.length !== 0) {
133806b2764S猫头猫        if (importToken !== _importToken) {
134806b2764S猫头猫            throw new Error('Import Broken');
135806b2764S猫头猫        }
136806b2764S猫头猫        peek = folderPaths.shift() as string;
137cd669353S猫头猫        try {
138806b2764S猫头猫            dirFiles = await FileSystem.statDir(peek);
139806b2764S猫头猫        } catch {
140806b2764S猫头猫            dirFiles = [];
141806b2764S猫头猫        }
142cd669353S猫头猫
143806b2764S猫头猫        dirFiles.forEach(item => {
14422c09412S猫头猫            if (item.type === 'directory' && !folderPaths.includes(item.path)) {
145806b2764S猫头猫                folderPaths.push(item.path);
146cd669353S猫头猫            } else if (localMediaFilter(item)) {
147806b2764S猫头猫                musicList.push(item);
148cd669353S猫头猫            }
149806b2764S猫头猫        });
150cd669353S猫头猫    }
151806b2764S猫头猫    return {musicList, token: _importToken};
152806b2764S猫头猫}
153806b2764S猫头猫
154806b2764S猫头猫function cancelImportLocal() {
155806b2764S猫头猫    importToken = null;
156cd669353S猫头猫}
157cd669353S猫头猫
158cd669353S猫头猫// 导入本地音乐
159*bb9b2f7bS猫头猫const groupNum = 50;
160806b2764S猫头猫async function importLocal(_folderPaths: string[]) {
161806b2764S猫头猫    const folderPaths = [..._folderPaths];
162806b2764S猫头猫    const {musicList, token} = await getMusicStats(folderPaths);
163806b2764S猫头猫    if (token !== importToken) {
164806b2764S猫头猫        throw new Error('Import Broken');
165806b2764S猫头猫    }
1668423b2d4S猫头猫    // 分组请求,不然序列化可能出问题
1678423b2d4S猫头猫    let metas: IBasicMeta[] = [];
1688423b2d4S猫头猫    const groups = Math.ceil(musicList.length / groupNum);
1698423b2d4S猫头猫    for (let i = 0; i < groups; ++i) {
1708423b2d4S猫头猫        metas = metas.concat(
1718423b2d4S猫头猫            await mp3Util.getMediaMeta(
1728423b2d4S猫头猫                musicList
1738423b2d4S猫头猫                    .slice(i * groupNum, (i + 1) * groupNum)
1748423b2d4S猫头猫                    .map(_ => _.path),
1758423b2d4S猫头猫            ),
1768423b2d4S猫头猫        );
1778423b2d4S猫头猫    }
178806b2764S猫头猫    if (token !== importToken) {
179806b2764S猫头猫        throw new Error('Import Broken');
180806b2764S猫头猫    }
181cd669353S猫头猫    const musicItems = await Promise.all(
182cd669353S猫头猫        musicList.map(async (musicStat, index) => {
183cd669353S猫头猫            let {platform, id, title, artist} =
184cd669353S猫头猫                parseFilename(musicStat.filename) ?? {};
185cd669353S猫头猫            const meta = metas[index];
186cd669353S猫头猫            if (!platform || !id) {
187cd669353S猫头猫                platform = '本地';
188cd669353S猫头猫                id = await FileSystem.hash(musicStat.path, 'MD5');
189cd669353S猫头猫            }
190cd669353S猫头猫            return {
191cd669353S猫头猫                id,
192cd669353S猫头猫                platform,
193cd669353S猫头猫                title: title ?? meta?.title ?? musicStat.filename,
194cd669353S猫头猫                artist: artist ?? meta?.artist ?? '未知歌手',
195cd669353S猫头猫                duration: parseInt(meta?.duration ?? '0') / 1000,
196cd669353S猫头猫                album: meta?.album ?? '未知专辑',
197cd669353S猫头猫                artwork: '',
198cd669353S猫头猫                [internalSerializeKey]: {
199cd669353S猫头猫                    localPath: musicStat.path,
200cd669353S猫头猫                },
201cd669353S猫头猫            };
202cd669353S猫头猫        }),
203cd669353S猫头猫    );
204806b2764S猫头猫    if (token !== importToken) {
205806b2764S猫头猫        throw new Error('Import Broken');
206806b2764S猫头猫    }
207cd669353S猫头猫    addMusic(musicItems);
208cd669353S猫头猫}
209cd669353S猫头猫
2100e4173cdS猫头猫/** 是否为本地音乐 */
2110e4173cdS猫头猫function isLocalMusic(
2120e4173cdS猫头猫    musicItem: ICommon.IMediaBase | null,
2130e4173cdS猫头猫): IMusic.IMusicItem | undefined {
2140e4173cdS猫头猫    return musicItem
2150e4173cdS猫头猫        ? localSheet.find(_ => isSameMediaItem(_, musicItem))
2160e4173cdS猫头猫        : undefined;
2170e4173cdS猫头猫}
2180e4173cdS猫头猫
2190e4173cdS猫头猫/** 状态-是否为本地音乐 */
2200e4173cdS猫头猫function useIsLocal(musicItem: IMusic.IMusicItem | null) {
2210e4173cdS猫头猫    const localMusicState = localSheetStateMapper.useMappedState();
2220e4173cdS猫头猫    const [isLocal, setIsLocal] = useState<boolean>(!!isLocalMusic(musicItem));
2230e4173cdS猫头猫    useEffect(() => {
2240e4173cdS猫头猫        if (!musicItem) {
2250e4173cdS猫头猫            setIsLocal(false);
2260e4173cdS猫头猫        } else {
2270e4173cdS猫头猫            setIsLocal(!!isLocalMusic(musicItem));
2280e4173cdS猫头猫        }
2290e4173cdS猫头猫    }, [localMusicState, musicItem]);
2300e4173cdS猫头猫    return isLocal;
2310e4173cdS猫头猫}
2320e4173cdS猫头猫
2330224b881S猫头猫function getMusicList() {
2340224b881S猫头猫    return localSheet;
2350224b881S猫头猫}
2360224b881S猫头猫
23754bb1cc8S猫头猫async function updateMusicList(newSheet: IMusic.IMusicItem[]) {
23854bb1cc8S猫头猫    const _localSheet = [...newSheet];
23954bb1cc8S猫头猫    try {
24054bb1cc8S猫头猫        await setStorage(StorageKeys.LocalMusicSheet, _localSheet);
24154bb1cc8S猫头猫        localSheet = _localSheet;
24254bb1cc8S猫头猫        localSheetStateMapper.notify();
24354bb1cc8S猫头猫    } catch {}
24454bb1cc8S猫头猫}
24554bb1cc8S猫头猫
2460e4173cdS猫头猫const LocalMusicSheet = {
2470e4173cdS猫头猫    setup,
2480e4173cdS猫头猫    addMusic,
2490e4173cdS猫头猫    removeMusic,
250dc160d50S猫头猫    addMusicDraft,
251dc160d50S猫头猫    saveLocalSheet,
252cd669353S猫头猫    importLocal,
253806b2764S猫头猫    cancelImportLocal,
2540e4173cdS猫头猫    isLocalMusic,
2550e4173cdS猫头猫    useIsLocal,
2560224b881S猫头猫    getMusicList,
2570e4173cdS猫头猫    useMusicList: localSheetStateMapper.useMappedState,
25854bb1cc8S猫头猫    updateMusicList,
2590e4173cdS猫头猫};
2600e4173cdS猫头猫
2610e4173cdS猫头猫export default LocalMusicSheet;
262