xref: /MusicFree/src/core/pluginManager.ts (revision 74d0cf81e0facef3bce793d52c6a2c05a955685a)
14060c00aS猫头猫import {
2927dbe93S猫头猫    copyFile,
3927dbe93S猫头猫    exists,
4927dbe93S猫头猫    readDir,
5927dbe93S猫头猫    readFile,
6927dbe93S猫头猫    unlink,
7927dbe93S猫头猫    writeFile,
8927dbe93S猫头猫} from 'react-native-fs';
9927dbe93S猫头猫import CryptoJs from 'crypto-js';
10927dbe93S猫头猫import dayjs from 'dayjs';
11927dbe93S猫头猫import axios from 'axios';
12ef60be1cS猫头猫import bigInt from 'big-integer';
13ef60be1cS猫头猫import qs from 'qs';
14927dbe93S猫头猫import {ToastAndroid} from 'react-native';
15927dbe93S猫头猫import pathConst from '@/constants/pathConst';
1625c1bd29S猫头猫import {compare, satisfies} from 'compare-versions';
17927dbe93S猫头猫import DeviceInfo from 'react-native-device-info';
18927dbe93S猫头猫import StateMapper from '@/utils/stateMapper';
19927dbe93S猫头猫import MediaMeta from './mediaMeta';
20927dbe93S猫头猫import {nanoid} from 'nanoid';
21927dbe93S猫头猫import {errorLog, trace} from '../utils/log';
22927dbe93S猫头猫import Cache from './cache';
23cfa0fc07S猫头猫import {
240e4173cdS猫头猫    getInternalData,
250e4173cdS猫头猫    InternalDataType,
260e4173cdS猫头猫    isSameMediaItem,
270e4173cdS猫头猫    resetMediaItem,
280e4173cdS猫头猫} from '@/utils/mediaItem';
290e4173cdS猫头猫import {CacheControl, internalSerializeKey} from '@/constants/commonConst';
30927dbe93S猫头猫import delay from '@/utils/delay';
314d9d3c4cS猫头猫import * as cheerio from 'cheerio';
327d7e864fS猫头猫import CookieManager from '@react-native-cookies/cookies';
337d7e864fS猫头猫import he from 'he';
34ef714860S猫头猫import Network from './network';
350e4173cdS猫头猫import LocalMusicSheet from './localMusicSheet';
360e4173cdS猫头猫import {FileSystem} from 'react-native-file-access';
37*74d0cf81S猫头猫import Mp3Util from '@/native/mp3Util';
38927dbe93S猫头猫
39927dbe93S猫头猫axios.defaults.timeout = 1500;
40927dbe93S猫头猫
41927dbe93S猫头猫const sha256 = CryptoJs.SHA256;
42927dbe93S猫头猫
43cfa0fc07S猫头猫export enum PluginStateCode {
44927dbe93S猫头猫    /** 版本不匹配 */
45927dbe93S猫头猫    VersionNotMatch = 'VERSION NOT MATCH',
46927dbe93S猫头猫    /** 无法解析 */
47927dbe93S猫头猫    CannotParse = 'CANNOT PARSE',
48927dbe93S猫头猫}
49927dbe93S猫头猫
50927dbe93S猫头猫export class Plugin {
51927dbe93S猫头猫    /** 插件名 */
52927dbe93S猫头猫    public name: string;
53927dbe93S猫头猫    /** 插件的hash,作为唯一id */
54927dbe93S猫头猫    public hash: string;
55927dbe93S猫头猫    /** 插件状态:激活、关闭、错误 */
56927dbe93S猫头猫    public state: 'enabled' | 'disabled' | 'error';
57927dbe93S猫头猫    /** 插件支持的搜索类型 */
58927dbe93S猫头猫    public supportedSearchType?: string;
59927dbe93S猫头猫    /** 插件状态信息 */
60927dbe93S猫头猫    public stateCode?: PluginStateCode;
61927dbe93S猫头猫    /** 插件的实例 */
62927dbe93S猫头猫    public instance: IPlugin.IPluginInstance;
63927dbe93S猫头猫    /** 插件路径 */
64927dbe93S猫头猫    public path: string;
65927dbe93S猫头猫    /** 插件方法 */
66927dbe93S猫头猫    public methods: PluginMethods;
67927dbe93S猫头猫
68*74d0cf81S猫头猫    constructor(
69*74d0cf81S猫头猫        funcCode: string | (() => IPlugin.IPluginInstance),
70*74d0cf81S猫头猫        pluginPath: string,
71*74d0cf81S猫头猫    ) {
72927dbe93S猫头猫        this.state = 'enabled';
73927dbe93S猫头猫        let _instance: IPlugin.IPluginInstance;
74927dbe93S猫头猫        try {
75*74d0cf81S猫头猫            if (typeof funcCode === 'string') {
764060c00aS猫头猫                // eslint-disable-next-line no-new-func
77927dbe93S猫头猫                _instance = Function(`
78927dbe93S猫头猫            'use strict';
79927dbe93S猫头猫            try {
80927dbe93S猫头猫              return ${funcCode};
81927dbe93S猫头猫            } catch(e) {
82927dbe93S猫头猫              return null;
83927dbe93S猫头猫            }
847d7e864fS猫头猫          `)()({
857d7e864fS猫头猫                    CryptoJs,
867d7e864fS猫头猫                    axios,
877d7e864fS猫头猫                    dayjs,
887d7e864fS猫头猫                    cheerio,
897d7e864fS猫头猫                    bigInt,
907d7e864fS猫头猫                    qs,
917d7e864fS猫头猫                    he,
927d7e864fS猫头猫                    CookieManager: {
937d7e864fS猫头猫                        flush: CookieManager.flush,
947d7e864fS猫头猫                        get: CookieManager.get,
957d7e864fS猫头猫                    },
967d7e864fS猫头猫                });
97*74d0cf81S猫头猫            } else {
98*74d0cf81S猫头猫                _instance = funcCode();
99*74d0cf81S猫头猫            }
100927dbe93S猫头猫            this.checkValid(_instance);
101927dbe93S猫头猫        } catch (e: any) {
102927dbe93S猫头猫            this.state = 'error';
103927dbe93S猫头猫            this.stateCode = PluginStateCode.CannotParse;
104927dbe93S猫头猫            if (e?.stateCode) {
105927dbe93S猫头猫                this.stateCode = e.stateCode;
106927dbe93S猫头猫            }
107927dbe93S猫头猫            errorLog(`${pluginPath}插件无法解析 `, {
108927dbe93S猫头猫                stateCode: this.stateCode,
109927dbe93S猫头猫                message: e?.message,
110927dbe93S猫头猫                stack: e?.stack,
111927dbe93S猫头猫            });
112927dbe93S猫头猫            _instance = e?.instance ?? {
113927dbe93S猫头猫                _path: '',
114927dbe93S猫头猫                platform: '',
115927dbe93S猫头猫                appVersion: '',
11620e6a092S猫头猫                async getMediaSource() {
117927dbe93S猫头猫                    return null;
118927dbe93S猫头猫                },
119927dbe93S猫头猫                async search() {
120927dbe93S猫头猫                    return {};
121927dbe93S猫头猫                },
122927dbe93S猫头猫                async getAlbumInfo() {
123927dbe93S猫头猫                    return null;
124927dbe93S猫头猫                },
125927dbe93S猫头猫            };
126927dbe93S猫头猫        }
127927dbe93S猫头猫        this.instance = _instance;
128927dbe93S猫头猫        this.path = pluginPath;
129927dbe93S猫头猫        this.name = _instance.platform;
130927dbe93S猫头猫        if (this.instance.platform === '') {
131927dbe93S猫头猫            this.hash = '';
132927dbe93S猫头猫        } else {
133*74d0cf81S猫头猫            if (typeof funcCode === 'string') {
134927dbe93S猫头猫                this.hash = sha256(funcCode).toString();
135*74d0cf81S猫头猫            } else {
136*74d0cf81S猫头猫                this.hash = sha256(funcCode.toString()).toString();
137*74d0cf81S猫头猫            }
138927dbe93S猫头猫        }
139927dbe93S猫头猫
140927dbe93S猫头猫        // 放在最后
141927dbe93S猫头猫        this.methods = new PluginMethods(this);
142927dbe93S猫头猫    }
143927dbe93S猫头猫
144927dbe93S猫头猫    private checkValid(_instance: IPlugin.IPluginInstance) {
145927dbe93S猫头猫        /** 版本号校验 */
146927dbe93S猫头猫        if (
147927dbe93S猫头猫            _instance.appVersion &&
148927dbe93S猫头猫            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
149927dbe93S猫头猫        ) {
150927dbe93S猫头猫            throw {
151927dbe93S猫头猫                instance: _instance,
152927dbe93S猫头猫                stateCode: PluginStateCode.VersionNotMatch,
153927dbe93S猫头猫            };
154927dbe93S猫头猫        }
155927dbe93S猫头猫        return true;
156927dbe93S猫头猫    }
157927dbe93S猫头猫}
158927dbe93S猫头猫
159927dbe93S猫头猫/** 有缓存等信息 */
160927dbe93S猫头猫class PluginMethods implements IPlugin.IPluginInstanceMethods {
161927dbe93S猫头猫    private plugin;
162927dbe93S猫头猫    constructor(plugin: Plugin) {
163927dbe93S猫头猫        this.plugin = plugin;
164927dbe93S猫头猫    }
165927dbe93S猫头猫    /** 搜索 */
166927dbe93S猫头猫    async search<T extends ICommon.SupportMediaType>(
167927dbe93S猫头猫        query: string,
168927dbe93S猫头猫        page: number,
169927dbe93S猫头猫        type: T,
170927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
171927dbe93S猫头猫        if (!this.plugin.instance.search) {
172927dbe93S猫头猫            return {
173927dbe93S猫头猫                isEnd: true,
174927dbe93S猫头猫                data: [],
175927dbe93S猫头猫            };
176927dbe93S猫头猫        }
177927dbe93S猫头猫
1784060c00aS猫头猫        const result =
1794060c00aS猫头猫            (await this.plugin.instance.search(query, page, type)) ?? {};
180927dbe93S猫头猫        if (Array.isArray(result.data)) {
181927dbe93S猫头猫            result.data.forEach(_ => {
182927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
183927dbe93S猫头猫            });
184927dbe93S猫头猫            return {
185927dbe93S猫头猫                isEnd: result.isEnd ?? true,
186927dbe93S猫头猫                data: result.data,
187927dbe93S猫头猫            };
188927dbe93S猫头猫        }
189927dbe93S猫头猫        return {
190927dbe93S猫头猫            isEnd: true,
191927dbe93S猫头猫            data: [],
192927dbe93S猫头猫        };
193927dbe93S猫头猫    }
194927dbe93S猫头猫
195927dbe93S猫头猫    /** 获取真实源 */
19620e6a092S猫头猫    async getMediaSource(
197927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
198927dbe93S猫头猫        retryCount = 1,
19920e6a092S猫头猫    ): Promise<IPlugin.IMediaSourceResult> {
200927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
201927dbe93S猫头猫        const localPath =
2020e4173cdS猫头猫            getInternalData<string>(musicItem, InternalDataType.LOCALPATH) ??
2030e4173cdS猫头猫            getInternalData<string>(
2040e4173cdS猫头猫                LocalMusicSheet.isLocalMusic(musicItem),
2050e4173cdS猫头猫                InternalDataType.LOCALPATH,
2060e4173cdS猫头猫            );
2070e4173cdS猫头猫        if (localPath && (await FileSystem.exists(localPath))) {
2080e4173cdS猫头猫            trace('本地播放', localPath);
209927dbe93S猫头猫            return {
210927dbe93S猫头猫                url: localPath,
211927dbe93S猫头猫            };
212927dbe93S猫头猫        }
213f5935920S猫头猫        if (musicItem.platform === '本地') {
214f5935920S猫头猫            throw new Error('本地音乐不存在');
215f5935920S猫头猫        }
216927dbe93S猫头猫        // 2. 缓存播放
217927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
21848f4b873S猫头猫        const pluginCacheControl = this.plugin.instance.cacheControl;
219cfa0fc07S猫头猫        if (
220cfa0fc07S猫头猫            mediaCache &&
221cfa0fc07S猫头猫            mediaCache?.url &&
22248f4b873S猫头猫            (pluginCacheControl === CacheControl.Cache ||
22348f4b873S猫头猫                (pluginCacheControl === CacheControl.NoCache &&
224ef714860S猫头猫                    Network.isOffline()))
225cfa0fc07S猫头猫        ) {
2265276aef9S猫头猫            trace('播放', '缓存播放');
227927dbe93S猫头猫            return {
228927dbe93S猫头猫                url: mediaCache.url,
229927dbe93S猫头猫                headers: mediaCache.headers,
2304060c00aS猫头猫                userAgent:
2314060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
232927dbe93S猫头猫            };
233927dbe93S猫头猫        }
234927dbe93S猫头猫        // 3. 插件解析
23520e6a092S猫头猫        if (!this.plugin.instance.getMediaSource) {
236927dbe93S猫头猫            return {url: musicItem.url};
237927dbe93S猫头猫        }
238927dbe93S猫头猫        try {
23948f4b873S猫头猫            const {url, headers} =
24020e6a092S猫头猫                (await this.plugin.instance.getMediaSource(musicItem)) ?? {};
241927dbe93S猫头猫            if (!url) {
242927dbe93S猫头猫                throw new Error();
243927dbe93S猫头猫            }
2445276aef9S猫头猫            trace('播放', '插件播放');
245927dbe93S猫头猫            const result = {
246927dbe93S猫头猫                url,
247927dbe93S猫头猫                headers,
248927dbe93S猫头猫                userAgent: headers?.['user-agent'],
249cfa0fc07S猫头猫            } as IPlugin.IMediaSourceResult;
250927dbe93S猫头猫
25148f4b873S猫头猫            if (pluginCacheControl !== CacheControl.NoStore) {
252927dbe93S猫头猫                Cache.update(musicItem, result);
253752ffc5aS猫头猫            }
254cfa0fc07S猫头猫
255927dbe93S猫头猫            return result;
256927dbe93S猫头猫        } catch (e: any) {
257927dbe93S猫头猫            if (retryCount > 0) {
258927dbe93S猫头猫                await delay(150);
25920e6a092S猫头猫                return this.getMediaSource(musicItem, --retryCount);
260927dbe93S猫头猫            }
261927dbe93S猫头猫            errorLog('获取真实源失败', e?.message);
262927dbe93S猫头猫            throw e;
263927dbe93S猫头猫        }
264927dbe93S猫头猫    }
265927dbe93S猫头猫
266927dbe93S猫头猫    /** 获取音乐详情 */
267927dbe93S猫头猫    async getMusicInfo(
268927dbe93S猫头猫        musicItem: ICommon.IMediaBase,
269*74d0cf81S猫头猫    ): Promise<Partial<IMusic.IMusicItem> | null> {
270927dbe93S猫头猫        if (!this.plugin.instance.getMusicInfo) {
271*74d0cf81S猫头猫            return {};
272927dbe93S猫头猫        }
273*74d0cf81S猫头猫        try {
274927dbe93S猫头猫            return (
275927dbe93S猫头猫                this.plugin.instance.getMusicInfo(
276*74d0cf81S猫头猫                    this.plugin.name === '本地'
277*74d0cf81S猫头猫                        ? musicItem
278*74d0cf81S猫头猫                        : resetMediaItem(musicItem, undefined, true),
279*74d0cf81S猫头猫                ) ?? {}
280927dbe93S猫头猫            );
281*74d0cf81S猫头猫        } catch (e) {
282*74d0cf81S猫头猫            console.log(e);
283*74d0cf81S猫头猫            return {};
284*74d0cf81S猫头猫        }
285927dbe93S猫头猫    }
286927dbe93S猫头猫
287927dbe93S猫头猫    /** 获取歌词 */
288927dbe93S猫头猫    async getLyric(
289927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
290927dbe93S猫头猫        from?: IMusic.IMusicItemBase,
291927dbe93S猫头猫    ): Promise<ILyric.ILyricSource | null> {
292927dbe93S猫头猫        // 1.额外存储的meta信息
293927dbe93S猫头猫        const meta = MediaMeta.get(musicItem);
294927dbe93S猫头猫        if (meta && meta.associatedLrc) {
295927dbe93S猫头猫            // 有关联歌词
296927dbe93S猫头猫            if (
297927dbe93S猫头猫                isSameMediaItem(musicItem, from) ||
298927dbe93S猫头猫                isSameMediaItem(meta.associatedLrc, musicItem)
299927dbe93S猫头猫            ) {
300927dbe93S猫头猫                // 形成环路,断开当前的环
301927dbe93S猫头猫                await MediaMeta.update(musicItem, {
302927dbe93S猫头猫                    associatedLrc: undefined,
303927dbe93S猫头猫                });
304927dbe93S猫头猫                // 无歌词
305927dbe93S猫头猫                return null;
306927dbe93S猫头猫            }
307927dbe93S猫头猫            // 获取关联歌词
3087a91f04fS猫头猫            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
3094060c00aS猫头猫            const result = await this.getLyric(
3107a91f04fS猫头猫                {...meta.associatedLrc, ...associatedMeta},
3114060c00aS猫头猫                from ?? musicItem,
3124060c00aS猫头猫            );
313927dbe93S猫头猫            if (result) {
314927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
315927dbe93S猫头猫                return result;
316927dbe93S猫头猫            }
317927dbe93S猫头猫        }
318927dbe93S猫头猫        const cache = Cache.get(musicItem);
319927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
320927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
321927dbe93S猫头猫        // 如果存在文本
322927dbe93S猫头猫        if (rawLrc) {
323927dbe93S猫头猫            return {
324927dbe93S猫头猫                rawLrc,
325927dbe93S猫头猫                lrc: lrcUrl,
326927dbe93S猫头猫            };
327927dbe93S猫头猫        }
328927dbe93S猫头猫        // 2.本地缓存
329927dbe93S猫头猫        const localLrc =
3300e4173cdS猫头猫            meta?.[internalSerializeKey]?.local?.localLrc ||
3310e4173cdS猫头猫            cache?.[internalSerializeKey]?.local?.localLrc;
332927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
333927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
334927dbe93S猫头猫            return {
335927dbe93S猫头猫                rawLrc,
336927dbe93S猫头猫                lrc: lrcUrl,
337927dbe93S猫头猫            };
338927dbe93S猫头猫        }
339927dbe93S猫头猫        // 3.优先使用url
340927dbe93S猫头猫        if (lrcUrl) {
341927dbe93S猫头猫            try {
342927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
3432a3194f5S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
344927dbe93S猫头猫                return {
345927dbe93S猫头猫                    rawLrc,
346927dbe93S猫头猫                    lrc: lrcUrl,
347927dbe93S猫头猫                };
348927dbe93S猫头猫            } catch {
349927dbe93S猫头猫                lrcUrl = undefined;
350927dbe93S猫头猫            }
351927dbe93S猫头猫        }
352927dbe93S猫头猫        // 4. 如果地址失效
353927dbe93S猫头猫        if (!lrcUrl) {
354927dbe93S猫头猫            // 插件获得url
355927dbe93S猫头猫            try {
3567a91f04fS猫头猫                let lrcSource;
3577a91f04fS猫头猫                if (from) {
3587a91f04fS猫头猫                    lrcSource = await PluginManager.getByMedia(
3597a91f04fS猫头猫                        musicItem,
3607a91f04fS猫头猫                    )?.instance?.getLyric?.(
361927dbe93S猫头猫                        resetMediaItem(musicItem, undefined, true),
362927dbe93S猫头猫                    );
3637a91f04fS猫头猫                } else {
3647a91f04fS猫头猫                    lrcSource = await this.plugin.instance?.getLyric?.(
3657a91f04fS猫头猫                        resetMediaItem(musicItem, undefined, true),
3667a91f04fS猫头猫                    );
3677a91f04fS猫头猫                }
3687a91f04fS猫头猫
369927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
370927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
371927dbe93S猫头猫            } catch (e: any) {
372927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
373927dbe93S猫头猫            }
374927dbe93S猫头猫        }
375927dbe93S猫头猫        // 5. 最后一次请求
376927dbe93S猫头猫        if (rawLrc || lrcUrl) {
377927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
378927dbe93S猫头猫            if (lrcUrl) {
379927dbe93S猫头猫                try {
3802a3194f5S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
381927dbe93S猫头猫                } catch {}
382927dbe93S猫头猫            }
383927dbe93S猫头猫            if (rawLrc) {
384927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
385927dbe93S猫头猫                // 写入缓存
386927dbe93S猫头猫                Cache.update(musicItem, [
3870e4173cdS猫头猫                    [`${internalSerializeKey}.local.localLrc`, filename],
388927dbe93S猫头猫                ]);
389927dbe93S猫头猫                // 如果有meta
390927dbe93S猫头猫                if (meta) {
391927dbe93S猫头猫                    MediaMeta.update(musicItem, [
3920e4173cdS猫头猫                        [`${internalSerializeKey}.local.localLrc`, filename],
393927dbe93S猫头猫                    ]);
394927dbe93S猫头猫                }
395927dbe93S猫头猫                return {
396927dbe93S猫头猫                    rawLrc,
397927dbe93S猫头猫                    lrc: lrcUrl,
398927dbe93S猫头猫                };
399927dbe93S猫头猫            }
400927dbe93S猫头猫        }
401927dbe93S猫头猫
402927dbe93S猫头猫        return null;
403927dbe93S猫头猫    }
404927dbe93S猫头猫
405927dbe93S猫头猫    /** 获取歌词文本 */
406927dbe93S猫头猫    async getLyricText(
407927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
408927dbe93S猫头猫    ): Promise<string | undefined> {
409927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
410927dbe93S猫头猫    }
411927dbe93S猫头猫
412927dbe93S猫头猫    /** 获取专辑信息 */
413927dbe93S猫头猫    async getAlbumInfo(
414927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
415927dbe93S猫头猫    ): Promise<IAlbum.IAlbumItem | null> {
416927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
417927dbe93S猫头猫            return {...albumItem, musicList: []};
418927dbe93S猫头猫        }
419927dbe93S猫头猫        try {
420927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
421927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
422927dbe93S猫头猫            );
4235276aef9S猫头猫            if (!result) {
4245276aef9S猫头猫                throw new Error();
4255276aef9S猫头猫            }
426927dbe93S猫头猫            result?.musicList?.forEach(_ => {
427927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
428927dbe93S猫头猫            });
4295276aef9S猫头猫
4305276aef9S猫头猫            return {...albumItem, ...result};
4317d7e864fS猫头猫        } catch (e) {
432927dbe93S猫头猫            return {...albumItem, musicList: []};
433927dbe93S猫头猫        }
434927dbe93S猫头猫    }
435927dbe93S猫头猫
436927dbe93S猫头猫    /** 查询作者信息 */
437efb9da24S猫头猫    async getArtistWorks<T extends IArtist.ArtistMediaType>(
438927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
439927dbe93S猫头猫        page: number,
440927dbe93S猫头猫        type: T,
441927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
442efb9da24S猫头猫        if (!this.plugin.instance.getArtistWorks) {
443927dbe93S猫头猫            return {
444927dbe93S猫头猫                isEnd: true,
445927dbe93S猫头猫                data: [],
446927dbe93S猫头猫            };
447927dbe93S猫头猫        }
448927dbe93S猫头猫        try {
449efb9da24S猫头猫            const result = await this.plugin.instance.getArtistWorks(
450927dbe93S猫头猫                artistItem,
451927dbe93S猫头猫                page,
452927dbe93S猫头猫                type,
453927dbe93S猫头猫            );
454927dbe93S猫头猫            if (!result.data) {
455927dbe93S猫头猫                return {
456927dbe93S猫头猫                    isEnd: true,
457927dbe93S猫头猫                    data: [],
458927dbe93S猫头猫                };
459927dbe93S猫头猫            }
460927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
461927dbe93S猫头猫            return {
462927dbe93S猫头猫                isEnd: result.isEnd ?? true,
463927dbe93S猫头猫                data: result.data,
464927dbe93S猫头猫            };
465927dbe93S猫头猫        } catch (e) {
466927dbe93S猫头猫            throw e;
467927dbe93S猫头猫        }
468927dbe93S猫头猫    }
46908380090S猫头猫
47008380090S猫头猫    /** 导入歌单 */
47108380090S猫头猫    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
47208380090S猫头猫        try {
47308380090S猫头猫            const result =
47408380090S猫头猫                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
47508380090S猫头猫            result.forEach(_ => resetMediaItem(_, this.plugin.name));
47608380090S猫头猫            return result;
4770e4173cdS猫头猫        } catch (e) {
4780e4173cdS猫头猫            console.log(e);
47908380090S猫头猫            return [];
48008380090S猫头猫        }
48108380090S猫头猫    }
4824d9d3c4cS猫头猫    /** 导入单曲 */
4834d9d3c4cS猫头猫    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
4844d9d3c4cS猫头猫        try {
4854d9d3c4cS猫头猫            const result = await this.plugin.instance?.importMusicItem?.(
4864d9d3c4cS猫头猫                urlLike,
4874d9d3c4cS猫头猫            );
4884d9d3c4cS猫头猫            if (!result) {
4894d9d3c4cS猫头猫                throw new Error();
4904d9d3c4cS猫头猫            }
4914d9d3c4cS猫头猫            resetMediaItem(result, this.plugin.name);
4924d9d3c4cS猫头猫            return result;
4934d9d3c4cS猫头猫        } catch {
4944d9d3c4cS猫头猫            return null;
4954d9d3c4cS猫头猫        }
4964d9d3c4cS猫头猫    }
497927dbe93S猫头猫}
4981a5528a0S猫头猫
499927dbe93S猫头猫let plugins: Array<Plugin> = [];
500927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
501*74d0cf81S猫头猫
502*74d0cf81S猫头猫/** 本地插件 */
503*74d0cf81S猫头猫const localFilePlugin = new Plugin(function () {
5040e4173cdS猫头猫    return {
505*74d0cf81S猫头猫        platform: '本地', //todo 改成常量
506*74d0cf81S猫头猫        _path: '',
507*74d0cf81S猫头猫        async getMusicInfo(musicBase) {
508*74d0cf81S猫头猫            const localPath = getInternalData<string>(
509*74d0cf81S猫头猫                musicBase,
510*74d0cf81S猫头猫                InternalDataType.LOCALPATH,
5110e4173cdS猫头猫            );
512*74d0cf81S猫头猫            if (localPath) {
513*74d0cf81S猫头猫                const coverImg = await Mp3Util.getMediaCoverImg(localPath);
514*74d0cf81S猫头猫                return {
515*74d0cf81S猫头猫                    artwork: coverImg,
516*74d0cf81S猫头猫                };
517*74d0cf81S猫头猫            }
518*74d0cf81S猫头猫            return null;
519*74d0cf81S猫头猫        },
520*74d0cf81S猫头猫    };
521*74d0cf81S猫头猫}, '');
522927dbe93S猫头猫
523927dbe93S猫头猫async function setup() {
524927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
525927dbe93S猫头猫    try {
526927dbe93S猫头猫        // 加载插件
527927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
528927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
529927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
5301e263108S猫头猫            trace('初始化插件', _pluginUrl);
5311e263108S猫头猫            if (
5321e263108S猫头猫                _pluginUrl.isFile() &&
5331e263108S猫头猫                (_pluginUrl.name?.endsWith?.('.js') ||
5341e263108S猫头猫                    _pluginUrl.path?.endsWith?.('.js'))
5351e263108S猫头猫            ) {
536927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
537927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
5384060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
5394060c00aS猫头猫                    p => p.hash === plugin.hash,
5404060c00aS猫头猫                );
541927dbe93S猫头猫                if (_pluginIndex !== -1) {
542927dbe93S猫头猫                    // 重复插件,直接忽略
543927dbe93S猫头猫                    return;
544927dbe93S猫头猫                }
545927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
546927dbe93S猫头猫            }
547927dbe93S猫头猫        }
548927dbe93S猫头猫
549927dbe93S猫头猫        plugins = _plugins;
550927dbe93S猫头猫        pluginStateMapper.notify();
551927dbe93S猫头猫    } catch (e: any) {
5524060c00aS猫头猫        ToastAndroid.show(
5534060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
5544060c00aS猫头猫            ToastAndroid.LONG,
5554060c00aS猫头猫        );
5561a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
557927dbe93S猫头猫        throw e;
558927dbe93S猫头猫    }
559927dbe93S猫头猫}
560927dbe93S猫头猫
561927dbe93S猫头猫// 安装插件
562927dbe93S猫头猫async function installPlugin(pluginPath: string) {
563b50427a2S猫头猫    if (pluginPath.endsWith('.js')) {
564927dbe93S猫头猫        const funcCode = await readFile(pluginPath, 'utf8');
565927dbe93S猫头猫        const plugin = new Plugin(funcCode, pluginPath);
566927dbe93S猫头猫        const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
567927dbe93S猫头猫        if (_pluginIndex !== -1) {
5684d9d3c4cS猫头猫            throw new Error('插件已安装');
569927dbe93S猫头猫        }
570927dbe93S猫头猫        if (plugin.hash !== '') {
571927dbe93S猫头猫            const fn = nanoid();
572927dbe93S猫头猫            const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
573927dbe93S猫头猫            await copyFile(pluginPath, _pluginPath);
574927dbe93S猫头猫            plugin.path = _pluginPath;
575927dbe93S猫头猫            plugins = plugins.concat(plugin);
576927dbe93S猫头猫            pluginStateMapper.notify();
5774d9d3c4cS猫头猫            return;
578927dbe93S猫头猫        }
5794d9d3c4cS猫头猫        throw new Error('插件无法解析');
580927dbe93S猫头猫    }
5814d9d3c4cS猫头猫    throw new Error('插件不存在');
582927dbe93S猫头猫}
583927dbe93S猫头猫
58458992c6bS猫头猫async function installPluginFromUrl(url: string) {
58558992c6bS猫头猫    try {
58658992c6bS猫头猫        const funcCode = (await axios.get(url)).data;
58758992c6bS猫头猫        if (funcCode) {
58858992c6bS猫头猫            const plugin = new Plugin(funcCode, '');
58958992c6bS猫头猫            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
59058992c6bS猫头猫            if (_pluginIndex !== -1) {
5918b7ddca8S猫头猫                // 静默忽略
5928b7ddca8S猫头猫                return;
59358992c6bS猫头猫            }
59425c1bd29S猫头猫            const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
59525c1bd29S猫头猫            if (oldVersionPlugin) {
59625c1bd29S猫头猫                if (
59725c1bd29S猫头猫                    compare(
59825c1bd29S猫头猫                        oldVersionPlugin.instance.version ?? '',
59925c1bd29S猫头猫                        plugin.instance.version ?? '',
60025c1bd29S猫头猫                        '>',
60125c1bd29S猫头猫                    )
60225c1bd29S猫头猫                ) {
60325c1bd29S猫头猫                    throw new Error('已安装更新版本的插件');
60425c1bd29S猫头猫                }
60525c1bd29S猫头猫            }
60625c1bd29S猫头猫
60758992c6bS猫头猫            if (plugin.hash !== '') {
60858992c6bS猫头猫                const fn = nanoid();
60958992c6bS猫头猫                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
61058992c6bS猫头猫                await writeFile(_pluginPath, funcCode, 'utf8');
61158992c6bS猫头猫                plugin.path = _pluginPath;
61258992c6bS猫头猫                plugins = plugins.concat(plugin);
61325c1bd29S猫头猫                if (oldVersionPlugin) {
61425c1bd29S猫头猫                    plugins = plugins.filter(
61525c1bd29S猫头猫                        _ => _.hash !== oldVersionPlugin.hash,
61625c1bd29S猫头猫                    );
61725c1bd29S猫头猫                    try {
61825c1bd29S猫头猫                        await unlink(oldVersionPlugin.path);
61925c1bd29S猫头猫                    } catch {}
62025c1bd29S猫头猫                }
62158992c6bS猫头猫                pluginStateMapper.notify();
62258992c6bS猫头猫                return;
62358992c6bS猫头猫            }
62458992c6bS猫头猫            throw new Error('插件无法解析');
62558992c6bS猫头猫        }
62625c1bd29S猫头猫    } catch (e: any) {
62758992c6bS猫头猫        errorLog('URL安装插件失败', e);
62825c1bd29S猫头猫        throw new Error(e?.message ?? '');
62958992c6bS猫头猫    }
63058992c6bS猫头猫}
63158992c6bS猫头猫
632927dbe93S猫头猫/** 卸载插件 */
633927dbe93S猫头猫async function uninstallPlugin(hash: string) {
634927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
635927dbe93S猫头猫    if (targetIndex !== -1) {
636927dbe93S猫头猫        try {
63724e5e74aS猫头猫            const pluginName = plugins[targetIndex].name;
638927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
639927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
640927dbe93S猫头猫            pluginStateMapper.notify();
64124e5e74aS猫头猫            if (plugins.every(_ => _.name !== pluginName)) {
64224e5e74aS猫头猫                await MediaMeta.removePlugin(pluginName);
64324e5e74aS猫头猫            }
644927dbe93S猫头猫        } catch {}
645927dbe93S猫头猫    }
646927dbe93S猫头猫}
647927dbe93S猫头猫
64808882a77S猫头猫async function uninstallAllPlugins() {
64908882a77S猫头猫    await Promise.all(
65008882a77S猫头猫        plugins.map(async plugin => {
65108882a77S猫头猫            try {
65208882a77S猫头猫                const pluginName = plugin.name;
65308882a77S猫头猫                await unlink(plugin.path);
65408882a77S猫头猫                await MediaMeta.removePlugin(pluginName);
65508882a77S猫头猫            } catch (e) {}
65608882a77S猫头猫        }),
65708882a77S猫头猫    );
65808882a77S猫头猫    plugins = [];
65908882a77S猫头猫    pluginStateMapper.notify();
66008882a77S猫头猫}
66108882a77S猫头猫
66225c1bd29S猫头猫async function updatePlugin(plugin: Plugin) {
66325c1bd29S猫头猫    const updateUrl = plugin.instance.srcUrl;
66425c1bd29S猫头猫    if (!updateUrl) {
66525c1bd29S猫头猫        throw new Error('没有更新源');
66625c1bd29S猫头猫    }
66725c1bd29S猫头猫    try {
66825c1bd29S猫头猫        await installPluginFromUrl(updateUrl);
66925c1bd29S猫头猫    } catch (e: any) {
67025c1bd29S猫头猫        if (e.message === '插件已安装') {
67125c1bd29S猫头猫            throw new Error('当前已是最新版本');
67225c1bd29S猫头猫        } else {
67325c1bd29S猫头猫            throw e;
67425c1bd29S猫头猫        }
67525c1bd29S猫头猫    }
67625c1bd29S猫头猫}
67725c1bd29S猫头猫
678927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
679927dbe93S猫头猫    return getByName(mediaItem.platform);
680927dbe93S猫头猫}
681927dbe93S猫头猫
682927dbe93S猫头猫function getByHash(hash: string) {
683927dbe93S猫头猫    return plugins.find(_ => _.hash === hash);
684927dbe93S猫头猫}
685927dbe93S猫头猫
686927dbe93S猫头猫function getByName(name: string) {
6870e4173cdS猫头猫    return name === '本地'
6880e4173cdS猫头猫        ? localFilePlugin
6890e4173cdS猫头猫        : plugins.find(_ => _.name === name);
690927dbe93S猫头猫}
691927dbe93S猫头猫
692927dbe93S猫头猫function getValidPlugins() {
693927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
694927dbe93S猫头猫}
695927dbe93S猫头猫
696efb9da24S猫头猫function getSearchablePlugins() {
697efb9da24S猫头猫    return plugins.filter(_ => _.state === 'enabled' && _.instance.search);
698efb9da24S猫头猫}
699efb9da24S猫头猫
700927dbe93S猫头猫const PluginManager = {
701927dbe93S猫头猫    setup,
702927dbe93S猫头猫    installPlugin,
70358992c6bS猫头猫    installPluginFromUrl,
70425c1bd29S猫头猫    updatePlugin,
705927dbe93S猫头猫    uninstallPlugin,
706927dbe93S猫头猫    getByMedia,
707927dbe93S猫头猫    getByHash,
708927dbe93S猫头猫    getByName,
709927dbe93S猫头猫    getValidPlugins,
710efb9da24S猫头猫    getSearchablePlugins,
7115276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
71208882a77S猫头猫    uninstallAllPlugins,
7135276aef9S猫头猫};
714927dbe93S猫头猫
715927dbe93S猫头猫export default PluginManager;
716