xref: /MusicFree/src/core/pluginManager.ts (revision c2b3a262dd4158cf5e7cf31c605fb52887617e42)
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';
14d4cd40d8S猫头猫import {InteractionManager, 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';
21ea6d708fS猫头猫import {devLog, errorLog, trace} from '../utils/log';
22927dbe93S猫头猫import Cache from './cache';
23cfa0fc07S猫头猫import {
240e4173cdS猫头猫    getInternalData,
250e4173cdS猫头猫    InternalDataType,
260e4173cdS猫头猫    isSameMediaItem,
270e4173cdS猫头猫    resetMediaItem,
280e4173cdS猫头猫} from '@/utils/mediaItem';
297993f90eS猫头猫import {
307993f90eS猫头猫    CacheControl,
31e08d37a3S猫头猫    emptyFunction,
327993f90eS猫头猫    internalSerializeKey,
337993f90eS猫头猫    localPluginHash,
347993f90eS猫头猫    localPluginPlatform,
357993f90eS猫头猫} from '@/constants/commonConst';
36927dbe93S猫头猫import delay from '@/utils/delay';
374d9d3c4cS猫头猫import * as cheerio from 'cheerio';
387d7e864fS猫头猫import CookieManager from '@react-native-cookies/cookies';
397d7e864fS猫头猫import he from 'he';
40ef714860S猫头猫import Network from './network';
410e4173cdS猫头猫import LocalMusicSheet from './localMusicSheet';
420e4173cdS猫头猫import {FileSystem} from 'react-native-file-access';
4374d0cf81S猫头猫import Mp3Util from '@/native/mp3Util';
44e08d37a3S猫头猫import {PluginMeta} from './pluginMeta';
4534588741S猫头猫import {useEffect, useState} from 'react';
46a84a85c5S猫头猫import {getFileName} from '@/utils/fileUtils';
47927dbe93S猫头猫
4861aca335S猫头猫axios.defaults.timeout = 2000;
49927dbe93S猫头猫
50927dbe93S猫头猫const sha256 = CryptoJs.SHA256;
51927dbe93S猫头猫
52cfa0fc07S猫头猫export enum PluginStateCode {
53927dbe93S猫头猫    /** 版本不匹配 */
54927dbe93S猫头猫    VersionNotMatch = 'VERSION NOT MATCH',
55927dbe93S猫头猫    /** 无法解析 */
56927dbe93S猫头猫    CannotParse = 'CANNOT PARSE',
57927dbe93S猫头猫}
58927dbe93S猫头猫
599c34d637S猫头猫const packages: Record<string, any> = {
609c34d637S猫头猫    cheerio,
619c34d637S猫头猫    'crypto-js': CryptoJs,
629c34d637S猫头猫    axios,
639c34d637S猫头猫    dayjs,
649c34d637S猫头猫    'big-integer': bigInt,
659c34d637S猫头猫    qs,
669c34d637S猫头猫    he,
673b3d6357S猫头猫    '@react-native-cookies/cookies': CookieManager,
689c34d637S猫头猫};
699c34d637S猫头猫
70b43683eaS猫头猫const _require = (packageName: string) => {
71b43683eaS猫头猫    let pkg = packages[packageName];
72b43683eaS猫头猫    pkg.default = pkg;
73b43683eaS猫头猫    return pkg;
74b43683eaS猫头猫};
759c34d637S猫头猫
7653f8cd8eS猫头猫const _consoleBind = function (
7753f8cd8eS猫头猫    method: 'log' | 'error' | 'info' | 'warn',
7853f8cd8eS猫头猫    ...args: any
7953f8cd8eS猫头猫) {
8053f8cd8eS猫头猫    const fn = console[method];
8153f8cd8eS猫头猫    if (fn) {
8253f8cd8eS猫头猫        fn(...args);
8353f8cd8eS猫头猫        devLog(method, ...args);
8453f8cd8eS猫头猫    }
8553f8cd8eS猫头猫};
8653f8cd8eS猫头猫
8753f8cd8eS猫头猫const _console = {
8853f8cd8eS猫头猫    log: _consoleBind.bind(null, 'log'),
8953f8cd8eS猫头猫    warn: _consoleBind.bind(null, 'warn'),
9053f8cd8eS猫头猫    info: _consoleBind.bind(null, 'info'),
9153f8cd8eS猫头猫    error: _consoleBind.bind(null, 'error'),
9253f8cd8eS猫头猫};
9353f8cd8eS猫头猫
94d5bfeb7eS猫头猫//#region 插件类
95927dbe93S猫头猫export class Plugin {
96927dbe93S猫头猫    /** 插件名 */
97927dbe93S猫头猫    public name: string;
98927dbe93S猫头猫    /** 插件的hash,作为唯一id */
99927dbe93S猫头猫    public hash: string;
100927dbe93S猫头猫    /** 插件状态:激活、关闭、错误 */
101927dbe93S猫头猫    public state: 'enabled' | 'disabled' | 'error';
102927dbe93S猫头猫    /** 插件状态信息 */
103927dbe93S猫头猫    public stateCode?: PluginStateCode;
104927dbe93S猫头猫    /** 插件的实例 */
105927dbe93S猫头猫    public instance: IPlugin.IPluginInstance;
106927dbe93S猫头猫    /** 插件路径 */
107927dbe93S猫头猫    public path: string;
108927dbe93S猫头猫    /** 插件方法 */
109927dbe93S猫头猫    public methods: PluginMethods;
110927dbe93S猫头猫
11174d0cf81S猫头猫    constructor(
11274d0cf81S猫头猫        funcCode: string | (() => IPlugin.IPluginInstance),
11374d0cf81S猫头猫        pluginPath: string,
11474d0cf81S猫头猫    ) {
115927dbe93S猫头猫        this.state = 'enabled';
116927dbe93S猫头猫        let _instance: IPlugin.IPluginInstance;
1173b3d6357S猫头猫        const _module: any = {exports: {}};
118927dbe93S猫头猫        try {
11974d0cf81S猫头猫            if (typeof funcCode === 'string') {
120e0caf342S猫头猫                // 插件的环境变量
121e0caf342S猫头猫                const env = {
122e0caf342S猫头猫                    getUserVariables: () => {
123e0caf342S猫头猫                        return (
124e0caf342S猫头猫                            PluginMeta.getPluginMeta(this)?.userVariables ?? {}
125e0caf342S猫头猫                        );
126e0caf342S猫头猫                    },
127e0caf342S猫头猫                };
128e0caf342S猫头猫
1294060c00aS猫头猫                // eslint-disable-next-line no-new-func
130927dbe93S猫头猫                _instance = Function(`
131927dbe93S猫头猫                    'use strict';
132e0caf342S猫头猫                    return function(require, __musicfree_require, module, exports, console, env) {
1339c34d637S猫头猫                        ${funcCode}
134927dbe93S猫头猫                    }
135e0caf342S猫头猫                `)()(
136e0caf342S猫头猫                    _require,
137e0caf342S猫头猫                    _require,
138e0caf342S猫头猫                    _module,
139e0caf342S猫头猫                    _module.exports,
140e0caf342S猫头猫                    _console,
141e0caf342S猫头猫                    env,
142e0caf342S猫头猫                );
1433b3d6357S猫头猫                if (_module.exports.default) {
1443b3d6357S猫头猫                    _instance = _module.exports
1453b3d6357S猫头猫                        .default as IPlugin.IPluginInstance;
1463b3d6357S猫头猫                } else {
1479c34d637S猫头猫                    _instance = _module.exports as IPlugin.IPluginInstance;
1483b3d6357S猫头猫                }
14974d0cf81S猫头猫            } else {
15074d0cf81S猫头猫                _instance = funcCode();
15174d0cf81S猫头猫            }
152*c2b3a262S猫头猫            // 插件初始化后的一些操作
15395297592S猫头猫            if (Array.isArray(_instance.userVariables)) {
15495297592S猫头猫                _instance.userVariables = _instance.userVariables.filter(
15595297592S猫头猫                    it => it?.key,
15695297592S猫头猫                );
15795297592S猫头猫            }
158927dbe93S猫头猫            this.checkValid(_instance);
159927dbe93S猫头猫        } catch (e: any) {
160b43683eaS猫头猫            console.log(e);
161927dbe93S猫头猫            this.state = 'error';
162927dbe93S猫头猫            this.stateCode = PluginStateCode.CannotParse;
163927dbe93S猫头猫            if (e?.stateCode) {
164927dbe93S猫头猫                this.stateCode = e.stateCode;
165927dbe93S猫头猫            }
166927dbe93S猫头猫            errorLog(`${pluginPath}插件无法解析 `, {
167927dbe93S猫头猫                stateCode: this.stateCode,
168927dbe93S猫头猫                message: e?.message,
169927dbe93S猫头猫                stack: e?.stack,
170927dbe93S猫头猫            });
171927dbe93S猫头猫            _instance = e?.instance ?? {
172927dbe93S猫头猫                _path: '',
173927dbe93S猫头猫                platform: '',
174927dbe93S猫头猫                appVersion: '',
17520e6a092S猫头猫                async getMediaSource() {
176927dbe93S猫头猫                    return null;
177927dbe93S猫头猫                },
178927dbe93S猫头猫                async search() {
179927dbe93S猫头猫                    return {};
180927dbe93S猫头猫                },
181927dbe93S猫头猫                async getAlbumInfo() {
182927dbe93S猫头猫                    return null;
183927dbe93S猫头猫                },
184927dbe93S猫头猫            };
185927dbe93S猫头猫        }
186927dbe93S猫头猫        this.instance = _instance;
187927dbe93S猫头猫        this.path = pluginPath;
188927dbe93S猫头猫        this.name = _instance.platform;
189ab8941d9S猫头猫        if (
190ab8941d9S猫头猫            this.instance.platform === '' ||
191ab8941d9S猫头猫            this.instance.platform === undefined
192ab8941d9S猫头猫        ) {
193927dbe93S猫头猫            this.hash = '';
194927dbe93S猫头猫        } else {
19574d0cf81S猫头猫            if (typeof funcCode === 'string') {
196927dbe93S猫头猫                this.hash = sha256(funcCode).toString();
19774d0cf81S猫头猫            } else {
19874d0cf81S猫头猫                this.hash = sha256(funcCode.toString()).toString();
19974d0cf81S猫头猫            }
200927dbe93S猫头猫        }
201927dbe93S猫头猫
202927dbe93S猫头猫        // 放在最后
203927dbe93S猫头猫        this.methods = new PluginMethods(this);
204927dbe93S猫头猫    }
205927dbe93S猫头猫
206927dbe93S猫头猫    private checkValid(_instance: IPlugin.IPluginInstance) {
207927dbe93S猫头猫        /** 版本号校验 */
208927dbe93S猫头猫        if (
209927dbe93S猫头猫            _instance.appVersion &&
210927dbe93S猫头猫            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
211927dbe93S猫头猫        ) {
212927dbe93S猫头猫            throw {
213927dbe93S猫头猫                instance: _instance,
214927dbe93S猫头猫                stateCode: PluginStateCode.VersionNotMatch,
215927dbe93S猫头猫            };
216927dbe93S猫头猫        }
217927dbe93S猫头猫        return true;
218927dbe93S猫头猫    }
219927dbe93S猫头猫}
220d5bfeb7eS猫头猫//#endregion
221927dbe93S猫头猫
222d5bfeb7eS猫头猫//#region 基于插件类封装的方法,供给APP侧直接调用
223927dbe93S猫头猫/** 有缓存等信息 */
224927dbe93S猫头猫class PluginMethods implements IPlugin.IPluginInstanceMethods {
225927dbe93S猫头猫    private plugin;
226927dbe93S猫头猫    constructor(plugin: Plugin) {
227927dbe93S猫头猫        this.plugin = plugin;
228927dbe93S猫头猫    }
229927dbe93S猫头猫    /** 搜索 */
230927dbe93S猫头猫    async search<T extends ICommon.SupportMediaType>(
231927dbe93S猫头猫        query: string,
232927dbe93S猫头猫        page: number,
233927dbe93S猫头猫        type: T,
234927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
235927dbe93S猫头猫        if (!this.plugin.instance.search) {
236927dbe93S猫头猫            return {
237927dbe93S猫头猫                isEnd: true,
238927dbe93S猫头猫                data: [],
239927dbe93S猫头猫            };
240927dbe93S猫头猫        }
241927dbe93S猫头猫
2424060c00aS猫头猫        const result =
2434060c00aS猫头猫            (await this.plugin.instance.search(query, page, type)) ?? {};
244927dbe93S猫头猫        if (Array.isArray(result.data)) {
245927dbe93S猫头猫            result.data.forEach(_ => {
246927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
247927dbe93S猫头猫            });
248927dbe93S猫头猫            return {
249927dbe93S猫头猫                isEnd: result.isEnd ?? true,
250927dbe93S猫头猫                data: result.data,
251927dbe93S猫头猫            };
252927dbe93S猫头猫        }
253927dbe93S猫头猫        return {
254927dbe93S猫头猫            isEnd: true,
255927dbe93S猫头猫            data: [],
256927dbe93S猫头猫        };
257927dbe93S猫头猫    }
258927dbe93S猫头猫
259927dbe93S猫头猫    /** 获取真实源 */
26020e6a092S猫头猫    async getMediaSource(
261927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
262abaede57S猫头猫        quality: IMusic.IQualityKey = 'standard',
263927dbe93S猫头猫        retryCount = 1,
264dc160d50S猫头猫        notUpdateCache = false,
265192ae2b0S猫头猫    ): Promise<IPlugin.IMediaSourceResult | null> {
266927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
267927dbe93S猫头猫        const localPath =
2680e4173cdS猫头猫            getInternalData<string>(musicItem, InternalDataType.LOCALPATH) ??
2690e4173cdS猫头猫            getInternalData<string>(
2700e4173cdS猫头猫                LocalMusicSheet.isLocalMusic(musicItem),
2710e4173cdS猫头猫                InternalDataType.LOCALPATH,
2720e4173cdS猫头猫            );
273a84a85c5S猫头猫        if (
274a84a85c5S猫头猫            localPath &&
275a84a85c5S猫头猫            (localPath.startsWith('content://') ||
276a84a85c5S猫头猫                (await FileSystem.exists(localPath)))
277a84a85c5S猫头猫        ) {
2780e4173cdS猫头猫            trace('本地播放', localPath);
279927dbe93S猫头猫            return {
280927dbe93S猫头猫                url: localPath,
281927dbe93S猫头猫            };
282927dbe93S猫头猫        }
283a84a85c5S猫头猫        console.log('BFFF2');
284a84a85c5S猫头猫
2857993f90eS猫头猫        if (musicItem.platform === localPluginPlatform) {
286f5935920S猫头猫            throw new Error('本地音乐不存在');
287f5935920S猫头猫        }
288927dbe93S猫头猫        // 2. 缓存播放
289927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
290985f8e75S猫头猫        const pluginCacheControl =
291985f8e75S猫头猫            this.plugin.instance.cacheControl ?? 'no-cache';
292cfa0fc07S猫头猫        if (
293cfa0fc07S猫头猫            mediaCache &&
294abaede57S猫头猫            mediaCache?.qualities?.[quality]?.url &&
29548f4b873S猫头猫            (pluginCacheControl === CacheControl.Cache ||
29648f4b873S猫头猫                (pluginCacheControl === CacheControl.NoCache &&
297ef714860S猫头猫                    Network.isOffline()))
298cfa0fc07S猫头猫        ) {
2995276aef9S猫头猫            trace('播放', '缓存播放');
300abaede57S猫头猫            const qualityInfo = mediaCache.qualities[quality];
301927dbe93S猫头猫            return {
302abaede57S猫头猫                url: qualityInfo.url,
303927dbe93S猫头猫                headers: mediaCache.headers,
3044060c00aS猫头猫                userAgent:
3054060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
306927dbe93S猫头猫            };
307927dbe93S猫头猫        }
308927dbe93S猫头猫        // 3. 插件解析
30920e6a092S猫头猫        if (!this.plugin.instance.getMediaSource) {
310abaede57S猫头猫            return {url: musicItem?.qualities?.[quality]?.url ?? musicItem.url};
311927dbe93S猫头猫        }
312927dbe93S猫头猫        try {
313abaede57S猫头猫            const {url, headers} = (await this.plugin.instance.getMediaSource(
314abaede57S猫头猫                musicItem,
315abaede57S猫头猫                quality,
316abaede57S猫头猫            )) ?? {url: musicItem?.qualities?.[quality]?.url};
317927dbe93S猫头猫            if (!url) {
318a28eac61S猫头猫                throw new Error('NOT RETRY');
319927dbe93S猫头猫            }
3205276aef9S猫头猫            trace('播放', '插件播放');
321927dbe93S猫头猫            const result = {
322927dbe93S猫头猫                url,
323927dbe93S猫头猫                headers,
324927dbe93S猫头猫                userAgent: headers?.['user-agent'],
325cfa0fc07S猫头猫            } as IPlugin.IMediaSourceResult;
326927dbe93S猫头猫
327dc160d50S猫头猫            if (
328dc160d50S猫头猫                pluginCacheControl !== CacheControl.NoStore &&
329dc160d50S猫头猫                !notUpdateCache
330dc160d50S猫头猫            ) {
331abaede57S猫头猫                Cache.update(musicItem, [
332abaede57S猫头猫                    ['headers', result.headers],
333abaede57S猫头猫                    ['userAgent', result.userAgent],
334abaede57S猫头猫                    [`qualities.${quality}.url`, url],
335abaede57S猫头猫                ]);
336752ffc5aS猫头猫            }
337cfa0fc07S猫头猫
338927dbe93S猫头猫            return result;
339927dbe93S猫头猫        } catch (e: any) {
340a28eac61S猫头猫            if (retryCount > 0 && e?.message !== 'NOT RETRY') {
341927dbe93S猫头猫                await delay(150);
342abaede57S猫头猫                return this.getMediaSource(musicItem, quality, --retryCount);
343927dbe93S猫头猫            }
344927dbe93S猫头猫            errorLog('获取真实源失败', e?.message);
345ea6d708fS猫头猫            devLog('error', '获取真实源失败', e, e?.message);
346192ae2b0S猫头猫            return null;
347927dbe93S猫头猫        }
348927dbe93S猫头猫    }
349927dbe93S猫头猫
350927dbe93S猫头猫    /** 获取音乐详情 */
351927dbe93S猫头猫    async getMusicInfo(
352927dbe93S猫头猫        musicItem: ICommon.IMediaBase,
35374d0cf81S猫头猫    ): Promise<Partial<IMusic.IMusicItem> | null> {
354927dbe93S猫头猫        if (!this.plugin.instance.getMusicInfo) {
355d704daedS猫头猫            return null;
356927dbe93S猫头猫        }
35774d0cf81S猫头猫        try {
358927dbe93S猫头猫            return (
359927dbe93S猫头猫                this.plugin.instance.getMusicInfo(
3607993f90eS猫头猫                    resetMediaItem(musicItem, undefined, true),
361d704daedS猫头猫                ) ?? null
362927dbe93S猫头猫            );
363ea6d708fS猫头猫        } catch (e: any) {
364ea6d708fS猫头猫            devLog('error', '获取音乐详情失败', e, e?.message);
365d704daedS猫头猫            return null;
36674d0cf81S猫头猫        }
367927dbe93S猫头猫    }
368927dbe93S猫头猫
369927dbe93S猫头猫    /** 获取歌词 */
370927dbe93S猫头猫    async getLyric(
371927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
372927dbe93S猫头猫        from?: IMusic.IMusicItemBase,
373927dbe93S猫头猫    ): Promise<ILyric.ILyricSource | null> {
374927dbe93S猫头猫        // 1.额外存储的meta信息
375927dbe93S猫头猫        const meta = MediaMeta.get(musicItem);
376927dbe93S猫头猫        if (meta && meta.associatedLrc) {
377927dbe93S猫头猫            // 有关联歌词
378927dbe93S猫头猫            if (
379927dbe93S猫头猫                isSameMediaItem(musicItem, from) ||
380927dbe93S猫头猫                isSameMediaItem(meta.associatedLrc, musicItem)
381927dbe93S猫头猫            ) {
382927dbe93S猫头猫                // 形成环路,断开当前的环
383927dbe93S猫头猫                await MediaMeta.update(musicItem, {
384927dbe93S猫头猫                    associatedLrc: undefined,
385927dbe93S猫头猫                });
386927dbe93S猫头猫                // 无歌词
387927dbe93S猫头猫                return null;
388927dbe93S猫头猫            }
389927dbe93S猫头猫            // 获取关联歌词
3907a91f04fS猫头猫            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
3914060c00aS猫头猫            const result = await this.getLyric(
3927a91f04fS猫头猫                {...meta.associatedLrc, ...associatedMeta},
3934060c00aS猫头猫                from ?? musicItem,
3944060c00aS猫头猫            );
395927dbe93S猫头猫            if (result) {
396927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
397927dbe93S猫头猫                return result;
398927dbe93S猫头猫            }
399927dbe93S猫头猫        }
400927dbe93S猫头猫        const cache = Cache.get(musicItem);
401927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
402927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
403927dbe93S猫头猫        // 如果存在文本
404927dbe93S猫头猫        if (rawLrc) {
405927dbe93S猫头猫            return {
406927dbe93S猫头猫                rawLrc,
407927dbe93S猫头猫                lrc: lrcUrl,
408927dbe93S猫头猫            };
409927dbe93S猫头猫        }
410927dbe93S猫头猫        // 2.本地缓存
411927dbe93S猫头猫        const localLrc =
4120e4173cdS猫头猫            meta?.[internalSerializeKey]?.local?.localLrc ||
4130e4173cdS猫头猫            cache?.[internalSerializeKey]?.local?.localLrc;
414927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
415927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
416927dbe93S猫头猫            return {
417927dbe93S猫头猫                rawLrc,
418927dbe93S猫头猫                lrc: lrcUrl,
419927dbe93S猫头猫            };
420927dbe93S猫头猫        }
421927dbe93S猫头猫        // 3.优先使用url
422927dbe93S猫头猫        if (lrcUrl) {
423927dbe93S猫头猫            try {
424927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
42561aca335S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 2000})).data;
426927dbe93S猫头猫                return {
427927dbe93S猫头猫                    rawLrc,
428927dbe93S猫头猫                    lrc: lrcUrl,
429927dbe93S猫头猫                };
430927dbe93S猫头猫            } catch {
431927dbe93S猫头猫                lrcUrl = undefined;
432927dbe93S猫头猫            }
433927dbe93S猫头猫        }
434927dbe93S猫头猫        // 4. 如果地址失效
435927dbe93S猫头猫        if (!lrcUrl) {
436927dbe93S猫头猫            // 插件获得url
437927dbe93S猫头猫            try {
4387a91f04fS猫头猫                let lrcSource;
4397a91f04fS猫头猫                if (from) {
4407a91f04fS猫头猫                    lrcSource = await PluginManager.getByMedia(
4417a91f04fS猫头猫                        musicItem,
4427a91f04fS猫头猫                    )?.instance?.getLyric?.(
443927dbe93S猫头猫                        resetMediaItem(musicItem, undefined, true),
444927dbe93S猫头猫                    );
4457a91f04fS猫头猫                } else {
4467a91f04fS猫头猫                    lrcSource = await this.plugin.instance?.getLyric?.(
4477a91f04fS猫头猫                        resetMediaItem(musicItem, undefined, true),
4487a91f04fS猫头猫                    );
4497a91f04fS猫头猫                }
4507a91f04fS猫头猫
451927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
452927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
453927dbe93S猫头猫            } catch (e: any) {
454927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
455ea6d708fS猫头猫                devLog('error', '插件获取歌词失败', e, e?.message);
456927dbe93S猫头猫            }
457927dbe93S猫头猫        }
458927dbe93S猫头猫        // 5. 最后一次请求
459927dbe93S猫头猫        if (rawLrc || lrcUrl) {
460927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
461927dbe93S猫头猫            if (lrcUrl) {
462927dbe93S猫头猫                try {
46361aca335S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 2000})).data;
464927dbe93S猫头猫                } catch {}
465927dbe93S猫头猫            }
466927dbe93S猫头猫            if (rawLrc) {
467927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
468927dbe93S猫头猫                // 写入缓存
469927dbe93S猫头猫                Cache.update(musicItem, [
4700e4173cdS猫头猫                    [`${internalSerializeKey}.local.localLrc`, filename],
471927dbe93S猫头猫                ]);
472927dbe93S猫头猫                // 如果有meta
473927dbe93S猫头猫                if (meta) {
474927dbe93S猫头猫                    MediaMeta.update(musicItem, [
4750e4173cdS猫头猫                        [`${internalSerializeKey}.local.localLrc`, filename],
476927dbe93S猫头猫                    ]);
477927dbe93S猫头猫                }
478927dbe93S猫头猫                return {
479927dbe93S猫头猫                    rawLrc,
480927dbe93S猫头猫                    lrc: lrcUrl,
481927dbe93S猫头猫                };
482927dbe93S猫头猫            }
483927dbe93S猫头猫        }
4843a6f67b1S猫头猫        // 6. 如果是本地文件
4853a6f67b1S猫头猫        const isDownloaded = LocalMusicSheet.isLocalMusic(musicItem);
4863a6f67b1S猫头猫        if (musicItem.platform !== localPluginPlatform && isDownloaded) {
4873a6f67b1S猫头猫            const res = await localFilePlugin.instance!.getLyric!(isDownloaded);
4883a6f67b1S猫头猫            if (res) {
4893a6f67b1S猫头猫                return res;
4903a6f67b1S猫头猫            }
4913a6f67b1S猫头猫        }
492ea6d708fS猫头猫        devLog('warn', '无歌词');
493927dbe93S猫头猫
494927dbe93S猫头猫        return null;
495927dbe93S猫头猫    }
496927dbe93S猫头猫
497927dbe93S猫头猫    /** 获取歌词文本 */
498927dbe93S猫头猫    async getLyricText(
499927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
500927dbe93S猫头猫    ): Promise<string | undefined> {
501927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
502927dbe93S猫头猫    }
503927dbe93S猫头猫
504927dbe93S猫头猫    /** 获取专辑信息 */
505927dbe93S猫头猫    async getAlbumInfo(
506927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
507f9afcc0dS猫头猫        page: number = 1,
508f9afcc0dS猫头猫    ): Promise<IPlugin.IAlbumInfoResult | null> {
509927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
510f9afcc0dS猫头猫            return {
511f9afcc0dS猫头猫                albumItem,
512f9afcc0dS猫头猫                musicList: albumItem?.musicList ?? [],
513f9afcc0dS猫头猫                isEnd: true,
514f9afcc0dS猫头猫            };
515927dbe93S猫头猫        }
516927dbe93S猫头猫        try {
517927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
518927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
519f9afcc0dS猫头猫                page,
520927dbe93S猫头猫            );
5215276aef9S猫头猫            if (!result) {
5225276aef9S猫头猫                throw new Error();
5235276aef9S猫头猫            }
524927dbe93S猫头猫            result?.musicList?.forEach(_ => {
525927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
52696744680S猫头猫                _.album = albumItem.title;
527927dbe93S猫头猫            });
5285276aef9S猫头猫
529f9afcc0dS猫头猫            if (page <= 1) {
530f9afcc0dS猫头猫                // 合并信息
531f9afcc0dS猫头猫                return {
532f9afcc0dS猫头猫                    albumItem: {...albumItem, ...(result?.albumItem ?? {})},
533f9afcc0dS猫头猫                    isEnd: result.isEnd === false ? false : true,
534f9afcc0dS猫头猫                    musicList: result.musicList,
535f9afcc0dS猫头猫                };
536f9afcc0dS猫头猫            } else {
537f9afcc0dS猫头猫                return {
538f9afcc0dS猫头猫                    isEnd: result.isEnd === false ? false : true,
539f9afcc0dS猫头猫                    musicList: result.musicList,
540f9afcc0dS猫头猫                };
541f9afcc0dS猫头猫            }
5424394410dS猫头猫        } catch (e: any) {
5434394410dS猫头猫            trace('获取专辑信息失败', e?.message);
544ea6d708fS猫头猫            devLog('error', '获取专辑信息失败', e, e?.message);
545ea6d708fS猫头猫
546f9afcc0dS猫头猫            return null;
547927dbe93S猫头猫        }
548927dbe93S猫头猫    }
549927dbe93S猫头猫
5505830c002S猫头猫    /** 获取歌单信息 */
5515830c002S猫头猫    async getMusicSheetInfo(
5525830c002S猫头猫        sheetItem: IMusic.IMusicSheetItem,
5535830c002S猫头猫        page: number = 1,
5545830c002S猫头猫    ): Promise<IPlugin.ISheetInfoResult | null> {
5555281926bS猫头猫        if (!this.plugin.instance.getMusicSheetInfo) {
5565830c002S猫头猫            return {
5575830c002S猫头猫                sheetItem,
5585830c002S猫头猫                musicList: sheetItem?.musicList ?? [],
5595830c002S猫头猫                isEnd: true,
5605830c002S猫头猫            };
5615830c002S猫头猫        }
5625830c002S猫头猫        try {
5635830c002S猫头猫            const result = await this.plugin.instance?.getMusicSheetInfo?.(
5645830c002S猫头猫                resetMediaItem(sheetItem, undefined, true),
5655830c002S猫头猫                page,
5665830c002S猫头猫            );
5675830c002S猫头猫            if (!result) {
5685830c002S猫头猫                throw new Error();
5695830c002S猫头猫            }
5705830c002S猫头猫            result?.musicList?.forEach(_ => {
5715830c002S猫头猫                resetMediaItem(_, this.plugin.name);
5725830c002S猫头猫            });
5735830c002S猫头猫
5745830c002S猫头猫            if (page <= 1) {
5755830c002S猫头猫                // 合并信息
5765830c002S猫头猫                return {
5775830c002S猫头猫                    sheetItem: {...sheetItem, ...(result?.sheetItem ?? {})},
5785830c002S猫头猫                    isEnd: result.isEnd === false ? false : true,
5795830c002S猫头猫                    musicList: result.musicList,
5805830c002S猫头猫                };
5815830c002S猫头猫            } else {
5825830c002S猫头猫                return {
5835830c002S猫头猫                    isEnd: result.isEnd === false ? false : true,
5845830c002S猫头猫                    musicList: result.musicList,
5855830c002S猫头猫                };
5865830c002S猫头猫            }
5875830c002S猫头猫        } catch (e: any) {
5885830c002S猫头猫            trace('获取歌单信息失败', e, e?.message);
5895830c002S猫头猫            devLog('error', '获取歌单信息失败', e, e?.message);
5905830c002S猫头猫
5915830c002S猫头猫            return null;
5925830c002S猫头猫        }
5935830c002S猫头猫    }
5945830c002S猫头猫
595927dbe93S猫头猫    /** 查询作者信息 */
596efb9da24S猫头猫    async getArtistWorks<T extends IArtist.ArtistMediaType>(
597927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
598927dbe93S猫头猫        page: number,
599927dbe93S猫头猫        type: T,
600927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
601efb9da24S猫头猫        if (!this.plugin.instance.getArtistWorks) {
602927dbe93S猫头猫            return {
603927dbe93S猫头猫                isEnd: true,
604927dbe93S猫头猫                data: [],
605927dbe93S猫头猫            };
606927dbe93S猫头猫        }
607927dbe93S猫头猫        try {
608efb9da24S猫头猫            const result = await this.plugin.instance.getArtistWorks(
609927dbe93S猫头猫                artistItem,
610927dbe93S猫头猫                page,
611927dbe93S猫头猫                type,
612927dbe93S猫头猫            );
613927dbe93S猫头猫            if (!result.data) {
614927dbe93S猫头猫                return {
615927dbe93S猫头猫                    isEnd: true,
616927dbe93S猫头猫                    data: [],
617927dbe93S猫头猫                };
618927dbe93S猫头猫            }
619927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
620927dbe93S猫头猫            return {
621927dbe93S猫头猫                isEnd: result.isEnd ?? true,
622927dbe93S猫头猫                data: result.data,
623927dbe93S猫头猫            };
6244394410dS猫头猫        } catch (e: any) {
6254394410dS猫头猫            trace('查询作者信息失败', e?.message);
626ea6d708fS猫头猫            devLog('error', '查询作者信息失败', e, e?.message);
627ea6d708fS猫头猫
628927dbe93S猫头猫            throw e;
629927dbe93S猫头猫        }
630927dbe93S猫头猫    }
63108380090S猫头猫
63208380090S猫头猫    /** 导入歌单 */
63308380090S猫头猫    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
63408380090S猫头猫        try {
63508380090S猫头猫            const result =
63608380090S猫头猫                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
63708380090S猫头猫            result.forEach(_ => resetMediaItem(_, this.plugin.name));
63808380090S猫头猫            return result;
639ea6d708fS猫头猫        } catch (e: any) {
6400e4173cdS猫头猫            console.log(e);
641ea6d708fS猫头猫            devLog('error', '导入歌单失败', e, e?.message);
642ea6d708fS猫头猫
64308380090S猫头猫            return [];
64408380090S猫头猫        }
64508380090S猫头猫    }
6464d9d3c4cS猫头猫    /** 导入单曲 */
6474d9d3c4cS猫头猫    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
6484d9d3c4cS猫头猫        try {
6494d9d3c4cS猫头猫            const result = await this.plugin.instance?.importMusicItem?.(
6504d9d3c4cS猫头猫                urlLike,
6514d9d3c4cS猫头猫            );
6524d9d3c4cS猫头猫            if (!result) {
6534d9d3c4cS猫头猫                throw new Error();
6544d9d3c4cS猫头猫            }
6554d9d3c4cS猫头猫            resetMediaItem(result, this.plugin.name);
6564d9d3c4cS猫头猫            return result;
657ea6d708fS猫头猫        } catch (e: any) {
658ea6d708fS猫头猫            devLog('error', '导入单曲失败', e, e?.message);
659ea6d708fS猫头猫
6604d9d3c4cS猫头猫            return null;
6614d9d3c4cS猫头猫        }
6624d9d3c4cS猫头猫    }
663d52aa40eS猫头猫    /** 获取榜单 */
66492b6c95aS猫头猫    async getTopLists(): Promise<IMusic.IMusicSheetGroupItem[]> {
665d52aa40eS猫头猫        try {
666d52aa40eS猫头猫            const result = await this.plugin.instance?.getTopLists?.();
667d52aa40eS猫头猫            if (!result) {
668d52aa40eS猫头猫                throw new Error();
669d52aa40eS猫头猫            }
670d52aa40eS猫头猫            return result;
671d52aa40eS猫头猫        } catch (e: any) {
672d52aa40eS猫头猫            devLog('error', '获取榜单失败', e, e?.message);
673d52aa40eS猫头猫            return [];
674d52aa40eS猫头猫        }
675d52aa40eS猫头猫    }
676d52aa40eS猫头猫    /** 获取榜单详情 */
677d52aa40eS猫头猫    async getTopListDetail(
67892b6c95aS猫头猫        topListItem: IMusic.IMusicSheetItemBase,
67992b6c95aS猫头猫    ): Promise<ICommon.WithMusicList<IMusic.IMusicSheetItemBase>> {
680d52aa40eS猫头猫        try {
681d52aa40eS猫头猫            const result = await this.plugin.instance?.getTopListDetail?.(
682d52aa40eS猫头猫                topListItem,
683d52aa40eS猫头猫            );
684d52aa40eS猫头猫            if (!result) {
685d52aa40eS猫头猫                throw new Error();
686d52aa40eS猫头猫            }
687d384662fS猫头猫            if (result.musicList) {
688d384662fS猫头猫                result.musicList.forEach(_ =>
689d384662fS猫头猫                    resetMediaItem(_, this.plugin.name),
690d384662fS猫头猫                );
691d384662fS猫头猫            }
692d52aa40eS猫头猫            return result;
693d52aa40eS猫头猫        } catch (e: any) {
694d52aa40eS猫头猫            devLog('error', '获取榜单详情失败', e, e?.message);
695d52aa40eS猫头猫            return {
696d52aa40eS猫头猫                ...topListItem,
697d52aa40eS猫头猫                musicList: [],
698d52aa40eS猫头猫            };
699d52aa40eS猫头猫        }
700d52aa40eS猫头猫    }
701ceb900cdS猫头猫
7025830c002S猫头猫    /** 获取推荐歌单的tag */
703ceb900cdS猫头猫    async getRecommendSheetTags(): Promise<IPlugin.IGetRecommendSheetTagsResult> {
704ceb900cdS猫头猫        try {
705ceb900cdS猫头猫            const result =
706ceb900cdS猫头猫                await this.plugin.instance?.getRecommendSheetTags?.();
707ceb900cdS猫头猫            if (!result) {
708ceb900cdS猫头猫                throw new Error();
709ceb900cdS猫头猫            }
710ceb900cdS猫头猫            return result;
711ceb900cdS猫头猫        } catch (e: any) {
712ceb900cdS猫头猫            devLog('error', '获取推荐歌单失败', e, e?.message);
713ceb900cdS猫头猫            return {
714ceb900cdS猫头猫                data: [],
715ceb900cdS猫头猫            };
716ceb900cdS猫头猫        }
717ceb900cdS猫头猫    }
7185830c002S猫头猫    /** 获取某个tag的推荐歌单 */
719ceb900cdS猫头猫    async getRecommendSheetsByTag(
720ceb900cdS猫头猫        tagItem: ICommon.IUnique,
721ceb900cdS猫头猫        page?: number,
722ceb900cdS猫头猫    ): Promise<ICommon.PaginationResponse<IMusic.IMusicSheetItemBase>> {
723ceb900cdS猫头猫        try {
724ceb900cdS猫头猫            const result =
725ceb900cdS猫头猫                await this.plugin.instance?.getRecommendSheetsByTag?.(
726ceb900cdS猫头猫                    tagItem,
727ceb900cdS猫头猫                    page ?? 1,
728ceb900cdS猫头猫                );
729ceb900cdS猫头猫            if (!result) {
730ceb900cdS猫头猫                throw new Error();
731ceb900cdS猫头猫            }
732ceb900cdS猫头猫            if (result.isEnd !== false) {
733ceb900cdS猫头猫                result.isEnd = true;
734ceb900cdS猫头猫            }
735ceb900cdS猫头猫            if (!result.data) {
736ceb900cdS猫头猫                result.data = [];
737ceb900cdS猫头猫            }
738ceb900cdS猫头猫            result.data.forEach(item => resetMediaItem(item, this.plugin.name));
739ceb900cdS猫头猫
740ceb900cdS猫头猫            return result;
741ceb900cdS猫头猫        } catch (e: any) {
742ceb900cdS猫头猫            devLog('error', '获取推荐歌单详情失败', e, e?.message);
743ceb900cdS猫头猫            return {
744ceb900cdS猫头猫                isEnd: true,
745ceb900cdS猫头猫                data: [],
746ceb900cdS猫头猫            };
747ceb900cdS猫头猫        }
748ceb900cdS猫头猫    }
749927dbe93S猫头猫}
750d5bfeb7eS猫头猫//#endregion
7511a5528a0S猫头猫
752927dbe93S猫头猫let plugins: Array<Plugin> = [];
753927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
75474d0cf81S猫头猫
755d5bfeb7eS猫头猫//#region 本地音乐插件
75674d0cf81S猫头猫/** 本地插件 */
75774d0cf81S猫头猫const localFilePlugin = new Plugin(function () {
7580e4173cdS猫头猫    return {
759d5bfeb7eS猫头猫        platform: localPluginPlatform,
76074d0cf81S猫头猫        _path: '',
76174d0cf81S猫头猫        async getMusicInfo(musicBase) {
76274d0cf81S猫头猫            const localPath = getInternalData<string>(
76374d0cf81S猫头猫                musicBase,
76474d0cf81S猫头猫                InternalDataType.LOCALPATH,
7650e4173cdS猫头猫            );
76674d0cf81S猫头猫            if (localPath) {
76774d0cf81S猫头猫                const coverImg = await Mp3Util.getMediaCoverImg(localPath);
76874d0cf81S猫头猫                return {
76974d0cf81S猫头猫                    artwork: coverImg,
77074d0cf81S猫头猫                };
77174d0cf81S猫头猫            }
77274d0cf81S猫头猫            return null;
77374d0cf81S猫头猫        },
7747993f90eS猫头猫        async getLyric(musicBase) {
7757993f90eS猫头猫            const localPath = getInternalData<string>(
7767993f90eS猫头猫                musicBase,
7777993f90eS猫头猫                InternalDataType.LOCALPATH,
7787993f90eS猫头猫            );
7793a6f67b1S猫头猫            let rawLrc: string | null = null;
7807993f90eS猫头猫            if (localPath) {
7813a6f67b1S猫头猫                // 读取内嵌歌词
7823a6f67b1S猫头猫                try {
7833a6f67b1S猫头猫                    rawLrc = await Mp3Util.getLyric(localPath);
7843a6f67b1S猫头猫                } catch (e) {
785a84a85c5S猫头猫                    console.log('读取内嵌歌词失败', e);
7867993f90eS猫头猫                }
7873a6f67b1S猫头猫                if (!rawLrc) {
7883a6f67b1S猫头猫                    // 读取配置歌词
7893a6f67b1S猫头猫                    const lastDot = localPath.lastIndexOf('.');
7903a6f67b1S猫头猫                    const lrcPath = localPath.slice(0, lastDot) + '.lrc';
7913a6f67b1S猫头猫
7923a6f67b1S猫头猫                    try {
7933a6f67b1S猫头猫                        if (await exists(lrcPath)) {
7943a6f67b1S猫头猫                            rawLrc = await readFile(lrcPath, 'utf8');
7953a6f67b1S猫头猫                        }
7963a6f67b1S猫头猫                    } catch {}
7973a6f67b1S猫头猫                }
7983a6f67b1S猫头猫            }
7993a6f67b1S猫头猫
8003a6f67b1S猫头猫            return rawLrc
8013a6f67b1S猫头猫                ? {
8023a6f67b1S猫头猫                      rawLrc,
8033a6f67b1S猫头猫                  }
8043a6f67b1S猫头猫                : null;
8057993f90eS猫头猫        },
806a84a85c5S猫头猫        async importMusicItem(urlLike) {
807a84a85c5S猫头猫            let meta: any = {};
808a84a85c5S猫头猫            try {
809a84a85c5S猫头猫                meta = await Mp3Util.getBasicMeta(urlLike);
810a84a85c5S猫头猫            } catch {}
811a84a85c5S猫头猫            const id = await FileSystem.hash(urlLike, 'MD5');
812a84a85c5S猫头猫            return {
813a84a85c5S猫头猫                id: id,
814a84a85c5S猫头猫                platform: '本地',
815a84a85c5S猫头猫                title: meta?.title ?? getFileName(urlLike),
816a84a85c5S猫头猫                artist: meta?.artist ?? '未知歌手',
817a84a85c5S猫头猫                duration: parseInt(meta?.duration ?? '0') / 1000,
818a84a85c5S猫头猫                album: meta?.album ?? '未知专辑',
819a84a85c5S猫头猫                artwork: '',
820a84a85c5S猫头猫                [internalSerializeKey]: {
821a84a85c5S猫头猫                    localPath: urlLike,
822a84a85c5S猫头猫                },
823a84a85c5S猫头猫            };
824a84a85c5S猫头猫        },
82574d0cf81S猫头猫    };
82674d0cf81S猫头猫}, '');
8277993f90eS猫头猫localFilePlugin.hash = localPluginHash;
828927dbe93S猫头猫
829d5bfeb7eS猫头猫//#endregion
830d5bfeb7eS猫头猫
831927dbe93S猫头猫async function setup() {
832927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
833927dbe93S猫头猫    try {
834927dbe93S猫头猫        // 加载插件
835927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
836927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
837927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
8381e263108S猫头猫            trace('初始化插件', _pluginUrl);
8391e263108S猫头猫            if (
8401e263108S猫头猫                _pluginUrl.isFile() &&
8411e263108S猫头猫                (_pluginUrl.name?.endsWith?.('.js') ||
8421e263108S猫头猫                    _pluginUrl.path?.endsWith?.('.js'))
8431e263108S猫头猫            ) {
844927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
845927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
8464060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
8474060c00aS猫头猫                    p => p.hash === plugin.hash,
8484060c00aS猫头猫                );
849927dbe93S猫头猫                if (_pluginIndex !== -1) {
850927dbe93S猫头猫                    // 重复插件,直接忽略
8510c266394S猫头猫                    continue;
852927dbe93S猫头猫                }
853927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
854927dbe93S猫头猫            }
855927dbe93S猫头猫        }
856927dbe93S猫头猫
857927dbe93S猫头猫        plugins = _plugins;
858e08d37a3S猫头猫        /** 初始化meta信息 */
859*c2b3a262S猫头猫        await PluginMeta.setupMeta(plugins.map(_ => _.name));
860*c2b3a262S猫头猫        /** 查看一下是否有禁用的标记 */
861*c2b3a262S猫头猫        const allMeta = PluginMeta.getPluginMetaAll() ?? {};
862*c2b3a262S猫头猫        for (let plugin of plugins) {
863*c2b3a262S猫头猫            if (allMeta[plugin.name]?.enabled === false) {
864*c2b3a262S猫头猫                plugin.state = 'disabled';
865*c2b3a262S猫头猫            }
866*c2b3a262S猫头猫        }
867*c2b3a262S猫头猫        pluginStateMapper.notify();
868927dbe93S猫头猫    } catch (e: any) {
8694060c00aS猫头猫        ToastAndroid.show(
8704060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
8714060c00aS猫头猫            ToastAndroid.LONG,
8724060c00aS猫头猫        );
8731a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
874927dbe93S猫头猫        throw e;
875927dbe93S猫头猫    }
876927dbe93S猫头猫}
877927dbe93S猫头猫
878927dbe93S猫头猫// 安装插件
879927dbe93S猫头猫async function installPlugin(pluginPath: string) {
88022c09412S猫头猫    // if (pluginPath.endsWith('.js')) {
881927dbe93S猫头猫    const funcCode = await readFile(pluginPath, 'utf8');
882927dbe93S猫头猫    const plugin = new Plugin(funcCode, pluginPath);
883927dbe93S猫头猫    const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
884927dbe93S猫头猫    if (_pluginIndex !== -1) {
8854d9d3c4cS猫头猫        throw new Error('插件已安装');
886927dbe93S猫头猫    }
887927dbe93S猫头猫    if (plugin.hash !== '') {
888927dbe93S猫头猫        const fn = nanoid();
889927dbe93S猫头猫        const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
890927dbe93S猫头猫        await copyFile(pluginPath, _pluginPath);
891927dbe93S猫头猫        plugin.path = _pluginPath;
892927dbe93S猫头猫        plugins = plugins.concat(plugin);
893927dbe93S猫头猫        pluginStateMapper.notify();
894a84a85c5S猫头猫        return plugin;
895927dbe93S猫头猫    }
8964d9d3c4cS猫头猫    throw new Error('插件无法解析');
89722c09412S猫头猫    // }
89822c09412S猫头猫    // throw new Error('插件不存在');
899927dbe93S猫头猫}
900927dbe93S猫头猫
901*c2b3a262S猫头猫interface IInstallPluginConfig {
902*c2b3a262S猫头猫    notCheckVersion?: boolean;
903*c2b3a262S猫头猫}
904*c2b3a262S猫头猫
905*c2b3a262S猫头猫async function installPluginFromUrl(
906*c2b3a262S猫头猫    url: string,
907*c2b3a262S猫头猫    config?: IInstallPluginConfig,
908*c2b3a262S猫头猫) {
90958992c6bS猫头猫    try {
91058992c6bS猫头猫        const funcCode = (await axios.get(url)).data;
91158992c6bS猫头猫        if (funcCode) {
91258992c6bS猫头猫            const plugin = new Plugin(funcCode, '');
91358992c6bS猫头猫            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
91458992c6bS猫头猫            if (_pluginIndex !== -1) {
9158b7ddca8S猫头猫                // 静默忽略
9168b7ddca8S猫头猫                return;
91758992c6bS猫头猫            }
91825c1bd29S猫头猫            const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
919*c2b3a262S猫头猫            if (oldVersionPlugin && !config?.notCheckVersion) {
92025c1bd29S猫头猫                if (
92125c1bd29S猫头猫                    compare(
92225c1bd29S猫头猫                        oldVersionPlugin.instance.version ?? '',
92325c1bd29S猫头猫                        plugin.instance.version ?? '',
92425c1bd29S猫头猫                        '>',
92525c1bd29S猫头猫                    )
92625c1bd29S猫头猫                ) {
92725c1bd29S猫头猫                    throw new Error('已安装更新版本的插件');
92825c1bd29S猫头猫                }
92925c1bd29S猫头猫            }
93025c1bd29S猫头猫
93158992c6bS猫头猫            if (plugin.hash !== '') {
93258992c6bS猫头猫                const fn = nanoid();
93358992c6bS猫头猫                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
93458992c6bS猫头猫                await writeFile(_pluginPath, funcCode, 'utf8');
93558992c6bS猫头猫                plugin.path = _pluginPath;
93658992c6bS猫头猫                plugins = plugins.concat(plugin);
93725c1bd29S猫头猫                if (oldVersionPlugin) {
93825c1bd29S猫头猫                    plugins = plugins.filter(
93925c1bd29S猫头猫                        _ => _.hash !== oldVersionPlugin.hash,
94025c1bd29S猫头猫                    );
94125c1bd29S猫头猫                    try {
94225c1bd29S猫头猫                        await unlink(oldVersionPlugin.path);
94325c1bd29S猫头猫                    } catch {}
94425c1bd29S猫头猫                }
94558992c6bS猫头猫                pluginStateMapper.notify();
94658992c6bS猫头猫                return;
94758992c6bS猫头猫            }
94874acbfc0S猫头猫            throw new Error('插件无法解析!');
94958992c6bS猫头猫        }
95025c1bd29S猫头猫    } catch (e: any) {
951ea6d708fS猫头猫        devLog('error', 'URL安装插件失败', e, e?.message);
95258992c6bS猫头猫        errorLog('URL安装插件失败', e);
95325c1bd29S猫头猫        throw new Error(e?.message ?? '');
95458992c6bS猫头猫    }
95558992c6bS猫头猫}
95658992c6bS猫头猫
957927dbe93S猫头猫/** 卸载插件 */
958927dbe93S猫头猫async function uninstallPlugin(hash: string) {
959927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
960927dbe93S猫头猫    if (targetIndex !== -1) {
961927dbe93S猫头猫        try {
96224e5e74aS猫头猫            const pluginName = plugins[targetIndex].name;
963927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
964927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
965927dbe93S猫头猫            pluginStateMapper.notify();
96624e5e74aS猫头猫            if (plugins.every(_ => _.name !== pluginName)) {
96724e5e74aS猫头猫                await MediaMeta.removePlugin(pluginName);
96824e5e74aS猫头猫            }
969927dbe93S猫头猫        } catch {}
970927dbe93S猫头猫    }
971927dbe93S猫头猫}
972927dbe93S猫头猫
97308882a77S猫头猫async function uninstallAllPlugins() {
97408882a77S猫头猫    await Promise.all(
97508882a77S猫头猫        plugins.map(async plugin => {
97608882a77S猫头猫            try {
97708882a77S猫头猫                const pluginName = plugin.name;
97808882a77S猫头猫                await unlink(plugin.path);
97908882a77S猫头猫                await MediaMeta.removePlugin(pluginName);
98008882a77S猫头猫            } catch (e) {}
98108882a77S猫头猫        }),
98208882a77S猫头猫    );
98308882a77S猫头猫    plugins = [];
98408882a77S猫头猫    pluginStateMapper.notify();
985e08d37a3S猫头猫
986e08d37a3S猫头猫    /** 清除空余文件,异步做就可以了 */
987e08d37a3S猫头猫    readDir(pathConst.pluginPath)
988e08d37a3S猫头猫        .then(fns => {
989e08d37a3S猫头猫            fns.forEach(fn => {
990e08d37a3S猫头猫                unlink(fn.path).catch(emptyFunction);
991e08d37a3S猫头猫            });
992e08d37a3S猫头猫        })
993e08d37a3S猫头猫        .catch(emptyFunction);
99408882a77S猫头猫}
99508882a77S猫头猫
99625c1bd29S猫头猫async function updatePlugin(plugin: Plugin) {
99725c1bd29S猫头猫    const updateUrl = plugin.instance.srcUrl;
99825c1bd29S猫头猫    if (!updateUrl) {
99925c1bd29S猫头猫        throw new Error('没有更新源');
100025c1bd29S猫头猫    }
100125c1bd29S猫头猫    try {
100225c1bd29S猫头猫        await installPluginFromUrl(updateUrl);
100325c1bd29S猫头猫    } catch (e: any) {
100425c1bd29S猫头猫        if (e.message === '插件已安装') {
100525c1bd29S猫头猫            throw new Error('当前已是最新版本');
100625c1bd29S猫头猫        } else {
100725c1bd29S猫头猫            throw e;
100825c1bd29S猫头猫        }
100925c1bd29S猫头猫    }
101025c1bd29S猫头猫}
101125c1bd29S猫头猫
1012927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
10132c595535S猫头猫    return getByName(mediaItem?.platform);
1014927dbe93S猫头猫}
1015927dbe93S猫头猫
1016927dbe93S猫头猫function getByHash(hash: string) {
10177993f90eS猫头猫    return hash === localPluginHash
10187993f90eS猫头猫        ? localFilePlugin
10197993f90eS猫头猫        : plugins.find(_ => _.hash === hash);
1020927dbe93S猫头猫}
1021927dbe93S猫头猫
1022927dbe93S猫头猫function getByName(name: string) {
10237993f90eS猫头猫    return name === localPluginPlatform
10240e4173cdS猫头猫        ? localFilePlugin
10250e4173cdS猫头猫        : plugins.find(_ => _.name === name);
1026927dbe93S猫头猫}
1027927dbe93S猫头猫
1028927dbe93S猫头猫function getValidPlugins() {
1029927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
1030927dbe93S猫头猫}
1031927dbe93S猫头猫
10322b80a429S猫头猫function getSearchablePlugins(supportedSearchType?: ICommon.SupportMediaType) {
10332b80a429S猫头猫    return plugins.filter(
10342b80a429S猫头猫        _ =>
10352b80a429S猫头猫            _.state === 'enabled' &&
10362b80a429S猫头猫            _.instance.search &&
103739ac60f7S猫头猫            (supportedSearchType && _.instance.supportedSearchType
103839ac60f7S猫头猫                ? _.instance.supportedSearchType.includes(supportedSearchType)
10392b80a429S猫头猫                : true),
10402b80a429S猫头猫    );
1041efb9da24S猫头猫}
1042efb9da24S猫头猫
10432b80a429S猫头猫function getSortedSearchablePlugins(
10442b80a429S猫头猫    supportedSearchType?: ICommon.SupportMediaType,
10452b80a429S猫头猫) {
10462b80a429S猫头猫    return getSearchablePlugins(supportedSearchType).sort((a, b) =>
1047e08d37a3S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
1048e08d37a3S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
1049e08d37a3S猫头猫        0
1050e08d37a3S猫头猫            ? -1
1051e08d37a3S猫头猫            : 1,
1052e08d37a3S猫头猫    );
1053e08d37a3S猫头猫}
1054e08d37a3S猫头猫
105515feccc1S猫头猫function getTopListsablePlugins() {
105615feccc1S猫头猫    return plugins.filter(_ => _.state === 'enabled' && _.instance.getTopLists);
105715feccc1S猫头猫}
105815feccc1S猫头猫
105915feccc1S猫头猫function getSortedTopListsablePlugins() {
106015feccc1S猫头猫    return getTopListsablePlugins().sort((a, b) =>
106115feccc1S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
106215feccc1S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
106315feccc1S猫头猫        0
106415feccc1S猫头猫            ? -1
106515feccc1S猫头猫            : 1,
106615feccc1S猫头猫    );
106715feccc1S猫头猫}
106815feccc1S猫头猫
1069ceb900cdS猫头猫function getRecommendSheetablePlugins() {
1070ceb900cdS猫头猫    return plugins.filter(
1071ceb900cdS猫头猫        _ => _.state === 'enabled' && _.instance.getRecommendSheetsByTag,
1072ceb900cdS猫头猫    );
1073ceb900cdS猫头猫}
1074ceb900cdS猫头猫
1075ceb900cdS猫头猫function getSortedRecommendSheetablePlugins() {
1076ceb900cdS猫头猫    return getRecommendSheetablePlugins().sort((a, b) =>
1077ceb900cdS猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
1078ceb900cdS猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
1079ceb900cdS猫头猫        0
1080ceb900cdS猫头猫            ? -1
1081ceb900cdS猫头猫            : 1,
1082ceb900cdS猫头猫    );
1083ceb900cdS猫头猫}
1084ceb900cdS猫头猫
1085e08d37a3S猫头猫function useSortedPlugins() {
1086e08d37a3S猫头猫    const _plugins = pluginStateMapper.useMappedState();
1087e08d37a3S猫头猫    const _pluginMetaAll = PluginMeta.usePluginMetaAll();
1088e08d37a3S猫头猫
108934588741S猫头猫    const [sortedPlugins, setSortedPlugins] = useState(
109034588741S猫头猫        [..._plugins].sort((a, b) =>
1091e08d37a3S猫头猫            (_pluginMetaAll[a.name]?.order ?? Infinity) -
1092e08d37a3S猫头猫                (_pluginMetaAll[b.name]?.order ?? Infinity) <
1093e08d37a3S猫头猫            0
1094e08d37a3S猫头猫                ? -1
1095e08d37a3S猫头猫                : 1,
109634588741S猫头猫        ),
1097e08d37a3S猫头猫    );
109834588741S猫头猫
109934588741S猫头猫    useEffect(() => {
1100d4cd40d8S猫头猫        InteractionManager.runAfterInteractions(() => {
110134588741S猫头猫            setSortedPlugins(
110234588741S猫头猫                [..._plugins].sort((a, b) =>
110334588741S猫头猫                    (_pluginMetaAll[a.name]?.order ?? Infinity) -
110434588741S猫头猫                        (_pluginMetaAll[b.name]?.order ?? Infinity) <
110534588741S猫头猫                    0
110634588741S猫头猫                        ? -1
110734588741S猫头猫                        : 1,
110834588741S猫头猫                ),
110934588741S猫头猫            );
1110d4cd40d8S猫头猫        });
111134588741S猫头猫    }, [_plugins, _pluginMetaAll]);
111234588741S猫头猫
111334588741S猫头猫    return sortedPlugins;
1114e08d37a3S猫头猫}
1115e08d37a3S猫头猫
1116*c2b3a262S猫头猫async function setPluginEnabled(plugin: Plugin, enabled?: boolean) {
1117*c2b3a262S猫头猫    const target = plugins.find(it => it.hash === plugin.hash);
1118*c2b3a262S猫头猫    if (target) {
1119*c2b3a262S猫头猫        target.state = enabled ? 'enabled' : 'disabled';
1120*c2b3a262S猫头猫        plugins = [...plugins];
1121*c2b3a262S猫头猫        pluginStateMapper.notify();
1122*c2b3a262S猫头猫        PluginMeta.setPluginMetaProp(plugin, 'enabled', enabled);
1123*c2b3a262S猫头猫    }
1124*c2b3a262S猫头猫}
1125*c2b3a262S猫头猫
1126927dbe93S猫头猫const PluginManager = {
1127927dbe93S猫头猫    setup,
1128927dbe93S猫头猫    installPlugin,
112958992c6bS猫头猫    installPluginFromUrl,
113025c1bd29S猫头猫    updatePlugin,
1131927dbe93S猫头猫    uninstallPlugin,
1132927dbe93S猫头猫    getByMedia,
1133927dbe93S猫头猫    getByHash,
1134927dbe93S猫头猫    getByName,
1135927dbe93S猫头猫    getValidPlugins,
1136efb9da24S猫头猫    getSearchablePlugins,
1137e08d37a3S猫头猫    getSortedSearchablePlugins,
113815feccc1S猫头猫    getTopListsablePlugins,
1139ceb900cdS猫头猫    getSortedRecommendSheetablePlugins,
114015feccc1S猫头猫    getSortedTopListsablePlugins,
11415276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
1142e08d37a3S猫头猫    useSortedPlugins,
114308882a77S猫头猫    uninstallAllPlugins,
1144*c2b3a262S猫头猫    setPluginEnabled,
11455276aef9S猫头猫};
1146927dbe93S猫头猫
1147927dbe93S猫头猫export default PluginManager;
1148