xref: /MusicFree/src/core/localMusicSheet.ts (revision 569da2d8a0aa01fa2fdd03e39d88f8e087a99deb)
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';
17*569da2d8S猫头猫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*569da2d8S猫头猫            await unlink(localPath);
94afb5c234S猫头猫        }
95afb5c234S猫头猫    }
96afb5c234S猫头猫    localSheet = newSheet;
97afb5c234S猫头猫    localSheetStateMapper.notify();
98afb5c234S猫头猫}
99afb5c234S猫头猫
100afb5c234S猫头猫function parseFilename(fn: string): Partial<IMusic.IMusicItem> | null {
101afb5c234S猫头猫    const data = fn.slice(0, fn.lastIndexOf('.')).split('@');
102afb5c234S猫头猫    const [platform, id, title, artist] = data;
103afb5c234S猫头猫    if (!platform || !id) {
104afb5c234S猫头猫        return null;
105afb5c234S猫头猫    }
106afb5c234S猫头猫    return {
107afb5c234S猫头猫        id,
108a8557e3dS猫头猫        platform: decodeURIComponent(platform),
109a8557e3dS猫头猫        title: decodeURIComponent(title ?? ''),
110a8557e3dS猫头猫        artist: decodeURIComponent(artist ?? ''),
111afb5c234S猫头猫    };
112afb5c234S猫头猫}
113afb5c234S猫头猫
114cd669353S猫头猫function localMediaFilter(_: FileStat) {
1158fc75cb2S猫头猫    return supportLocalMediaType.some(ext => _.filename.endsWith(ext));
116cd669353S猫头猫}
117cd669353S猫头猫
118806b2764S猫头猫let importToken: string | null = null;
119806b2764S猫头猫// 获取本地的文件列表
120806b2764S猫头猫async function getMusicStats(folderPaths: string[]) {
121806b2764S猫头猫    const _importToken = nanoid();
122806b2764S猫头猫    importToken = _importToken;
123806b2764S猫头猫    const musicList: FileStat[] = [];
124806b2764S猫头猫    let peek: string | undefined;
125806b2764S猫头猫    let dirFiles: FileStat[] = [];
126806b2764S猫头猫    while (folderPaths.length !== 0) {
127806b2764S猫头猫        if (importToken !== _importToken) {
128806b2764S猫头猫            throw new Error('Import Broken');
129806b2764S猫头猫        }
130806b2764S猫头猫        peek = folderPaths.shift() as string;
131cd669353S猫头猫        try {
132806b2764S猫头猫            dirFiles = await FileSystem.statDir(peek);
133806b2764S猫头猫        } catch {
134806b2764S猫头猫            dirFiles = [];
135806b2764S猫头猫        }
136cd669353S猫头猫
137806b2764S猫头猫        dirFiles.forEach(item => {
13822c09412S猫头猫            if (item.type === 'directory' && !folderPaths.includes(item.path)) {
139806b2764S猫头猫                folderPaths.push(item.path);
140cd669353S猫头猫            } else if (localMediaFilter(item)) {
141806b2764S猫头猫                musicList.push(item);
142cd669353S猫头猫            }
143806b2764S猫头猫        });
144cd669353S猫头猫    }
145806b2764S猫头猫    return {musicList, token: _importToken};
146806b2764S猫头猫}
147806b2764S猫头猫
148806b2764S猫头猫function cancelImportLocal() {
149806b2764S猫头猫    importToken = null;
150cd669353S猫头猫}
151cd669353S猫头猫
152cd669353S猫头猫// 导入本地音乐
153bb9b2f7bS猫头猫const groupNum = 50;
154806b2764S猫头猫async function importLocal(_folderPaths: string[]) {
155806b2764S猫头猫    const folderPaths = [..._folderPaths];
156806b2764S猫头猫    const {musicList, token} = await getMusicStats(folderPaths);
157806b2764S猫头猫    if (token !== importToken) {
158806b2764S猫头猫        throw new Error('Import Broken');
159806b2764S猫头猫    }
1608423b2d4S猫头猫    // 分组请求,不然序列化可能出问题
1618423b2d4S猫头猫    let metas: IBasicMeta[] = [];
1628423b2d4S猫头猫    const groups = Math.ceil(musicList.length / groupNum);
1638423b2d4S猫头猫    for (let i = 0; i < groups; ++i) {
1648423b2d4S猫头猫        metas = metas.concat(
1658423b2d4S猫头猫            await mp3Util.getMediaMeta(
1668423b2d4S猫头猫                musicList
1678423b2d4S猫头猫                    .slice(i * groupNum, (i + 1) * groupNum)
1688423b2d4S猫头猫                    .map(_ => _.path),
1698423b2d4S猫头猫            ),
1708423b2d4S猫头猫        );
1718423b2d4S猫头猫    }
172806b2764S猫头猫    if (token !== importToken) {
173806b2764S猫头猫        throw new Error('Import Broken');
174806b2764S猫头猫    }
175cd669353S猫头猫    const musicItems = await Promise.all(
176cd669353S猫头猫        musicList.map(async (musicStat, index) => {
177cd669353S猫头猫            let {platform, id, title, artist} =
178cd669353S猫头猫                parseFilename(musicStat.filename) ?? {};
179cd669353S猫头猫            const meta = metas[index];
180cd669353S猫头猫            if (!platform || !id) {
181cd669353S猫头猫                platform = '本地';
182cd669353S猫头猫                id = await FileSystem.hash(musicStat.path, 'MD5');
183cd669353S猫头猫            }
184cd669353S猫头猫            return {
185cd669353S猫头猫                id,
186cd669353S猫头猫                platform,
187cd669353S猫头猫                title: title ?? meta?.title ?? musicStat.filename,
188cd669353S猫头猫                artist: artist ?? meta?.artist ?? '未知歌手',
189cd669353S猫头猫                duration: parseInt(meta?.duration ?? '0') / 1000,
190cd669353S猫头猫                album: meta?.album ?? '未知专辑',
191cd669353S猫头猫                artwork: '',
192cd669353S猫头猫                [internalSerializeKey]: {
193cd669353S猫头猫                    localPath: musicStat.path,
194cd669353S猫头猫                },
195cd669353S猫头猫            };
196cd669353S猫头猫        }),
197cd669353S猫头猫    );
198806b2764S猫头猫    if (token !== importToken) {
199806b2764S猫头猫        throw new Error('Import Broken');
200806b2764S猫头猫    }
201cd669353S猫头猫    addMusic(musicItems);
202cd669353S猫头猫}
203cd669353S猫头猫
2040e4173cdS猫头猫/** 是否为本地音乐 */
2050e4173cdS猫头猫function isLocalMusic(
2060e4173cdS猫头猫    musicItem: ICommon.IMediaBase | null,
2070e4173cdS猫头猫): IMusic.IMusicItem | undefined {
2080e4173cdS猫头猫    return musicItem
2090e4173cdS猫头猫        ? localSheet.find(_ => isSameMediaItem(_, musicItem))
2100e4173cdS猫头猫        : undefined;
2110e4173cdS猫头猫}
2120e4173cdS猫头猫
2130e4173cdS猫头猫/** 状态-是否为本地音乐 */
2140e4173cdS猫头猫function useIsLocal(musicItem: IMusic.IMusicItem | null) {
2150e4173cdS猫头猫    const localMusicState = localSheetStateMapper.useMappedState();
2160e4173cdS猫头猫    const [isLocal, setIsLocal] = useState<boolean>(!!isLocalMusic(musicItem));
2170e4173cdS猫头猫    useEffect(() => {
2180e4173cdS猫头猫        if (!musicItem) {
2190e4173cdS猫头猫            setIsLocal(false);
2200e4173cdS猫头猫        } else {
2210e4173cdS猫头猫            setIsLocal(!!isLocalMusic(musicItem));
2220e4173cdS猫头猫        }
2230e4173cdS猫头猫    }, [localMusicState, musicItem]);
2240e4173cdS猫头猫    return isLocal;
2250e4173cdS猫头猫}
2260e4173cdS猫头猫
2270224b881S猫头猫function getMusicList() {
2280224b881S猫头猫    return localSheet;
2290224b881S猫头猫}
2300224b881S猫头猫
23154bb1cc8S猫头猫async function updateMusicList(newSheet: IMusic.IMusicItem[]) {
23254bb1cc8S猫头猫    const _localSheet = [...newSheet];
23354bb1cc8S猫头猫    try {
23454bb1cc8S猫头猫        await setStorage(StorageKeys.LocalMusicSheet, _localSheet);
23554bb1cc8S猫头猫        localSheet = _localSheet;
23654bb1cc8S猫头猫        localSheetStateMapper.notify();
23754bb1cc8S猫头猫    } catch {}
23854bb1cc8S猫头猫}
23954bb1cc8S猫头猫
2400e4173cdS猫头猫const LocalMusicSheet = {
2410e4173cdS猫头猫    setup,
2420e4173cdS猫头猫    addMusic,
2430e4173cdS猫头猫    removeMusic,
244dc160d50S猫头猫    addMusicDraft,
245dc160d50S猫头猫    saveLocalSheet,
246cd669353S猫头猫    importLocal,
247806b2764S猫头猫    cancelImportLocal,
2480e4173cdS猫头猫    isLocalMusic,
2490e4173cdS猫头猫    useIsLocal,
2500224b881S猫头猫    getMusicList,
2510e4173cdS猫头猫    useMusicList: localSheetStateMapper.useMappedState,
25254bb1cc8S猫头猫    updateMusicList,
2530e4173cdS猫头猫};
2540e4173cdS猫头猫
2550e4173cdS猫头猫export default LocalMusicSheet;
256