xref: /MusicFree/src/core/localMusicSheet.ts (revision 483fe5856044df91771f8cf65aeb02b7e2f61fad)
18fc75cb2S猫头猫import {
28fc75cb2S猫头猫    internalSerializeKey,
38fc75cb2S猫头猫    StorageKeys,
48fc75cb2S猫头猫    supportLocalMediaType,
58fc75cb2S猫头猫} from '@/constants/commonConst';
68423b2d4S猫头猫import mp3Util, {IBasicMeta} from '@/native/mp3Util';
788772aabS猫头猫import {
888772aabS猫头猫    getInternalData,
988772aabS猫头猫    InternalDataType,
1088772aabS猫头猫    isSameMediaItem,
1188772aabS猫头猫} from '@/utils/mediaItem';
12afb5c234S猫头猫import StateMapper from '@/utils/stateMapper';
13afb5c234S猫头猫import {getStorage, setStorage} from '@/utils/storage';
14806b2764S猫头猫import {nanoid} from 'nanoid';
150e4173cdS猫头猫import {useEffect, useState} from 'react';
16cd669353S猫头猫import {FileStat, FileSystem} from 'react-native-file-access';
17569da2d8S猫头猫import {unlink} from 'react-native-fs';
18afb5c234S猫头猫
19afb5c234S猫头猫let localSheet: IMusic.IMusicItem[] = [];
20afb5c234S猫头猫const localSheetStateMapper = new StateMapper(() => localSheet);
21afb5c234S猫头猫
22afb5c234S猫头猫export async function setup() {
2388772aabS猫头猫    const sheet = await getStorage(StorageKeys.LocalMusicSheet);
2488772aabS猫头猫    if (sheet) {
2588772aabS猫头猫        let validSheet = [];
2688772aabS猫头猫        for (let musicItem of sheet) {
2788772aabS猫头猫            const localPath = getInternalData<string>(
2888772aabS猫头猫                musicItem,
2988772aabS猫头猫                InternalDataType.LOCALPATH,
3088772aabS猫头猫            );
3188772aabS猫头猫            if (localPath && (await FileSystem.exists(localPath))) {
3288772aabS猫头猫                validSheet.push(musicItem);
3388772aabS猫头猫            }
3488772aabS猫头猫        }
3588772aabS猫头猫        if (validSheet.length !== sheet.length) {
3688772aabS猫头猫            await setStorage(StorageKeys.LocalMusicSheet, validSheet);
3788772aabS猫头猫        }
3888772aabS猫头猫        localSheet = validSheet;
39afb5c234S猫头猫    } else {
40afb5c234S猫头猫        await setStorage(StorageKeys.LocalMusicSheet, []);
41afb5c234S猫头猫    }
42afb5c234S猫头猫    localSheetStateMapper.notify();
43afb5c234S猫头猫}
44afb5c234S猫头猫
45afb5c234S猫头猫export async function addMusic(
46afb5c234S猫头猫    musicItem: IMusic.IMusicItem | IMusic.IMusicItem[],
47afb5c234S猫头猫) {
48afb5c234S猫头猫    if (!Array.isArray(musicItem)) {
49afb5c234S猫头猫        musicItem = [musicItem];
50afb5c234S猫头猫    }
51afb5c234S猫头猫    let newSheet = [...localSheet];
52afb5c234S猫头猫    musicItem.forEach(mi => {
53afb5c234S猫头猫        if (localSheet.findIndex(_ => isSameMediaItem(mi, _)) === -1) {
54afb5c234S猫头猫            newSheet.push(mi);
55afb5c234S猫头猫        }
56afb5c234S猫头猫    });
57afb5c234S猫头猫    await setStorage(StorageKeys.LocalMusicSheet, newSheet);
58afb5c234S猫头猫    localSheet = newSheet;
59afb5c234S猫头猫    localSheetStateMapper.notify();
60afb5c234S猫头猫}
61afb5c234S猫头猫
62dc160d50S猫头猫function addMusicDraft(musicItem: IMusic.IMusicItem | IMusic.IMusicItem[]) {
63dc160d50S猫头猫    if (!Array.isArray(musicItem)) {
64dc160d50S猫头猫        musicItem = [musicItem];
65dc160d50S猫头猫    }
66dc160d50S猫头猫    let newSheet = [...localSheet];
67dc160d50S猫头猫    musicItem.forEach(mi => {
68dc160d50S猫头猫        if (localSheet.findIndex(_ => isSameMediaItem(mi, _)) === -1) {
69dc160d50S猫头猫            newSheet.push(mi);
70dc160d50S猫头猫        }
71dc160d50S猫头猫    });
72dc160d50S猫头猫    localSheet = newSheet;
73dc160d50S猫头猫    localSheetStateMapper.notify();
74dc160d50S猫头猫}
75dc160d50S猫头猫
76dc160d50S猫头猫async function saveLocalSheet() {
77dc160d50S猫头猫    await setStorage(StorageKeys.LocalMusicSheet, localSheet);
78dc160d50S猫头猫}
79dc160d50S猫头猫
80afb5c234S猫头猫export async function removeMusic(
81afb5c234S猫头猫    musicItem: IMusic.IMusicItem,
82afb5c234S猫头猫    deleteOriginalFile = false,
83afb5c234S猫头猫) {
84afb5c234S猫头猫    const idx = localSheet.findIndex(_ => isSameMediaItem(_, musicItem));
85afb5c234S猫头猫    let newSheet = [...localSheet];
86afb5c234S猫头猫    if (idx !== -1) {
87e65882dbS猫头猫        const localMusicItem = localSheet[idx];
88afb5c234S猫头猫        newSheet.splice(idx, 1);
89e65882dbS猫头猫        const localPath =
90e65882dbS猫头猫            musicItem[internalSerializeKey]?.localPath ??
91e65882dbS猫头猫            localMusicItem[internalSerializeKey]?.localPath;
92e65882dbS猫头猫        if (deleteOriginalFile && localPath) {
93*483fe585S猫头猫            try {
94569da2d8S猫头猫                await unlink(localPath);
95*483fe585S猫头猫            } catch (e: any) {
96*483fe585S猫头猫                if (e.message !== 'File does not exist') {
97*483fe585S猫头猫                    throw e;
98*483fe585S猫头猫                }
99*483fe585S猫头猫            }
100afb5c234S猫头猫        }
101afb5c234S猫头猫    }
102afb5c234S猫头猫    localSheet = newSheet;
103afb5c234S猫头猫    localSheetStateMapper.notify();
104afb5c234S猫头猫}
105afb5c234S猫头猫
106afb5c234S猫头猫function parseFilename(fn: string): Partial<IMusic.IMusicItem> | null {
107afb5c234S猫头猫    const data = fn.slice(0, fn.lastIndexOf('.')).split('@');
108afb5c234S猫头猫    const [platform, id, title, artist] = data;
109afb5c234S猫头猫    if (!platform || !id) {
110afb5c234S猫头猫        return null;
111afb5c234S猫头猫    }
112afb5c234S猫头猫    return {
113afb5c234S猫头猫        id,
114f55de8c2S猫头猫        platform: platform,
115f55de8c2S猫头猫        title: title ?? '',
116f55de8c2S猫头猫        artist: artist ?? '',
117afb5c234S猫头猫    };
118afb5c234S猫头猫}
119afb5c234S猫头猫
120cd669353S猫头猫function localMediaFilter(_: FileStat) {
1218fc75cb2S猫头猫    return supportLocalMediaType.some(ext => _.filename.endsWith(ext));
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猫头猫// 导入本地音乐
1594173d3ebS猫头猫const groupNum = 25;
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