xref: /MusicFree/src/core/pluginManager.ts (revision e36e2599644694ccfcb227890698ec9b0477cf3c)
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猫头猫                    },
127e3fa9b3cS猫头猫                    os: 'android',
128e0caf342S猫头猫                };
129e0caf342S猫头猫
1304060c00aS猫头猫                // eslint-disable-next-line no-new-func
131927dbe93S猫头猫                _instance = Function(`
132927dbe93S猫头猫                    'use strict';
133e0caf342S猫头猫                    return function(require, __musicfree_require, module, exports, console, env) {
1349c34d637S猫头猫                        ${funcCode}
135927dbe93S猫头猫                    }
136e0caf342S猫头猫                `)()(
137e0caf342S猫头猫                    _require,
138e0caf342S猫头猫                    _require,
139e0caf342S猫头猫                    _module,
140e0caf342S猫头猫                    _module.exports,
141e0caf342S猫头猫                    _console,
142e0caf342S猫头猫                    env,
143e0caf342S猫头猫                );
1443b3d6357S猫头猫                if (_module.exports.default) {
1453b3d6357S猫头猫                    _instance = _module.exports
1463b3d6357S猫头猫                        .default as IPlugin.IPluginInstance;
1473b3d6357S猫头猫                } else {
1489c34d637S猫头猫                    _instance = _module.exports as IPlugin.IPluginInstance;
1493b3d6357S猫头猫                }
15074d0cf81S猫头猫            } else {
15174d0cf81S猫头猫                _instance = funcCode();
15274d0cf81S猫头猫            }
153c2b3a262S猫头猫            // 插件初始化后的一些操作
15495297592S猫头猫            if (Array.isArray(_instance.userVariables)) {
15595297592S猫头猫                _instance.userVariables = _instance.userVariables.filter(
15695297592S猫头猫                    it => it?.key,
15795297592S猫头猫                );
15895297592S猫头猫            }
159927dbe93S猫头猫            this.checkValid(_instance);
160927dbe93S猫头猫        } catch (e: any) {
161b43683eaS猫头猫            console.log(e);
162927dbe93S猫头猫            this.state = 'error';
163927dbe93S猫头猫            this.stateCode = PluginStateCode.CannotParse;
164927dbe93S猫头猫            if (e?.stateCode) {
165927dbe93S猫头猫                this.stateCode = e.stateCode;
166927dbe93S猫头猫            }
167927dbe93S猫头猫            errorLog(`${pluginPath}插件无法解析 `, {
168927dbe93S猫头猫                stateCode: this.stateCode,
169927dbe93S猫头猫                message: e?.message,
170927dbe93S猫头猫                stack: e?.stack,
171927dbe93S猫头猫            });
172927dbe93S猫头猫            _instance = e?.instance ?? {
173927dbe93S猫头猫                _path: '',
174927dbe93S猫头猫                platform: '',
175927dbe93S猫头猫                appVersion: '',
17620e6a092S猫头猫                async getMediaSource() {
177927dbe93S猫头猫                    return null;
178927dbe93S猫头猫                },
179927dbe93S猫头猫                async search() {
180927dbe93S猫头猫                    return {};
181927dbe93S猫头猫                },
182927dbe93S猫头猫                async getAlbumInfo() {
183927dbe93S猫头猫                    return null;
184927dbe93S猫头猫                },
185927dbe93S猫头猫            };
186927dbe93S猫头猫        }
187927dbe93S猫头猫        this.instance = _instance;
188927dbe93S猫头猫        this.path = pluginPath;
189927dbe93S猫头猫        this.name = _instance.platform;
190ab8941d9S猫头猫        if (
191ab8941d9S猫头猫            this.instance.platform === '' ||
192ab8941d9S猫头猫            this.instance.platform === undefined
193ab8941d9S猫头猫        ) {
194927dbe93S猫头猫            this.hash = '';
195927dbe93S猫头猫        } else {
19674d0cf81S猫头猫            if (typeof funcCode === 'string') {
197927dbe93S猫头猫                this.hash = sha256(funcCode).toString();
19874d0cf81S猫头猫            } else {
19974d0cf81S猫头猫                this.hash = sha256(funcCode.toString()).toString();
20074d0cf81S猫头猫            }
201927dbe93S猫头猫        }
202927dbe93S猫头猫
203927dbe93S猫头猫        // 放在最后
204927dbe93S猫头猫        this.methods = new PluginMethods(this);
205927dbe93S猫头猫    }
206927dbe93S猫头猫
207927dbe93S猫头猫    private checkValid(_instance: IPlugin.IPluginInstance) {
208927dbe93S猫头猫        /** 版本号校验 */
209927dbe93S猫头猫        if (
210927dbe93S猫头猫            _instance.appVersion &&
211927dbe93S猫头猫            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
212927dbe93S猫头猫        ) {
213927dbe93S猫头猫            throw {
214927dbe93S猫头猫                instance: _instance,
215927dbe93S猫头猫                stateCode: PluginStateCode.VersionNotMatch,
216927dbe93S猫头猫            };
217927dbe93S猫头猫        }
218927dbe93S猫头猫        return true;
219927dbe93S猫头猫    }
220927dbe93S猫头猫}
221d5bfeb7eS猫头猫//#endregion
222927dbe93S猫头猫
223d5bfeb7eS猫头猫//#region 基于插件类封装的方法,供给APP侧直接调用
224927dbe93S猫头猫/** 有缓存等信息 */
225927dbe93S猫头猫class PluginMethods implements IPlugin.IPluginInstanceMethods {
226927dbe93S猫头猫    private plugin;
227927dbe93S猫头猫    constructor(plugin: Plugin) {
228927dbe93S猫头猫        this.plugin = plugin;
229927dbe93S猫头猫    }
230927dbe93S猫头猫    /** 搜索 */
231927dbe93S猫头猫    async search<T extends ICommon.SupportMediaType>(
232927dbe93S猫头猫        query: string,
233927dbe93S猫头猫        page: number,
234927dbe93S猫头猫        type: T,
235927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
236927dbe93S猫头猫        if (!this.plugin.instance.search) {
237927dbe93S猫头猫            return {
238927dbe93S猫头猫                isEnd: true,
239927dbe93S猫头猫                data: [],
240927dbe93S猫头猫            };
241927dbe93S猫头猫        }
242927dbe93S猫头猫
2434060c00aS猫头猫        const result =
2444060c00aS猫头猫            (await this.plugin.instance.search(query, page, type)) ?? {};
245927dbe93S猫头猫        if (Array.isArray(result.data)) {
246927dbe93S猫头猫            result.data.forEach(_ => {
247927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
248927dbe93S猫头猫            });
249927dbe93S猫头猫            return {
250927dbe93S猫头猫                isEnd: result.isEnd ?? true,
251927dbe93S猫头猫                data: result.data,
252927dbe93S猫头猫            };
253927dbe93S猫头猫        }
254927dbe93S猫头猫        return {
255927dbe93S猫头猫            isEnd: true,
256927dbe93S猫头猫            data: [],
257927dbe93S猫头猫        };
258927dbe93S猫头猫    }
259927dbe93S猫头猫
260927dbe93S猫头猫    /** 获取真实源 */
26120e6a092S猫头猫    async getMediaSource(
262927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
263abaede57S猫头猫        quality: IMusic.IQualityKey = 'standard',
264927dbe93S猫头猫        retryCount = 1,
265dc160d50S猫头猫        notUpdateCache = false,
266192ae2b0S猫头猫    ): Promise<IPlugin.IMediaSourceResult | null> {
267927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
268927dbe93S猫头猫        const localPath =
2690e4173cdS猫头猫            getInternalData<string>(musicItem, InternalDataType.LOCALPATH) ??
2700e4173cdS猫头猫            getInternalData<string>(
2710e4173cdS猫头猫                LocalMusicSheet.isLocalMusic(musicItem),
2720e4173cdS猫头猫                InternalDataType.LOCALPATH,
2730e4173cdS猫头猫            );
274a84a85c5S猫头猫        if (
275a84a85c5S猫头猫            localPath &&
276a84a85c5S猫头猫            (localPath.startsWith('content://') ||
277a84a85c5S猫头猫                (await FileSystem.exists(localPath)))
278a84a85c5S猫头猫        ) {
2790e4173cdS猫头猫            trace('本地播放', localPath);
280927dbe93S猫头猫            return {
281927dbe93S猫头猫                url: localPath,
282927dbe93S猫头猫            };
283927dbe93S猫头猫        }
284a84a85c5S猫头猫        console.log('BFFF2');
285a84a85c5S猫头猫
2867993f90eS猫头猫        if (musicItem.platform === localPluginPlatform) {
287f5935920S猫头猫            throw new Error('本地音乐不存在');
288f5935920S猫头猫        }
289927dbe93S猫头猫        // 2. 缓存播放
290927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
291985f8e75S猫头猫        const pluginCacheControl =
292985f8e75S猫头猫            this.plugin.instance.cacheControl ?? 'no-cache';
293cfa0fc07S猫头猫        if (
294cfa0fc07S猫头猫            mediaCache &&
295abaede57S猫头猫            mediaCache?.qualities?.[quality]?.url &&
29648f4b873S猫头猫            (pluginCacheControl === CacheControl.Cache ||
29748f4b873S猫头猫                (pluginCacheControl === CacheControl.NoCache &&
298ef714860S猫头猫                    Network.isOffline()))
299cfa0fc07S猫头猫        ) {
3005276aef9S猫头猫            trace('播放', '缓存播放');
301abaede57S猫头猫            const qualityInfo = mediaCache.qualities[quality];
302927dbe93S猫头猫            return {
303abaede57S猫头猫                url: qualityInfo.url,
304927dbe93S猫头猫                headers: mediaCache.headers,
3054060c00aS猫头猫                userAgent:
3064060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
307927dbe93S猫头猫            };
308927dbe93S猫头猫        }
309927dbe93S猫头猫        // 3. 插件解析
31020e6a092S猫头猫        if (!this.plugin.instance.getMediaSource) {
311abaede57S猫头猫            return {url: musicItem?.qualities?.[quality]?.url ?? musicItem.url};
312927dbe93S猫头猫        }
313927dbe93S猫头猫        try {
314abaede57S猫头猫            const {url, headers} = (await this.plugin.instance.getMediaSource(
315abaede57S猫头猫                musicItem,
316abaede57S猫头猫                quality,
317abaede57S猫头猫            )) ?? {url: musicItem?.qualities?.[quality]?.url};
318927dbe93S猫头猫            if (!url) {
319a28eac61S猫头猫                throw new Error('NOT RETRY');
320927dbe93S猫头猫            }
3215276aef9S猫头猫            trace('播放', '插件播放');
322927dbe93S猫头猫            const result = {
323927dbe93S猫头猫                url,
324927dbe93S猫头猫                headers,
325927dbe93S猫头猫                userAgent: headers?.['user-agent'],
326cfa0fc07S猫头猫            } as IPlugin.IMediaSourceResult;
327927dbe93S猫头猫
328dc160d50S猫头猫            if (
329dc160d50S猫头猫                pluginCacheControl !== CacheControl.NoStore &&
330dc160d50S猫头猫                !notUpdateCache
331dc160d50S猫头猫            ) {
332abaede57S猫头猫                Cache.update(musicItem, [
333abaede57S猫头猫                    ['headers', result.headers],
334abaede57S猫头猫                    ['userAgent', result.userAgent],
335abaede57S猫头猫                    [`qualities.${quality}.url`, url],
336abaede57S猫头猫                ]);
337752ffc5aS猫头猫            }
338cfa0fc07S猫头猫
339927dbe93S猫头猫            return result;
340927dbe93S猫头猫        } catch (e: any) {
341a28eac61S猫头猫            if (retryCount > 0 && e?.message !== 'NOT RETRY') {
342927dbe93S猫头猫                await delay(150);
343abaede57S猫头猫                return this.getMediaSource(musicItem, quality, --retryCount);
344927dbe93S猫头猫            }
345927dbe93S猫头猫            errorLog('获取真实源失败', e?.message);
346ea6d708fS猫头猫            devLog('error', '获取真实源失败', e, e?.message);
347192ae2b0S猫头猫            return null;
348927dbe93S猫头猫        }
349927dbe93S猫头猫    }
350927dbe93S猫头猫
351927dbe93S猫头猫    /** 获取音乐详情 */
352927dbe93S猫头猫    async getMusicInfo(
353927dbe93S猫头猫        musicItem: ICommon.IMediaBase,
35474d0cf81S猫头猫    ): Promise<Partial<IMusic.IMusicItem> | null> {
355927dbe93S猫头猫        if (!this.plugin.instance.getMusicInfo) {
356d704daedS猫头猫            return null;
357927dbe93S猫头猫        }
35874d0cf81S猫头猫        try {
359927dbe93S猫头猫            return (
360927dbe93S猫头猫                this.plugin.instance.getMusicInfo(
3617993f90eS猫头猫                    resetMediaItem(musicItem, undefined, true),
362d704daedS猫头猫                ) ?? null
363927dbe93S猫头猫            );
364ea6d708fS猫头猫        } catch (e: any) {
365ea6d708fS猫头猫            devLog('error', '获取音乐详情失败', e, e?.message);
366d704daedS猫头猫            return null;
36774d0cf81S猫头猫        }
368927dbe93S猫头猫    }
369927dbe93S猫头猫
370927dbe93S猫头猫    /** 获取歌词 */
371927dbe93S猫头猫    async getLyric(
372927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
373927dbe93S猫头猫        from?: IMusic.IMusicItemBase,
374927dbe93S猫头猫    ): Promise<ILyric.ILyricSource | null> {
375927dbe93S猫头猫        // 1.额外存储的meta信息
376927dbe93S猫头猫        const meta = MediaMeta.get(musicItem);
377927dbe93S猫头猫        if (meta && meta.associatedLrc) {
378927dbe93S猫头猫            // 有关联歌词
379927dbe93S猫头猫            if (
380927dbe93S猫头猫                isSameMediaItem(musicItem, from) ||
381927dbe93S猫头猫                isSameMediaItem(meta.associatedLrc, musicItem)
382927dbe93S猫头猫            ) {
383927dbe93S猫头猫                // 形成环路,断开当前的环
384927dbe93S猫头猫                await MediaMeta.update(musicItem, {
385927dbe93S猫头猫                    associatedLrc: undefined,
386927dbe93S猫头猫                });
387927dbe93S猫头猫                // 无歌词
388927dbe93S猫头猫                return null;
389927dbe93S猫头猫            }
390927dbe93S猫头猫            // 获取关联歌词
3917a91f04fS猫头猫            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
3924060c00aS猫头猫            const result = await this.getLyric(
3937a91f04fS猫头猫                {...meta.associatedLrc, ...associatedMeta},
3944060c00aS猫头猫                from ?? musicItem,
3954060c00aS猫头猫            );
396927dbe93S猫头猫            if (result) {
397927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
398927dbe93S猫头猫                return result;
399927dbe93S猫头猫            }
400927dbe93S猫头猫        }
401927dbe93S猫头猫        const cache = Cache.get(musicItem);
402927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
403927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
404927dbe93S猫头猫        // 如果存在文本
405927dbe93S猫头猫        if (rawLrc) {
406927dbe93S猫头猫            return {
407927dbe93S猫头猫                rawLrc,
408927dbe93S猫头猫                lrc: lrcUrl,
409927dbe93S猫头猫            };
410927dbe93S猫头猫        }
411927dbe93S猫头猫        // 2.本地缓存
412927dbe93S猫头猫        const localLrc =
4130e4173cdS猫头猫            meta?.[internalSerializeKey]?.local?.localLrc ||
4140e4173cdS猫头猫            cache?.[internalSerializeKey]?.local?.localLrc;
415927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
416927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
417927dbe93S猫头猫            return {
418927dbe93S猫头猫                rawLrc,
419927dbe93S猫头猫                lrc: lrcUrl,
420927dbe93S猫头猫            };
421927dbe93S猫头猫        }
422927dbe93S猫头猫        // 3.优先使用url
423927dbe93S猫头猫        if (lrcUrl) {
424927dbe93S猫头猫            try {
425927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
42661aca335S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 2000})).data;
427927dbe93S猫头猫                return {
428927dbe93S猫头猫                    rawLrc,
429927dbe93S猫头猫                    lrc: lrcUrl,
430927dbe93S猫头猫                };
431927dbe93S猫头猫            } catch {
432927dbe93S猫头猫                lrcUrl = undefined;
433927dbe93S猫头猫            }
434927dbe93S猫头猫        }
435927dbe93S猫头猫        // 4. 如果地址失效
436927dbe93S猫头猫        if (!lrcUrl) {
437927dbe93S猫头猫            // 插件获得url
438927dbe93S猫头猫            try {
4397a91f04fS猫头猫                let lrcSource;
4407a91f04fS猫头猫                if (from) {
4417a91f04fS猫头猫                    lrcSource = await PluginManager.getByMedia(
4427a91f04fS猫头猫                        musicItem,
4437a91f04fS猫头猫                    )?.instance?.getLyric?.(
444927dbe93S猫头猫                        resetMediaItem(musicItem, undefined, true),
445927dbe93S猫头猫                    );
4467a91f04fS猫头猫                } else {
4477a91f04fS猫头猫                    lrcSource = await this.plugin.instance?.getLyric?.(
4487a91f04fS猫头猫                        resetMediaItem(musicItem, undefined, true),
4497a91f04fS猫头猫                    );
4507a91f04fS猫头猫                }
4517a91f04fS猫头猫
452927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
453927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
454927dbe93S猫头猫            } catch (e: any) {
455927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
456ea6d708fS猫头猫                devLog('error', '插件获取歌词失败', e, e?.message);
457927dbe93S猫头猫            }
458927dbe93S猫头猫        }
459927dbe93S猫头猫        // 5. 最后一次请求
460927dbe93S猫头猫        if (rawLrc || lrcUrl) {
461927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
462927dbe93S猫头猫            if (lrcUrl) {
463927dbe93S猫头猫                try {
46461aca335S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 2000})).data;
465927dbe93S猫头猫                } catch {}
466927dbe93S猫头猫            }
467927dbe93S猫头猫            if (rawLrc) {
468927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
469927dbe93S猫头猫                // 写入缓存
470927dbe93S猫头猫                Cache.update(musicItem, [
4710e4173cdS猫头猫                    [`${internalSerializeKey}.local.localLrc`, filename],
472927dbe93S猫头猫                ]);
473927dbe93S猫头猫                // 如果有meta
474927dbe93S猫头猫                if (meta) {
475927dbe93S猫头猫                    MediaMeta.update(musicItem, [
4760e4173cdS猫头猫                        [`${internalSerializeKey}.local.localLrc`, filename],
477927dbe93S猫头猫                    ]);
478927dbe93S猫头猫                }
479927dbe93S猫头猫                return {
480927dbe93S猫头猫                    rawLrc,
481927dbe93S猫头猫                    lrc: lrcUrl,
482927dbe93S猫头猫                };
483927dbe93S猫头猫            }
484927dbe93S猫头猫        }
4853a6f67b1S猫头猫        // 6. 如果是本地文件
4863a6f67b1S猫头猫        const isDownloaded = LocalMusicSheet.isLocalMusic(musicItem);
4873a6f67b1S猫头猫        if (musicItem.platform !== localPluginPlatform && isDownloaded) {
4883a6f67b1S猫头猫            const res = await localFilePlugin.instance!.getLyric!(isDownloaded);
4893a6f67b1S猫头猫            if (res) {
4903a6f67b1S猫头猫                return res;
4913a6f67b1S猫头猫            }
4923a6f67b1S猫头猫        }
493ea6d708fS猫头猫        devLog('warn', '无歌词');
494927dbe93S猫头猫
495927dbe93S猫头猫        return null;
496927dbe93S猫头猫    }
497927dbe93S猫头猫
498927dbe93S猫头猫    /** 获取歌词文本 */
499927dbe93S猫头猫    async getLyricText(
500927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
501927dbe93S猫头猫    ): Promise<string | undefined> {
502927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
503927dbe93S猫头猫    }
504927dbe93S猫头猫
505927dbe93S猫头猫    /** 获取专辑信息 */
506927dbe93S猫头猫    async getAlbumInfo(
507927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
508f9afcc0dS猫头猫        page: number = 1,
509f9afcc0dS猫头猫    ): Promise<IPlugin.IAlbumInfoResult | null> {
510927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
511f9afcc0dS猫头猫            return {
512f9afcc0dS猫头猫                albumItem,
513f9afcc0dS猫头猫                musicList: albumItem?.musicList ?? [],
514f9afcc0dS猫头猫                isEnd: true,
515f9afcc0dS猫头猫            };
516927dbe93S猫头猫        }
517927dbe93S猫头猫        try {
518927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
519927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
520f9afcc0dS猫头猫                page,
521927dbe93S猫头猫            );
5225276aef9S猫头猫            if (!result) {
5235276aef9S猫头猫                throw new Error();
5245276aef9S猫头猫            }
525927dbe93S猫头猫            result?.musicList?.forEach(_ => {
526927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
52796744680S猫头猫                _.album = albumItem.title;
528927dbe93S猫头猫            });
5295276aef9S猫头猫
530f9afcc0dS猫头猫            if (page <= 1) {
531f9afcc0dS猫头猫                // 合并信息
532f9afcc0dS猫头猫                return {
533f9afcc0dS猫头猫                    albumItem: {...albumItem, ...(result?.albumItem ?? {})},
534f9afcc0dS猫头猫                    isEnd: result.isEnd === false ? false : true,
535f9afcc0dS猫头猫                    musicList: result.musicList,
536f9afcc0dS猫头猫                };
537f9afcc0dS猫头猫            } else {
538f9afcc0dS猫头猫                return {
539f9afcc0dS猫头猫                    isEnd: result.isEnd === false ? false : true,
540f9afcc0dS猫头猫                    musicList: result.musicList,
541f9afcc0dS猫头猫                };
542f9afcc0dS猫头猫            }
5434394410dS猫头猫        } catch (e: any) {
5444394410dS猫头猫            trace('获取专辑信息失败', e?.message);
545ea6d708fS猫头猫            devLog('error', '获取专辑信息失败', e, e?.message);
546ea6d708fS猫头猫
547f9afcc0dS猫头猫            return null;
548927dbe93S猫头猫        }
549927dbe93S猫头猫    }
550927dbe93S猫头猫
5515830c002S猫头猫    /** 获取歌单信息 */
5525830c002S猫头猫    async getMusicSheetInfo(
5535830c002S猫头猫        sheetItem: IMusic.IMusicSheetItem,
5545830c002S猫头猫        page: number = 1,
5555830c002S猫头猫    ): Promise<IPlugin.ISheetInfoResult | null> {
5565281926bS猫头猫        if (!this.plugin.instance.getMusicSheetInfo) {
5575830c002S猫头猫            return {
5585830c002S猫头猫                sheetItem,
5595830c002S猫头猫                musicList: sheetItem?.musicList ?? [],
5605830c002S猫头猫                isEnd: true,
5615830c002S猫头猫            };
5625830c002S猫头猫        }
5635830c002S猫头猫        try {
5645830c002S猫头猫            const result = await this.plugin.instance?.getMusicSheetInfo?.(
5655830c002S猫头猫                resetMediaItem(sheetItem, undefined, true),
5665830c002S猫头猫                page,
5675830c002S猫头猫            );
5685830c002S猫头猫            if (!result) {
5695830c002S猫头猫                throw new Error();
5705830c002S猫头猫            }
5715830c002S猫头猫            result?.musicList?.forEach(_ => {
5725830c002S猫头猫                resetMediaItem(_, this.plugin.name);
5735830c002S猫头猫            });
5745830c002S猫头猫
5755830c002S猫头猫            if (page <= 1) {
5765830c002S猫头猫                // 合并信息
5775830c002S猫头猫                return {
5785830c002S猫头猫                    sheetItem: {...sheetItem, ...(result?.sheetItem ?? {})},
5795830c002S猫头猫                    isEnd: result.isEnd === false ? false : true,
5805830c002S猫头猫                    musicList: result.musicList,
5815830c002S猫头猫                };
5825830c002S猫头猫            } else {
5835830c002S猫头猫                return {
5845830c002S猫头猫                    isEnd: result.isEnd === false ? false : true,
5855830c002S猫头猫                    musicList: result.musicList,
5865830c002S猫头猫                };
5875830c002S猫头猫            }
5885830c002S猫头猫        } catch (e: any) {
5895830c002S猫头猫            trace('获取歌单信息失败', e, e?.message);
5905830c002S猫头猫            devLog('error', '获取歌单信息失败', e, e?.message);
5915830c002S猫头猫
5925830c002S猫头猫            return null;
5935830c002S猫头猫        }
5945830c002S猫头猫    }
5955830c002S猫头猫
596927dbe93S猫头猫    /** 查询作者信息 */
597efb9da24S猫头猫    async getArtistWorks<T extends IArtist.ArtistMediaType>(
598927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
599927dbe93S猫头猫        page: number,
600927dbe93S猫头猫        type: T,
601927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
602efb9da24S猫头猫        if (!this.plugin.instance.getArtistWorks) {
603927dbe93S猫头猫            return {
604927dbe93S猫头猫                isEnd: true,
605927dbe93S猫头猫                data: [],
606927dbe93S猫头猫            };
607927dbe93S猫头猫        }
608927dbe93S猫头猫        try {
609efb9da24S猫头猫            const result = await this.plugin.instance.getArtistWorks(
610927dbe93S猫头猫                artistItem,
611927dbe93S猫头猫                page,
612927dbe93S猫头猫                type,
613927dbe93S猫头猫            );
614927dbe93S猫头猫            if (!result.data) {
615927dbe93S猫头猫                return {
616927dbe93S猫头猫                    isEnd: true,
617927dbe93S猫头猫                    data: [],
618927dbe93S猫头猫                };
619927dbe93S猫头猫            }
620927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
621927dbe93S猫头猫            return {
622927dbe93S猫头猫                isEnd: result.isEnd ?? true,
623927dbe93S猫头猫                data: result.data,
624927dbe93S猫头猫            };
6254394410dS猫头猫        } catch (e: any) {
6264394410dS猫头猫            trace('查询作者信息失败', e?.message);
627ea6d708fS猫头猫            devLog('error', '查询作者信息失败', e, e?.message);
628ea6d708fS猫头猫
629927dbe93S猫头猫            throw e;
630927dbe93S猫头猫        }
631927dbe93S猫头猫    }
63208380090S猫头猫
63308380090S猫头猫    /** 导入歌单 */
63408380090S猫头猫    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
63508380090S猫头猫        try {
63608380090S猫头猫            const result =
63708380090S猫头猫                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
63808380090S猫头猫            result.forEach(_ => resetMediaItem(_, this.plugin.name));
63908380090S猫头猫            return result;
640ea6d708fS猫头猫        } catch (e: any) {
6410e4173cdS猫头猫            console.log(e);
642ea6d708fS猫头猫            devLog('error', '导入歌单失败', e, e?.message);
643ea6d708fS猫头猫
64408380090S猫头猫            return [];
64508380090S猫头猫        }
64608380090S猫头猫    }
6474d9d3c4cS猫头猫    /** 导入单曲 */
6484d9d3c4cS猫头猫    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
6494d9d3c4cS猫头猫        try {
6504d9d3c4cS猫头猫            const result = await this.plugin.instance?.importMusicItem?.(
6514d9d3c4cS猫头猫                urlLike,
6524d9d3c4cS猫头猫            );
6534d9d3c4cS猫头猫            if (!result) {
6544d9d3c4cS猫头猫                throw new Error();
6554d9d3c4cS猫头猫            }
6564d9d3c4cS猫头猫            resetMediaItem(result, this.plugin.name);
6574d9d3c4cS猫头猫            return result;
658ea6d708fS猫头猫        } catch (e: any) {
659ea6d708fS猫头猫            devLog('error', '导入单曲失败', e, e?.message);
660ea6d708fS猫头猫
6614d9d3c4cS猫头猫            return null;
6624d9d3c4cS猫头猫        }
6634d9d3c4cS猫头猫    }
664d52aa40eS猫头猫    /** 获取榜单 */
66592b6c95aS猫头猫    async getTopLists(): Promise<IMusic.IMusicSheetGroupItem[]> {
666d52aa40eS猫头猫        try {
667d52aa40eS猫头猫            const result = await this.plugin.instance?.getTopLists?.();
668d52aa40eS猫头猫            if (!result) {
669d52aa40eS猫头猫                throw new Error();
670d52aa40eS猫头猫            }
671d52aa40eS猫头猫            return result;
672d52aa40eS猫头猫        } catch (e: any) {
673d52aa40eS猫头猫            devLog('error', '获取榜单失败', e, e?.message);
674d52aa40eS猫头猫            return [];
675d52aa40eS猫头猫        }
676d52aa40eS猫头猫    }
677d52aa40eS猫头猫    /** 获取榜单详情 */
678d52aa40eS猫头猫    async getTopListDetail(
67992b6c95aS猫头猫        topListItem: IMusic.IMusicSheetItemBase,
68092b6c95aS猫头猫    ): Promise<ICommon.WithMusicList<IMusic.IMusicSheetItemBase>> {
681d52aa40eS猫头猫        try {
682d52aa40eS猫头猫            const result = await this.plugin.instance?.getTopListDetail?.(
683d52aa40eS猫头猫                topListItem,
684d52aa40eS猫头猫            );
685d52aa40eS猫头猫            if (!result) {
686d52aa40eS猫头猫                throw new Error();
687d52aa40eS猫头猫            }
688d384662fS猫头猫            if (result.musicList) {
689d384662fS猫头猫                result.musicList.forEach(_ =>
690d384662fS猫头猫                    resetMediaItem(_, this.plugin.name),
691d384662fS猫头猫                );
692d384662fS猫头猫            }
693d52aa40eS猫头猫            return result;
694d52aa40eS猫头猫        } catch (e: any) {
695d52aa40eS猫头猫            devLog('error', '获取榜单详情失败', e, e?.message);
696d52aa40eS猫头猫            return {
697d52aa40eS猫头猫                ...topListItem,
698d52aa40eS猫头猫                musicList: [],
699d52aa40eS猫头猫            };
700d52aa40eS猫头猫        }
701d52aa40eS猫头猫    }
702ceb900cdS猫头猫
7035830c002S猫头猫    /** 获取推荐歌单的tag */
704ceb900cdS猫头猫    async getRecommendSheetTags(): Promise<IPlugin.IGetRecommendSheetTagsResult> {
705ceb900cdS猫头猫        try {
706ceb900cdS猫头猫            const result =
707ceb900cdS猫头猫                await this.plugin.instance?.getRecommendSheetTags?.();
708ceb900cdS猫头猫            if (!result) {
709ceb900cdS猫头猫                throw new Error();
710ceb900cdS猫头猫            }
711ceb900cdS猫头猫            return result;
712ceb900cdS猫头猫        } catch (e: any) {
713ceb900cdS猫头猫            devLog('error', '获取推荐歌单失败', e, e?.message);
714ceb900cdS猫头猫            return {
715ceb900cdS猫头猫                data: [],
716ceb900cdS猫头猫            };
717ceb900cdS猫头猫        }
718ceb900cdS猫头猫    }
7195830c002S猫头猫    /** 获取某个tag的推荐歌单 */
720ceb900cdS猫头猫    async getRecommendSheetsByTag(
721ceb900cdS猫头猫        tagItem: ICommon.IUnique,
722ceb900cdS猫头猫        page?: number,
723ceb900cdS猫头猫    ): Promise<ICommon.PaginationResponse<IMusic.IMusicSheetItemBase>> {
724ceb900cdS猫头猫        try {
725ceb900cdS猫头猫            const result =
726ceb900cdS猫头猫                await this.plugin.instance?.getRecommendSheetsByTag?.(
727ceb900cdS猫头猫                    tagItem,
728ceb900cdS猫头猫                    page ?? 1,
729ceb900cdS猫头猫                );
730ceb900cdS猫头猫            if (!result) {
731ceb900cdS猫头猫                throw new Error();
732ceb900cdS猫头猫            }
733ceb900cdS猫头猫            if (result.isEnd !== false) {
734ceb900cdS猫头猫                result.isEnd = true;
735ceb900cdS猫头猫            }
736ceb900cdS猫头猫            if (!result.data) {
737ceb900cdS猫头猫                result.data = [];
738ceb900cdS猫头猫            }
739ceb900cdS猫头猫            result.data.forEach(item => resetMediaItem(item, this.plugin.name));
740ceb900cdS猫头猫
741ceb900cdS猫头猫            return result;
742ceb900cdS猫头猫        } catch (e: any) {
743ceb900cdS猫头猫            devLog('error', '获取推荐歌单详情失败', e, e?.message);
744ceb900cdS猫头猫            return {
745ceb900cdS猫头猫                isEnd: true,
746ceb900cdS猫头猫                data: [],
747ceb900cdS猫头猫            };
748ceb900cdS猫头猫        }
749ceb900cdS猫头猫    }
750927dbe93S猫头猫}
751d5bfeb7eS猫头猫//#endregion
7521a5528a0S猫头猫
753927dbe93S猫头猫let plugins: Array<Plugin> = [];
754927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
75574d0cf81S猫头猫
756d5bfeb7eS猫头猫//#region 本地音乐插件
75774d0cf81S猫头猫/** 本地插件 */
75874d0cf81S猫头猫const localFilePlugin = new Plugin(function () {
7590e4173cdS猫头猫    return {
760d5bfeb7eS猫头猫        platform: localPluginPlatform,
76174d0cf81S猫头猫        _path: '',
76274d0cf81S猫头猫        async getMusicInfo(musicBase) {
76374d0cf81S猫头猫            const localPath = getInternalData<string>(
76474d0cf81S猫头猫                musicBase,
76574d0cf81S猫头猫                InternalDataType.LOCALPATH,
7660e4173cdS猫头猫            );
76774d0cf81S猫头猫            if (localPath) {
76874d0cf81S猫头猫                const coverImg = await Mp3Util.getMediaCoverImg(localPath);
76974d0cf81S猫头猫                return {
77074d0cf81S猫头猫                    artwork: coverImg,
77174d0cf81S猫头猫                };
77274d0cf81S猫头猫            }
77374d0cf81S猫头猫            return null;
77474d0cf81S猫头猫        },
7757993f90eS猫头猫        async getLyric(musicBase) {
7767993f90eS猫头猫            const localPath = getInternalData<string>(
7777993f90eS猫头猫                musicBase,
7787993f90eS猫头猫                InternalDataType.LOCALPATH,
7797993f90eS猫头猫            );
7803a6f67b1S猫头猫            let rawLrc: string | null = null;
7817993f90eS猫头猫            if (localPath) {
7823a6f67b1S猫头猫                // 读取内嵌歌词
7833a6f67b1S猫头猫                try {
7843a6f67b1S猫头猫                    rawLrc = await Mp3Util.getLyric(localPath);
7853a6f67b1S猫头猫                } catch (e) {
786a84a85c5S猫头猫                    console.log('读取内嵌歌词失败', e);
7877993f90eS猫头猫                }
7883a6f67b1S猫头猫                if (!rawLrc) {
7893a6f67b1S猫头猫                    // 读取配置歌词
7903a6f67b1S猫头猫                    const lastDot = localPath.lastIndexOf('.');
7913a6f67b1S猫头猫                    const lrcPath = localPath.slice(0, lastDot) + '.lrc';
7923a6f67b1S猫头猫
7933a6f67b1S猫头猫                    try {
7943a6f67b1S猫头猫                        if (await exists(lrcPath)) {
7953a6f67b1S猫头猫                            rawLrc = await readFile(lrcPath, 'utf8');
7963a6f67b1S猫头猫                        }
7973a6f67b1S猫头猫                    } catch {}
7983a6f67b1S猫头猫                }
7993a6f67b1S猫头猫            }
8003a6f67b1S猫头猫
8013a6f67b1S猫头猫            return rawLrc
8023a6f67b1S猫头猫                ? {
8033a6f67b1S猫头猫                      rawLrc,
8043a6f67b1S猫头猫                  }
8053a6f67b1S猫头猫                : null;
8067993f90eS猫头猫        },
807a84a85c5S猫头猫        async importMusicItem(urlLike) {
808a84a85c5S猫头猫            let meta: any = {};
809a84a85c5S猫头猫            try {
810a84a85c5S猫头猫                meta = await Mp3Util.getBasicMeta(urlLike);
811a84a85c5S猫头猫            } catch {}
812a84a85c5S猫头猫            const id = await FileSystem.hash(urlLike, 'MD5');
813a84a85c5S猫头猫            return {
814a84a85c5S猫头猫                id: id,
815a84a85c5S猫头猫                platform: '本地',
816a84a85c5S猫头猫                title: meta?.title ?? getFileName(urlLike),
817a84a85c5S猫头猫                artist: meta?.artist ?? '未知歌手',
818a84a85c5S猫头猫                duration: parseInt(meta?.duration ?? '0') / 1000,
819a84a85c5S猫头猫                album: meta?.album ?? '未知专辑',
820a84a85c5S猫头猫                artwork: '',
821a84a85c5S猫头猫                [internalSerializeKey]: {
822a84a85c5S猫头猫                    localPath: urlLike,
823a84a85c5S猫头猫                },
824a84a85c5S猫头猫            };
825a84a85c5S猫头猫        },
82674d0cf81S猫头猫    };
82774d0cf81S猫头猫}, '');
8287993f90eS猫头猫localFilePlugin.hash = localPluginHash;
829927dbe93S猫头猫
830d5bfeb7eS猫头猫//#endregion
831d5bfeb7eS猫头猫
832927dbe93S猫头猫async function setup() {
833927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
834927dbe93S猫头猫    try {
835927dbe93S猫头猫        // 加载插件
836927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
837927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
838927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
8391e263108S猫头猫            trace('初始化插件', _pluginUrl);
8401e263108S猫头猫            if (
8411e263108S猫头猫                _pluginUrl.isFile() &&
8421e263108S猫头猫                (_pluginUrl.name?.endsWith?.('.js') ||
8431e263108S猫头猫                    _pluginUrl.path?.endsWith?.('.js'))
8441e263108S猫头猫            ) {
845927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
846927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
8474060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
8484060c00aS猫头猫                    p => p.hash === plugin.hash,
8494060c00aS猫头猫                );
850927dbe93S猫头猫                if (_pluginIndex !== -1) {
851927dbe93S猫头猫                    // 重复插件,直接忽略
8520c266394S猫头猫                    continue;
853927dbe93S猫头猫                }
854927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
855927dbe93S猫头猫            }
856927dbe93S猫头猫        }
857927dbe93S猫头猫
858927dbe93S猫头猫        plugins = _plugins;
859e08d37a3S猫头猫        /** 初始化meta信息 */
860c2b3a262S猫头猫        await PluginMeta.setupMeta(plugins.map(_ => _.name));
861c2b3a262S猫头猫        /** 查看一下是否有禁用的标记 */
862c2b3a262S猫头猫        const allMeta = PluginMeta.getPluginMetaAll() ?? {};
863c2b3a262S猫头猫        for (let plugin of plugins) {
864c2b3a262S猫头猫            if (allMeta[plugin.name]?.enabled === false) {
865c2b3a262S猫头猫                plugin.state = 'disabled';
866c2b3a262S猫头猫            }
867c2b3a262S猫头猫        }
868c2b3a262S猫头猫        pluginStateMapper.notify();
869927dbe93S猫头猫    } catch (e: any) {
8704060c00aS猫头猫        ToastAndroid.show(
8714060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
8724060c00aS猫头猫            ToastAndroid.LONG,
8734060c00aS猫头猫        );
8741a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
875927dbe93S猫头猫        throw e;
876927dbe93S猫头猫    }
877927dbe93S猫头猫}
878927dbe93S猫头猫
879*e36e2599S猫头猫interface IInstallPluginConfig {
880*e36e2599S猫头猫    notCheckVersion?: boolean;
881*e36e2599S猫头猫}
882*e36e2599S猫头猫
883927dbe93S猫头猫// 安装插件
884*e36e2599S猫头猫async function installPlugin(
885*e36e2599S猫头猫    pluginPath: string,
886*e36e2599S猫头猫    config?: IInstallPluginConfig,
887*e36e2599S猫头猫) {
88822c09412S猫头猫    // if (pluginPath.endsWith('.js')) {
889927dbe93S猫头猫    const funcCode = await readFile(pluginPath, 'utf8');
890*e36e2599S猫头猫
891*e36e2599S猫头猫    if (funcCode) {
892927dbe93S猫头猫        const plugin = new Plugin(funcCode, pluginPath);
893927dbe93S猫头猫        const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
894927dbe93S猫头猫        if (_pluginIndex !== -1) {
895*e36e2599S猫头猫            // 静默忽略
896*e36e2599S猫头猫            return plugin;
897927dbe93S猫头猫        }
898*e36e2599S猫头猫        const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
899*e36e2599S猫头猫        if (oldVersionPlugin && !config?.notCheckVersion) {
900*e36e2599S猫头猫            if (
901*e36e2599S猫头猫                compare(
902*e36e2599S猫头猫                    oldVersionPlugin.instance.version ?? '',
903*e36e2599S猫头猫                    plugin.instance.version ?? '',
904*e36e2599S猫头猫                    '>',
905*e36e2599S猫头猫                )
906*e36e2599S猫头猫            ) {
907*e36e2599S猫头猫                throw new Error('已安装更新版本的插件');
908*e36e2599S猫头猫            }
909*e36e2599S猫头猫        }
910*e36e2599S猫头猫
911927dbe93S猫头猫        if (plugin.hash !== '') {
912927dbe93S猫头猫            const fn = nanoid();
913*e36e2599S猫头猫            if (oldVersionPlugin) {
914*e36e2599S猫头猫                plugins = plugins.filter(_ => _.hash !== oldVersionPlugin.hash);
915*e36e2599S猫头猫                try {
916*e36e2599S猫头猫                    await unlink(oldVersionPlugin.path);
917*e36e2599S猫头猫                } catch {}
918*e36e2599S猫头猫            }
919927dbe93S猫头猫            const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
920927dbe93S猫头猫            await copyFile(pluginPath, _pluginPath);
921927dbe93S猫头猫            plugin.path = _pluginPath;
922927dbe93S猫头猫            plugins = plugins.concat(plugin);
923927dbe93S猫头猫            pluginStateMapper.notify();
924a84a85c5S猫头猫            return plugin;
925927dbe93S猫头猫        }
926*e36e2599S猫头猫        throw new Error('插件无法解析!');
927927dbe93S猫头猫    }
928*e36e2599S猫头猫    throw new Error('插件无法识别!');
929c2b3a262S猫头猫}
930c2b3a262S猫头猫
931c2b3a262S猫头猫async function installPluginFromUrl(
932c2b3a262S猫头猫    url: string,
933c2b3a262S猫头猫    config?: IInstallPluginConfig,
934c2b3a262S猫头猫) {
93558992c6bS猫头猫    try {
93658992c6bS猫头猫        const funcCode = (await axios.get(url)).data;
93758992c6bS猫头猫        if (funcCode) {
93858992c6bS猫头猫            const plugin = new Plugin(funcCode, '');
93958992c6bS猫头猫            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
94058992c6bS猫头猫            if (_pluginIndex !== -1) {
9418b7ddca8S猫头猫                // 静默忽略
9428b7ddca8S猫头猫                return;
94358992c6bS猫头猫            }
94425c1bd29S猫头猫            const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
945c2b3a262S猫头猫            if (oldVersionPlugin && !config?.notCheckVersion) {
94625c1bd29S猫头猫                if (
94725c1bd29S猫头猫                    compare(
94825c1bd29S猫头猫                        oldVersionPlugin.instance.version ?? '',
94925c1bd29S猫头猫                        plugin.instance.version ?? '',
95025c1bd29S猫头猫                        '>',
95125c1bd29S猫头猫                    )
95225c1bd29S猫头猫                ) {
95325c1bd29S猫头猫                    throw new Error('已安装更新版本的插件');
95425c1bd29S猫头猫                }
95525c1bd29S猫头猫            }
95625c1bd29S猫头猫
95758992c6bS猫头猫            if (plugin.hash !== '') {
95858992c6bS猫头猫                const fn = nanoid();
95958992c6bS猫头猫                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
96058992c6bS猫头猫                await writeFile(_pluginPath, funcCode, 'utf8');
96158992c6bS猫头猫                plugin.path = _pluginPath;
96258992c6bS猫头猫                plugins = plugins.concat(plugin);
96325c1bd29S猫头猫                if (oldVersionPlugin) {
96425c1bd29S猫头猫                    plugins = plugins.filter(
96525c1bd29S猫头猫                        _ => _.hash !== oldVersionPlugin.hash,
96625c1bd29S猫头猫                    );
96725c1bd29S猫头猫                    try {
96825c1bd29S猫头猫                        await unlink(oldVersionPlugin.path);
96925c1bd29S猫头猫                    } catch {}
97025c1bd29S猫头猫                }
97158992c6bS猫头猫                pluginStateMapper.notify();
97258992c6bS猫头猫                return;
97358992c6bS猫头猫            }
97474acbfc0S猫头猫            throw new Error('插件无法解析!');
97558992c6bS猫头猫        }
97625c1bd29S猫头猫    } catch (e: any) {
977ea6d708fS猫头猫        devLog('error', 'URL安装插件失败', e, e?.message);
97858992c6bS猫头猫        errorLog('URL安装插件失败', e);
97925c1bd29S猫头猫        throw new Error(e?.message ?? '');
98058992c6bS猫头猫    }
98158992c6bS猫头猫}
98258992c6bS猫头猫
983927dbe93S猫头猫/** 卸载插件 */
984927dbe93S猫头猫async function uninstallPlugin(hash: string) {
985927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
986927dbe93S猫头猫    if (targetIndex !== -1) {
987927dbe93S猫头猫        try {
98824e5e74aS猫头猫            const pluginName = plugins[targetIndex].name;
989927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
990927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
991927dbe93S猫头猫            pluginStateMapper.notify();
99224e5e74aS猫头猫            if (plugins.every(_ => _.name !== pluginName)) {
99324e5e74aS猫头猫                await MediaMeta.removePlugin(pluginName);
99424e5e74aS猫头猫            }
995927dbe93S猫头猫        } catch {}
996927dbe93S猫头猫    }
997927dbe93S猫头猫}
998927dbe93S猫头猫
99908882a77S猫头猫async function uninstallAllPlugins() {
100008882a77S猫头猫    await Promise.all(
100108882a77S猫头猫        plugins.map(async plugin => {
100208882a77S猫头猫            try {
100308882a77S猫头猫                const pluginName = plugin.name;
100408882a77S猫头猫                await unlink(plugin.path);
100508882a77S猫头猫                await MediaMeta.removePlugin(pluginName);
100608882a77S猫头猫            } catch (e) {}
100708882a77S猫头猫        }),
100808882a77S猫头猫    );
100908882a77S猫头猫    plugins = [];
101008882a77S猫头猫    pluginStateMapper.notify();
1011e08d37a3S猫头猫
1012e08d37a3S猫头猫    /** 清除空余文件,异步做就可以了 */
1013e08d37a3S猫头猫    readDir(pathConst.pluginPath)
1014e08d37a3S猫头猫        .then(fns => {
1015e08d37a3S猫头猫            fns.forEach(fn => {
1016e08d37a3S猫头猫                unlink(fn.path).catch(emptyFunction);
1017e08d37a3S猫头猫            });
1018e08d37a3S猫头猫        })
1019e08d37a3S猫头猫        .catch(emptyFunction);
102008882a77S猫头猫}
102108882a77S猫头猫
102225c1bd29S猫头猫async function updatePlugin(plugin: Plugin) {
102325c1bd29S猫头猫    const updateUrl = plugin.instance.srcUrl;
102425c1bd29S猫头猫    if (!updateUrl) {
102525c1bd29S猫头猫        throw new Error('没有更新源');
102625c1bd29S猫头猫    }
102725c1bd29S猫头猫    try {
102825c1bd29S猫头猫        await installPluginFromUrl(updateUrl);
102925c1bd29S猫头猫    } catch (e: any) {
103025c1bd29S猫头猫        if (e.message === '插件已安装') {
103125c1bd29S猫头猫            throw new Error('当前已是最新版本');
103225c1bd29S猫头猫        } else {
103325c1bd29S猫头猫            throw e;
103425c1bd29S猫头猫        }
103525c1bd29S猫头猫    }
103625c1bd29S猫头猫}
103725c1bd29S猫头猫
1038927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
10392c595535S猫头猫    return getByName(mediaItem?.platform);
1040927dbe93S猫头猫}
1041927dbe93S猫头猫
1042927dbe93S猫头猫function getByHash(hash: string) {
10437993f90eS猫头猫    return hash === localPluginHash
10447993f90eS猫头猫        ? localFilePlugin
10457993f90eS猫头猫        : plugins.find(_ => _.hash === hash);
1046927dbe93S猫头猫}
1047927dbe93S猫头猫
1048927dbe93S猫头猫function getByName(name: string) {
10497993f90eS猫头猫    return name === localPluginPlatform
10500e4173cdS猫头猫        ? localFilePlugin
10510e4173cdS猫头猫        : plugins.find(_ => _.name === name);
1052927dbe93S猫头猫}
1053927dbe93S猫头猫
1054927dbe93S猫头猫function getValidPlugins() {
1055927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
1056927dbe93S猫头猫}
1057927dbe93S猫头猫
10582b80a429S猫头猫function getSearchablePlugins(supportedSearchType?: ICommon.SupportMediaType) {
10592b80a429S猫头猫    return plugins.filter(
10602b80a429S猫头猫        _ =>
10612b80a429S猫头猫            _.state === 'enabled' &&
10622b80a429S猫头猫            _.instance.search &&
106339ac60f7S猫头猫            (supportedSearchType && _.instance.supportedSearchType
106439ac60f7S猫头猫                ? _.instance.supportedSearchType.includes(supportedSearchType)
10652b80a429S猫头猫                : true),
10662b80a429S猫头猫    );
1067efb9da24S猫头猫}
1068efb9da24S猫头猫
10692b80a429S猫头猫function getSortedSearchablePlugins(
10702b80a429S猫头猫    supportedSearchType?: ICommon.SupportMediaType,
10712b80a429S猫头猫) {
10722b80a429S猫头猫    return getSearchablePlugins(supportedSearchType).sort((a, b) =>
1073e08d37a3S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
1074e08d37a3S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
1075e08d37a3S猫头猫        0
1076e08d37a3S猫头猫            ? -1
1077e08d37a3S猫头猫            : 1,
1078e08d37a3S猫头猫    );
1079e08d37a3S猫头猫}
1080e08d37a3S猫头猫
108115feccc1S猫头猫function getTopListsablePlugins() {
108215feccc1S猫头猫    return plugins.filter(_ => _.state === 'enabled' && _.instance.getTopLists);
108315feccc1S猫头猫}
108415feccc1S猫头猫
108515feccc1S猫头猫function getSortedTopListsablePlugins() {
108615feccc1S猫头猫    return getTopListsablePlugins().sort((a, b) =>
108715feccc1S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
108815feccc1S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
108915feccc1S猫头猫        0
109015feccc1S猫头猫            ? -1
109115feccc1S猫头猫            : 1,
109215feccc1S猫头猫    );
109315feccc1S猫头猫}
109415feccc1S猫头猫
1095ceb900cdS猫头猫function getRecommendSheetablePlugins() {
1096ceb900cdS猫头猫    return plugins.filter(
1097ceb900cdS猫头猫        _ => _.state === 'enabled' && _.instance.getRecommendSheetsByTag,
1098ceb900cdS猫头猫    );
1099ceb900cdS猫头猫}
1100ceb900cdS猫头猫
1101ceb900cdS猫头猫function getSortedRecommendSheetablePlugins() {
1102ceb900cdS猫头猫    return getRecommendSheetablePlugins().sort((a, b) =>
1103ceb900cdS猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
1104ceb900cdS猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
1105ceb900cdS猫头猫        0
1106ceb900cdS猫头猫            ? -1
1107ceb900cdS猫头猫            : 1,
1108ceb900cdS猫头猫    );
1109ceb900cdS猫头猫}
1110ceb900cdS猫头猫
1111e08d37a3S猫头猫function useSortedPlugins() {
1112e08d37a3S猫头猫    const _plugins = pluginStateMapper.useMappedState();
1113e08d37a3S猫头猫    const _pluginMetaAll = PluginMeta.usePluginMetaAll();
1114e08d37a3S猫头猫
111534588741S猫头猫    const [sortedPlugins, setSortedPlugins] = useState(
111634588741S猫头猫        [..._plugins].sort((a, b) =>
1117e08d37a3S猫头猫            (_pluginMetaAll[a.name]?.order ?? Infinity) -
1118e08d37a3S猫头猫                (_pluginMetaAll[b.name]?.order ?? Infinity) <
1119e08d37a3S猫头猫            0
1120e08d37a3S猫头猫                ? -1
1121e08d37a3S猫头猫                : 1,
112234588741S猫头猫        ),
1123e08d37a3S猫头猫    );
112434588741S猫头猫
112534588741S猫头猫    useEffect(() => {
1126d4cd40d8S猫头猫        InteractionManager.runAfterInteractions(() => {
112734588741S猫头猫            setSortedPlugins(
112834588741S猫头猫                [..._plugins].sort((a, b) =>
112934588741S猫头猫                    (_pluginMetaAll[a.name]?.order ?? Infinity) -
113034588741S猫头猫                        (_pluginMetaAll[b.name]?.order ?? Infinity) <
113134588741S猫头猫                    0
113234588741S猫头猫                        ? -1
113334588741S猫头猫                        : 1,
113434588741S猫头猫                ),
113534588741S猫头猫            );
1136d4cd40d8S猫头猫        });
113734588741S猫头猫    }, [_plugins, _pluginMetaAll]);
113834588741S猫头猫
113934588741S猫头猫    return sortedPlugins;
1140e08d37a3S猫头猫}
1141e08d37a3S猫头猫
1142c2b3a262S猫头猫async function setPluginEnabled(plugin: Plugin, enabled?: boolean) {
1143c2b3a262S猫头猫    const target = plugins.find(it => it.hash === plugin.hash);
1144c2b3a262S猫头猫    if (target) {
1145c2b3a262S猫头猫        target.state = enabled ? 'enabled' : 'disabled';
1146c2b3a262S猫头猫        plugins = [...plugins];
1147c2b3a262S猫头猫        pluginStateMapper.notify();
1148c2b3a262S猫头猫        PluginMeta.setPluginMetaProp(plugin, 'enabled', enabled);
1149c2b3a262S猫头猫    }
1150c2b3a262S猫头猫}
1151c2b3a262S猫头猫
1152927dbe93S猫头猫const PluginManager = {
1153927dbe93S猫头猫    setup,
1154927dbe93S猫头猫    installPlugin,
115558992c6bS猫头猫    installPluginFromUrl,
115625c1bd29S猫头猫    updatePlugin,
1157927dbe93S猫头猫    uninstallPlugin,
1158927dbe93S猫头猫    getByMedia,
1159927dbe93S猫头猫    getByHash,
1160927dbe93S猫头猫    getByName,
1161927dbe93S猫头猫    getValidPlugins,
1162efb9da24S猫头猫    getSearchablePlugins,
1163e08d37a3S猫头猫    getSortedSearchablePlugins,
116415feccc1S猫头猫    getTopListsablePlugins,
1165ceb900cdS猫头猫    getSortedRecommendSheetablePlugins,
116615feccc1S猫头猫    getSortedTopListsablePlugins,
11675276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
1168e08d37a3S猫头猫    useSortedPlugins,
116908882a77S猫头猫    uninstallAllPlugins,
1170c2b3a262S猫头猫    setPluginEnabled,
11715276aef9S猫头猫};
1172927dbe93S猫头猫
1173927dbe93S猫头猫export default PluginManager;
1174