xref: /MusicFree/src/core/pluginManager.ts (revision 95297592953d9ab84253eeb05f1d58e2c70e7c95)
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*95297592S猫头猫            if (Array.isArray(_instance.userVariables)) {
153*95297592S猫头猫                _instance.userVariables = _instance.userVariables.filter(
154*95297592S猫头猫                    it => it?.key,
155*95297592S猫头猫                );
156*95297592S猫头猫            }
157927dbe93S猫头猫            this.checkValid(_instance);
158927dbe93S猫头猫        } catch (e: any) {
159b43683eaS猫头猫            console.log(e);
160927dbe93S猫头猫            this.state = 'error';
161927dbe93S猫头猫            this.stateCode = PluginStateCode.CannotParse;
162927dbe93S猫头猫            if (e?.stateCode) {
163927dbe93S猫头猫                this.stateCode = e.stateCode;
164927dbe93S猫头猫            }
165927dbe93S猫头猫            errorLog(`${pluginPath}插件无法解析 `, {
166927dbe93S猫头猫                stateCode: this.stateCode,
167927dbe93S猫头猫                message: e?.message,
168927dbe93S猫头猫                stack: e?.stack,
169927dbe93S猫头猫            });
170927dbe93S猫头猫            _instance = e?.instance ?? {
171927dbe93S猫头猫                _path: '',
172927dbe93S猫头猫                platform: '',
173927dbe93S猫头猫                appVersion: '',
17420e6a092S猫头猫                async getMediaSource() {
175927dbe93S猫头猫                    return null;
176927dbe93S猫头猫                },
177927dbe93S猫头猫                async search() {
178927dbe93S猫头猫                    return {};
179927dbe93S猫头猫                },
180927dbe93S猫头猫                async getAlbumInfo() {
181927dbe93S猫头猫                    return null;
182927dbe93S猫头猫                },
183927dbe93S猫头猫            };
184927dbe93S猫头猫        }
185927dbe93S猫头猫        this.instance = _instance;
186927dbe93S猫头猫        this.path = pluginPath;
187927dbe93S猫头猫        this.name = _instance.platform;
188ab8941d9S猫头猫        if (
189ab8941d9S猫头猫            this.instance.platform === '' ||
190ab8941d9S猫头猫            this.instance.platform === undefined
191ab8941d9S猫头猫        ) {
192927dbe93S猫头猫            this.hash = '';
193927dbe93S猫头猫        } else {
19474d0cf81S猫头猫            if (typeof funcCode === 'string') {
195927dbe93S猫头猫                this.hash = sha256(funcCode).toString();
19674d0cf81S猫头猫            } else {
19774d0cf81S猫头猫                this.hash = sha256(funcCode.toString()).toString();
19874d0cf81S猫头猫            }
199927dbe93S猫头猫        }
200927dbe93S猫头猫
201927dbe93S猫头猫        // 放在最后
202927dbe93S猫头猫        this.methods = new PluginMethods(this);
203927dbe93S猫头猫    }
204927dbe93S猫头猫
205927dbe93S猫头猫    private checkValid(_instance: IPlugin.IPluginInstance) {
206927dbe93S猫头猫        /** 版本号校验 */
207927dbe93S猫头猫        if (
208927dbe93S猫头猫            _instance.appVersion &&
209927dbe93S猫头猫            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
210927dbe93S猫头猫        ) {
211927dbe93S猫头猫            throw {
212927dbe93S猫头猫                instance: _instance,
213927dbe93S猫头猫                stateCode: PluginStateCode.VersionNotMatch,
214927dbe93S猫头猫            };
215927dbe93S猫头猫        }
216927dbe93S猫头猫        return true;
217927dbe93S猫头猫    }
218927dbe93S猫头猫}
219d5bfeb7eS猫头猫//#endregion
220927dbe93S猫头猫
221d5bfeb7eS猫头猫//#region 基于插件类封装的方法,供给APP侧直接调用
222927dbe93S猫头猫/** 有缓存等信息 */
223927dbe93S猫头猫class PluginMethods implements IPlugin.IPluginInstanceMethods {
224927dbe93S猫头猫    private plugin;
225927dbe93S猫头猫    constructor(plugin: Plugin) {
226927dbe93S猫头猫        this.plugin = plugin;
227927dbe93S猫头猫    }
228927dbe93S猫头猫    /** 搜索 */
229927dbe93S猫头猫    async search<T extends ICommon.SupportMediaType>(
230927dbe93S猫头猫        query: string,
231927dbe93S猫头猫        page: number,
232927dbe93S猫头猫        type: T,
233927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
234927dbe93S猫头猫        if (!this.plugin.instance.search) {
235927dbe93S猫头猫            return {
236927dbe93S猫头猫                isEnd: true,
237927dbe93S猫头猫                data: [],
238927dbe93S猫头猫            };
239927dbe93S猫头猫        }
240927dbe93S猫头猫
2414060c00aS猫头猫        const result =
2424060c00aS猫头猫            (await this.plugin.instance.search(query, page, type)) ?? {};
243927dbe93S猫头猫        if (Array.isArray(result.data)) {
244927dbe93S猫头猫            result.data.forEach(_ => {
245927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
246927dbe93S猫头猫            });
247927dbe93S猫头猫            return {
248927dbe93S猫头猫                isEnd: result.isEnd ?? true,
249927dbe93S猫头猫                data: result.data,
250927dbe93S猫头猫            };
251927dbe93S猫头猫        }
252927dbe93S猫头猫        return {
253927dbe93S猫头猫            isEnd: true,
254927dbe93S猫头猫            data: [],
255927dbe93S猫头猫        };
256927dbe93S猫头猫    }
257927dbe93S猫头猫
258927dbe93S猫头猫    /** 获取真实源 */
25920e6a092S猫头猫    async getMediaSource(
260927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
261abaede57S猫头猫        quality: IMusic.IQualityKey = 'standard',
262927dbe93S猫头猫        retryCount = 1,
263dc160d50S猫头猫        notUpdateCache = false,
264192ae2b0S猫头猫    ): Promise<IPlugin.IMediaSourceResult | null> {
265927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
266927dbe93S猫头猫        const localPath =
2670e4173cdS猫头猫            getInternalData<string>(musicItem, InternalDataType.LOCALPATH) ??
2680e4173cdS猫头猫            getInternalData<string>(
2690e4173cdS猫头猫                LocalMusicSheet.isLocalMusic(musicItem),
2700e4173cdS猫头猫                InternalDataType.LOCALPATH,
2710e4173cdS猫头猫            );
272a84a85c5S猫头猫        if (
273a84a85c5S猫头猫            localPath &&
274a84a85c5S猫头猫            (localPath.startsWith('content://') ||
275a84a85c5S猫头猫                (await FileSystem.exists(localPath)))
276a84a85c5S猫头猫        ) {
2770e4173cdS猫头猫            trace('本地播放', localPath);
278927dbe93S猫头猫            return {
279927dbe93S猫头猫                url: localPath,
280927dbe93S猫头猫            };
281927dbe93S猫头猫        }
282a84a85c5S猫头猫        console.log('BFFF2');
283a84a85c5S猫头猫
2847993f90eS猫头猫        if (musicItem.platform === localPluginPlatform) {
285f5935920S猫头猫            throw new Error('本地音乐不存在');
286f5935920S猫头猫        }
287927dbe93S猫头猫        // 2. 缓存播放
288927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
289985f8e75S猫头猫        const pluginCacheControl =
290985f8e75S猫头猫            this.plugin.instance.cacheControl ?? 'no-cache';
291cfa0fc07S猫头猫        if (
292cfa0fc07S猫头猫            mediaCache &&
293abaede57S猫头猫            mediaCache?.qualities?.[quality]?.url &&
29448f4b873S猫头猫            (pluginCacheControl === CacheControl.Cache ||
29548f4b873S猫头猫                (pluginCacheControl === CacheControl.NoCache &&
296ef714860S猫头猫                    Network.isOffline()))
297cfa0fc07S猫头猫        ) {
2985276aef9S猫头猫            trace('播放', '缓存播放');
299abaede57S猫头猫            const qualityInfo = mediaCache.qualities[quality];
300927dbe93S猫头猫            return {
301abaede57S猫头猫                url: qualityInfo.url,
302927dbe93S猫头猫                headers: mediaCache.headers,
3034060c00aS猫头猫                userAgent:
3044060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
305927dbe93S猫头猫            };
306927dbe93S猫头猫        }
307927dbe93S猫头猫        // 3. 插件解析
30820e6a092S猫头猫        if (!this.plugin.instance.getMediaSource) {
309abaede57S猫头猫            return {url: musicItem?.qualities?.[quality]?.url ?? musicItem.url};
310927dbe93S猫头猫        }
311927dbe93S猫头猫        try {
312abaede57S猫头猫            const {url, headers} = (await this.plugin.instance.getMediaSource(
313abaede57S猫头猫                musicItem,
314abaede57S猫头猫                quality,
315abaede57S猫头猫            )) ?? {url: musicItem?.qualities?.[quality]?.url};
316927dbe93S猫头猫            if (!url) {
317a28eac61S猫头猫                throw new Error('NOT RETRY');
318927dbe93S猫头猫            }
3195276aef9S猫头猫            trace('播放', '插件播放');
320927dbe93S猫头猫            const result = {
321927dbe93S猫头猫                url,
322927dbe93S猫头猫                headers,
323927dbe93S猫头猫                userAgent: headers?.['user-agent'],
324cfa0fc07S猫头猫            } as IPlugin.IMediaSourceResult;
325927dbe93S猫头猫
326dc160d50S猫头猫            if (
327dc160d50S猫头猫                pluginCacheControl !== CacheControl.NoStore &&
328dc160d50S猫头猫                !notUpdateCache
329dc160d50S猫头猫            ) {
330abaede57S猫头猫                Cache.update(musicItem, [
331abaede57S猫头猫                    ['headers', result.headers],
332abaede57S猫头猫                    ['userAgent', result.userAgent],
333abaede57S猫头猫                    [`qualities.${quality}.url`, url],
334abaede57S猫头猫                ]);
335752ffc5aS猫头猫            }
336cfa0fc07S猫头猫
337927dbe93S猫头猫            return result;
338927dbe93S猫头猫        } catch (e: any) {
339a28eac61S猫头猫            if (retryCount > 0 && e?.message !== 'NOT RETRY') {
340927dbe93S猫头猫                await delay(150);
341abaede57S猫头猫                return this.getMediaSource(musicItem, quality, --retryCount);
342927dbe93S猫头猫            }
343927dbe93S猫头猫            errorLog('获取真实源失败', e?.message);
344ea6d708fS猫头猫            devLog('error', '获取真实源失败', e, e?.message);
345192ae2b0S猫头猫            return null;
346927dbe93S猫头猫        }
347927dbe93S猫头猫    }
348927dbe93S猫头猫
349927dbe93S猫头猫    /** 获取音乐详情 */
350927dbe93S猫头猫    async getMusicInfo(
351927dbe93S猫头猫        musicItem: ICommon.IMediaBase,
35274d0cf81S猫头猫    ): Promise<Partial<IMusic.IMusicItem> | null> {
353927dbe93S猫头猫        if (!this.plugin.instance.getMusicInfo) {
354d704daedS猫头猫            return null;
355927dbe93S猫头猫        }
35674d0cf81S猫头猫        try {
357927dbe93S猫头猫            return (
358927dbe93S猫头猫                this.plugin.instance.getMusicInfo(
3597993f90eS猫头猫                    resetMediaItem(musicItem, undefined, true),
360d704daedS猫头猫                ) ?? null
361927dbe93S猫头猫            );
362ea6d708fS猫头猫        } catch (e: any) {
363ea6d708fS猫头猫            devLog('error', '获取音乐详情失败', e, e?.message);
364d704daedS猫头猫            return null;
36574d0cf81S猫头猫        }
366927dbe93S猫头猫    }
367927dbe93S猫头猫
368927dbe93S猫头猫    /** 获取歌词 */
369927dbe93S猫头猫    async getLyric(
370927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
371927dbe93S猫头猫        from?: IMusic.IMusicItemBase,
372927dbe93S猫头猫    ): Promise<ILyric.ILyricSource | null> {
373927dbe93S猫头猫        // 1.额外存储的meta信息
374927dbe93S猫头猫        const meta = MediaMeta.get(musicItem);
375927dbe93S猫头猫        if (meta && meta.associatedLrc) {
376927dbe93S猫头猫            // 有关联歌词
377927dbe93S猫头猫            if (
378927dbe93S猫头猫                isSameMediaItem(musicItem, from) ||
379927dbe93S猫头猫                isSameMediaItem(meta.associatedLrc, musicItem)
380927dbe93S猫头猫            ) {
381927dbe93S猫头猫                // 形成环路,断开当前的环
382927dbe93S猫头猫                await MediaMeta.update(musicItem, {
383927dbe93S猫头猫                    associatedLrc: undefined,
384927dbe93S猫头猫                });
385927dbe93S猫头猫                // 无歌词
386927dbe93S猫头猫                return null;
387927dbe93S猫头猫            }
388927dbe93S猫头猫            // 获取关联歌词
3897a91f04fS猫头猫            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
3904060c00aS猫头猫            const result = await this.getLyric(
3917a91f04fS猫头猫                {...meta.associatedLrc, ...associatedMeta},
3924060c00aS猫头猫                from ?? musicItem,
3934060c00aS猫头猫            );
394927dbe93S猫头猫            if (result) {
395927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
396927dbe93S猫头猫                return result;
397927dbe93S猫头猫            }
398927dbe93S猫头猫        }
399927dbe93S猫头猫        const cache = Cache.get(musicItem);
400927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
401927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
402927dbe93S猫头猫        // 如果存在文本
403927dbe93S猫头猫        if (rawLrc) {
404927dbe93S猫头猫            return {
405927dbe93S猫头猫                rawLrc,
406927dbe93S猫头猫                lrc: lrcUrl,
407927dbe93S猫头猫            };
408927dbe93S猫头猫        }
409927dbe93S猫头猫        // 2.本地缓存
410927dbe93S猫头猫        const localLrc =
4110e4173cdS猫头猫            meta?.[internalSerializeKey]?.local?.localLrc ||
4120e4173cdS猫头猫            cache?.[internalSerializeKey]?.local?.localLrc;
413927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
414927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
415927dbe93S猫头猫            return {
416927dbe93S猫头猫                rawLrc,
417927dbe93S猫头猫                lrc: lrcUrl,
418927dbe93S猫头猫            };
419927dbe93S猫头猫        }
420927dbe93S猫头猫        // 3.优先使用url
421927dbe93S猫头猫        if (lrcUrl) {
422927dbe93S猫头猫            try {
423927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
42461aca335S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 2000})).data;
425927dbe93S猫头猫                return {
426927dbe93S猫头猫                    rawLrc,
427927dbe93S猫头猫                    lrc: lrcUrl,
428927dbe93S猫头猫                };
429927dbe93S猫头猫            } catch {
430927dbe93S猫头猫                lrcUrl = undefined;
431927dbe93S猫头猫            }
432927dbe93S猫头猫        }
433927dbe93S猫头猫        // 4. 如果地址失效
434927dbe93S猫头猫        if (!lrcUrl) {
435927dbe93S猫头猫            // 插件获得url
436927dbe93S猫头猫            try {
4377a91f04fS猫头猫                let lrcSource;
4387a91f04fS猫头猫                if (from) {
4397a91f04fS猫头猫                    lrcSource = await PluginManager.getByMedia(
4407a91f04fS猫头猫                        musicItem,
4417a91f04fS猫头猫                    )?.instance?.getLyric?.(
442927dbe93S猫头猫                        resetMediaItem(musicItem, undefined, true),
443927dbe93S猫头猫                    );
4447a91f04fS猫头猫                } else {
4457a91f04fS猫头猫                    lrcSource = await this.plugin.instance?.getLyric?.(
4467a91f04fS猫头猫                        resetMediaItem(musicItem, undefined, true),
4477a91f04fS猫头猫                    );
4487a91f04fS猫头猫                }
4497a91f04fS猫头猫
450927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
451927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
452927dbe93S猫头猫            } catch (e: any) {
453927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
454ea6d708fS猫头猫                devLog('error', '插件获取歌词失败', e, e?.message);
455927dbe93S猫头猫            }
456927dbe93S猫头猫        }
457927dbe93S猫头猫        // 5. 最后一次请求
458927dbe93S猫头猫        if (rawLrc || lrcUrl) {
459927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
460927dbe93S猫头猫            if (lrcUrl) {
461927dbe93S猫头猫                try {
46261aca335S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 2000})).data;
463927dbe93S猫头猫                } catch {}
464927dbe93S猫头猫            }
465927dbe93S猫头猫            if (rawLrc) {
466927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
467927dbe93S猫头猫                // 写入缓存
468927dbe93S猫头猫                Cache.update(musicItem, [
4690e4173cdS猫头猫                    [`${internalSerializeKey}.local.localLrc`, filename],
470927dbe93S猫头猫                ]);
471927dbe93S猫头猫                // 如果有meta
472927dbe93S猫头猫                if (meta) {
473927dbe93S猫头猫                    MediaMeta.update(musicItem, [
4740e4173cdS猫头猫                        [`${internalSerializeKey}.local.localLrc`, filename],
475927dbe93S猫头猫                    ]);
476927dbe93S猫头猫                }
477927dbe93S猫头猫                return {
478927dbe93S猫头猫                    rawLrc,
479927dbe93S猫头猫                    lrc: lrcUrl,
480927dbe93S猫头猫                };
481927dbe93S猫头猫            }
482927dbe93S猫头猫        }
4833a6f67b1S猫头猫        // 6. 如果是本地文件
4843a6f67b1S猫头猫        const isDownloaded = LocalMusicSheet.isLocalMusic(musicItem);
4853a6f67b1S猫头猫        if (musicItem.platform !== localPluginPlatform && isDownloaded) {
4863a6f67b1S猫头猫            const res = await localFilePlugin.instance!.getLyric!(isDownloaded);
4873a6f67b1S猫头猫            if (res) {
4883a6f67b1S猫头猫                return res;
4893a6f67b1S猫头猫            }
4903a6f67b1S猫头猫        }
491ea6d708fS猫头猫        devLog('warn', '无歌词');
492927dbe93S猫头猫
493927dbe93S猫头猫        return null;
494927dbe93S猫头猫    }
495927dbe93S猫头猫
496927dbe93S猫头猫    /** 获取歌词文本 */
497927dbe93S猫头猫    async getLyricText(
498927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
499927dbe93S猫头猫    ): Promise<string | undefined> {
500927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
501927dbe93S猫头猫    }
502927dbe93S猫头猫
503927dbe93S猫头猫    /** 获取专辑信息 */
504927dbe93S猫头猫    async getAlbumInfo(
505927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
506f9afcc0dS猫头猫        page: number = 1,
507f9afcc0dS猫头猫    ): Promise<IPlugin.IAlbumInfoResult | null> {
508927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
509f9afcc0dS猫头猫            return {
510f9afcc0dS猫头猫                albumItem,
511f9afcc0dS猫头猫                musicList: albumItem?.musicList ?? [],
512f9afcc0dS猫头猫                isEnd: true,
513f9afcc0dS猫头猫            };
514927dbe93S猫头猫        }
515927dbe93S猫头猫        try {
516927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
517927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
518f9afcc0dS猫头猫                page,
519927dbe93S猫头猫            );
5205276aef9S猫头猫            if (!result) {
5215276aef9S猫头猫                throw new Error();
5225276aef9S猫头猫            }
523927dbe93S猫头猫            result?.musicList?.forEach(_ => {
524927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
52596744680S猫头猫                _.album = albumItem.title;
526927dbe93S猫头猫            });
5275276aef9S猫头猫
528f9afcc0dS猫头猫            if (page <= 1) {
529f9afcc0dS猫头猫                // 合并信息
530f9afcc0dS猫头猫                return {
531f9afcc0dS猫头猫                    albumItem: {...albumItem, ...(result?.albumItem ?? {})},
532f9afcc0dS猫头猫                    isEnd: result.isEnd === false ? false : true,
533f9afcc0dS猫头猫                    musicList: result.musicList,
534f9afcc0dS猫头猫                };
535f9afcc0dS猫头猫            } else {
536f9afcc0dS猫头猫                return {
537f9afcc0dS猫头猫                    isEnd: result.isEnd === false ? false : true,
538f9afcc0dS猫头猫                    musicList: result.musicList,
539f9afcc0dS猫头猫                };
540f9afcc0dS猫头猫            }
5414394410dS猫头猫        } catch (e: any) {
5424394410dS猫头猫            trace('获取专辑信息失败', e?.message);
543ea6d708fS猫头猫            devLog('error', '获取专辑信息失败', e, e?.message);
544ea6d708fS猫头猫
545f9afcc0dS猫头猫            return null;
546927dbe93S猫头猫        }
547927dbe93S猫头猫    }
548927dbe93S猫头猫
5495830c002S猫头猫    /** 获取歌单信息 */
5505830c002S猫头猫    async getMusicSheetInfo(
5515830c002S猫头猫        sheetItem: IMusic.IMusicSheetItem,
5525830c002S猫头猫        page: number = 1,
5535830c002S猫头猫    ): Promise<IPlugin.ISheetInfoResult | null> {
5545281926bS猫头猫        if (!this.plugin.instance.getMusicSheetInfo) {
5555830c002S猫头猫            return {
5565830c002S猫头猫                sheetItem,
5575830c002S猫头猫                musicList: sheetItem?.musicList ?? [],
5585830c002S猫头猫                isEnd: true,
5595830c002S猫头猫            };
5605830c002S猫头猫        }
5615830c002S猫头猫        try {
5625830c002S猫头猫            const result = await this.plugin.instance?.getMusicSheetInfo?.(
5635830c002S猫头猫                resetMediaItem(sheetItem, undefined, true),
5645830c002S猫头猫                page,
5655830c002S猫头猫            );
5665830c002S猫头猫            if (!result) {
5675830c002S猫头猫                throw new Error();
5685830c002S猫头猫            }
5695830c002S猫头猫            result?.musicList?.forEach(_ => {
5705830c002S猫头猫                resetMediaItem(_, this.plugin.name);
5715830c002S猫头猫            });
5725830c002S猫头猫
5735830c002S猫头猫            if (page <= 1) {
5745830c002S猫头猫                // 合并信息
5755830c002S猫头猫                return {
5765830c002S猫头猫                    sheetItem: {...sheetItem, ...(result?.sheetItem ?? {})},
5775830c002S猫头猫                    isEnd: result.isEnd === false ? false : true,
5785830c002S猫头猫                    musicList: result.musicList,
5795830c002S猫头猫                };
5805830c002S猫头猫            } else {
5815830c002S猫头猫                return {
5825830c002S猫头猫                    isEnd: result.isEnd === false ? false : true,
5835830c002S猫头猫                    musicList: result.musicList,
5845830c002S猫头猫                };
5855830c002S猫头猫            }
5865830c002S猫头猫        } catch (e: any) {
5875830c002S猫头猫            trace('获取歌单信息失败', e, e?.message);
5885830c002S猫头猫            devLog('error', '获取歌单信息失败', e, e?.message);
5895830c002S猫头猫
5905830c002S猫头猫            return null;
5915830c002S猫头猫        }
5925830c002S猫头猫    }
5935830c002S猫头猫
594927dbe93S猫头猫    /** 查询作者信息 */
595efb9da24S猫头猫    async getArtistWorks<T extends IArtist.ArtistMediaType>(
596927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
597927dbe93S猫头猫        page: number,
598927dbe93S猫头猫        type: T,
599927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
600efb9da24S猫头猫        if (!this.plugin.instance.getArtistWorks) {
601927dbe93S猫头猫            return {
602927dbe93S猫头猫                isEnd: true,
603927dbe93S猫头猫                data: [],
604927dbe93S猫头猫            };
605927dbe93S猫头猫        }
606927dbe93S猫头猫        try {
607efb9da24S猫头猫            const result = await this.plugin.instance.getArtistWorks(
608927dbe93S猫头猫                artistItem,
609927dbe93S猫头猫                page,
610927dbe93S猫头猫                type,
611927dbe93S猫头猫            );
612927dbe93S猫头猫            if (!result.data) {
613927dbe93S猫头猫                return {
614927dbe93S猫头猫                    isEnd: true,
615927dbe93S猫头猫                    data: [],
616927dbe93S猫头猫                };
617927dbe93S猫头猫            }
618927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
619927dbe93S猫头猫            return {
620927dbe93S猫头猫                isEnd: result.isEnd ?? true,
621927dbe93S猫头猫                data: result.data,
622927dbe93S猫头猫            };
6234394410dS猫头猫        } catch (e: any) {
6244394410dS猫头猫            trace('查询作者信息失败', e?.message);
625ea6d708fS猫头猫            devLog('error', '查询作者信息失败', e, e?.message);
626ea6d708fS猫头猫
627927dbe93S猫头猫            throw e;
628927dbe93S猫头猫        }
629927dbe93S猫头猫    }
63008380090S猫头猫
63108380090S猫头猫    /** 导入歌单 */
63208380090S猫头猫    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
63308380090S猫头猫        try {
63408380090S猫头猫            const result =
63508380090S猫头猫                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
63608380090S猫头猫            result.forEach(_ => resetMediaItem(_, this.plugin.name));
63708380090S猫头猫            return result;
638ea6d708fS猫头猫        } catch (e: any) {
6390e4173cdS猫头猫            console.log(e);
640ea6d708fS猫头猫            devLog('error', '导入歌单失败', e, e?.message);
641ea6d708fS猫头猫
64208380090S猫头猫            return [];
64308380090S猫头猫        }
64408380090S猫头猫    }
6454d9d3c4cS猫头猫    /** 导入单曲 */
6464d9d3c4cS猫头猫    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
6474d9d3c4cS猫头猫        try {
6484d9d3c4cS猫头猫            const result = await this.plugin.instance?.importMusicItem?.(
6494d9d3c4cS猫头猫                urlLike,
6504d9d3c4cS猫头猫            );
6514d9d3c4cS猫头猫            if (!result) {
6524d9d3c4cS猫头猫                throw new Error();
6534d9d3c4cS猫头猫            }
6544d9d3c4cS猫头猫            resetMediaItem(result, this.plugin.name);
6554d9d3c4cS猫头猫            return result;
656ea6d708fS猫头猫        } catch (e: any) {
657ea6d708fS猫头猫            devLog('error', '导入单曲失败', e, e?.message);
658ea6d708fS猫头猫
6594d9d3c4cS猫头猫            return null;
6604d9d3c4cS猫头猫        }
6614d9d3c4cS猫头猫    }
662d52aa40eS猫头猫    /** 获取榜单 */
66392b6c95aS猫头猫    async getTopLists(): Promise<IMusic.IMusicSheetGroupItem[]> {
664d52aa40eS猫头猫        try {
665d52aa40eS猫头猫            const result = await this.plugin.instance?.getTopLists?.();
666d52aa40eS猫头猫            if (!result) {
667d52aa40eS猫头猫                throw new Error();
668d52aa40eS猫头猫            }
669d52aa40eS猫头猫            return result;
670d52aa40eS猫头猫        } catch (e: any) {
671d52aa40eS猫头猫            devLog('error', '获取榜单失败', e, e?.message);
672d52aa40eS猫头猫            return [];
673d52aa40eS猫头猫        }
674d52aa40eS猫头猫    }
675d52aa40eS猫头猫    /** 获取榜单详情 */
676d52aa40eS猫头猫    async getTopListDetail(
67792b6c95aS猫头猫        topListItem: IMusic.IMusicSheetItemBase,
67892b6c95aS猫头猫    ): Promise<ICommon.WithMusicList<IMusic.IMusicSheetItemBase>> {
679d52aa40eS猫头猫        try {
680d52aa40eS猫头猫            const result = await this.plugin.instance?.getTopListDetail?.(
681d52aa40eS猫头猫                topListItem,
682d52aa40eS猫头猫            );
683d52aa40eS猫头猫            if (!result) {
684d52aa40eS猫头猫                throw new Error();
685d52aa40eS猫头猫            }
686d384662fS猫头猫            if (result.musicList) {
687d384662fS猫头猫                result.musicList.forEach(_ =>
688d384662fS猫头猫                    resetMediaItem(_, this.plugin.name),
689d384662fS猫头猫                );
690d384662fS猫头猫            }
691d52aa40eS猫头猫            return result;
692d52aa40eS猫头猫        } catch (e: any) {
693d52aa40eS猫头猫            devLog('error', '获取榜单详情失败', e, e?.message);
694d52aa40eS猫头猫            return {
695d52aa40eS猫头猫                ...topListItem,
696d52aa40eS猫头猫                musicList: [],
697d52aa40eS猫头猫            };
698d52aa40eS猫头猫        }
699d52aa40eS猫头猫    }
700ceb900cdS猫头猫
7015830c002S猫头猫    /** 获取推荐歌单的tag */
702ceb900cdS猫头猫    async getRecommendSheetTags(): Promise<IPlugin.IGetRecommendSheetTagsResult> {
703ceb900cdS猫头猫        try {
704ceb900cdS猫头猫            const result =
705ceb900cdS猫头猫                await this.plugin.instance?.getRecommendSheetTags?.();
706ceb900cdS猫头猫            if (!result) {
707ceb900cdS猫头猫                throw new Error();
708ceb900cdS猫头猫            }
709ceb900cdS猫头猫            return result;
710ceb900cdS猫头猫        } catch (e: any) {
711ceb900cdS猫头猫            devLog('error', '获取推荐歌单失败', e, e?.message);
712ceb900cdS猫头猫            return {
713ceb900cdS猫头猫                data: [],
714ceb900cdS猫头猫            };
715ceb900cdS猫头猫        }
716ceb900cdS猫头猫    }
7175830c002S猫头猫    /** 获取某个tag的推荐歌单 */
718ceb900cdS猫头猫    async getRecommendSheetsByTag(
719ceb900cdS猫头猫        tagItem: ICommon.IUnique,
720ceb900cdS猫头猫        page?: number,
721ceb900cdS猫头猫    ): Promise<ICommon.PaginationResponse<IMusic.IMusicSheetItemBase>> {
722ceb900cdS猫头猫        try {
723ceb900cdS猫头猫            const result =
724ceb900cdS猫头猫                await this.plugin.instance?.getRecommendSheetsByTag?.(
725ceb900cdS猫头猫                    tagItem,
726ceb900cdS猫头猫                    page ?? 1,
727ceb900cdS猫头猫                );
728ceb900cdS猫头猫            if (!result) {
729ceb900cdS猫头猫                throw new Error();
730ceb900cdS猫头猫            }
731ceb900cdS猫头猫            if (result.isEnd !== false) {
732ceb900cdS猫头猫                result.isEnd = true;
733ceb900cdS猫头猫            }
734ceb900cdS猫头猫            if (!result.data) {
735ceb900cdS猫头猫                result.data = [];
736ceb900cdS猫头猫            }
737ceb900cdS猫头猫            result.data.forEach(item => resetMediaItem(item, this.plugin.name));
738ceb900cdS猫头猫
739ceb900cdS猫头猫            return result;
740ceb900cdS猫头猫        } catch (e: any) {
741ceb900cdS猫头猫            devLog('error', '获取推荐歌单详情失败', e, e?.message);
742ceb900cdS猫头猫            return {
743ceb900cdS猫头猫                isEnd: true,
744ceb900cdS猫头猫                data: [],
745ceb900cdS猫头猫            };
746ceb900cdS猫头猫        }
747ceb900cdS猫头猫    }
748927dbe93S猫头猫}
749d5bfeb7eS猫头猫//#endregion
7501a5528a0S猫头猫
751927dbe93S猫头猫let plugins: Array<Plugin> = [];
752927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
75374d0cf81S猫头猫
754d5bfeb7eS猫头猫//#region 本地音乐插件
75574d0cf81S猫头猫/** 本地插件 */
75674d0cf81S猫头猫const localFilePlugin = new Plugin(function () {
7570e4173cdS猫头猫    return {
758d5bfeb7eS猫头猫        platform: localPluginPlatform,
75974d0cf81S猫头猫        _path: '',
76074d0cf81S猫头猫        async getMusicInfo(musicBase) {
76174d0cf81S猫头猫            const localPath = getInternalData<string>(
76274d0cf81S猫头猫                musicBase,
76374d0cf81S猫头猫                InternalDataType.LOCALPATH,
7640e4173cdS猫头猫            );
76574d0cf81S猫头猫            if (localPath) {
76674d0cf81S猫头猫                const coverImg = await Mp3Util.getMediaCoverImg(localPath);
76774d0cf81S猫头猫                return {
76874d0cf81S猫头猫                    artwork: coverImg,
76974d0cf81S猫头猫                };
77074d0cf81S猫头猫            }
77174d0cf81S猫头猫            return null;
77274d0cf81S猫头猫        },
7737993f90eS猫头猫        async getLyric(musicBase) {
7747993f90eS猫头猫            const localPath = getInternalData<string>(
7757993f90eS猫头猫                musicBase,
7767993f90eS猫头猫                InternalDataType.LOCALPATH,
7777993f90eS猫头猫            );
7783a6f67b1S猫头猫            let rawLrc: string | null = null;
7797993f90eS猫头猫            if (localPath) {
7803a6f67b1S猫头猫                // 读取内嵌歌词
7813a6f67b1S猫头猫                try {
7823a6f67b1S猫头猫                    rawLrc = await Mp3Util.getLyric(localPath);
7833a6f67b1S猫头猫                } catch (e) {
784a84a85c5S猫头猫                    console.log('读取内嵌歌词失败', e);
7857993f90eS猫头猫                }
7863a6f67b1S猫头猫                if (!rawLrc) {
7873a6f67b1S猫头猫                    // 读取配置歌词
7883a6f67b1S猫头猫                    const lastDot = localPath.lastIndexOf('.');
7893a6f67b1S猫头猫                    const lrcPath = localPath.slice(0, lastDot) + '.lrc';
7903a6f67b1S猫头猫
7913a6f67b1S猫头猫                    try {
7923a6f67b1S猫头猫                        if (await exists(lrcPath)) {
7933a6f67b1S猫头猫                            rawLrc = await readFile(lrcPath, 'utf8');
7943a6f67b1S猫头猫                        }
7953a6f67b1S猫头猫                    } catch {}
7963a6f67b1S猫头猫                }
7973a6f67b1S猫头猫            }
7983a6f67b1S猫头猫
7993a6f67b1S猫头猫            return rawLrc
8003a6f67b1S猫头猫                ? {
8013a6f67b1S猫头猫                      rawLrc,
8023a6f67b1S猫头猫                  }
8033a6f67b1S猫头猫                : null;
8047993f90eS猫头猫        },
805a84a85c5S猫头猫        async importMusicItem(urlLike) {
806a84a85c5S猫头猫            let meta: any = {};
807a84a85c5S猫头猫            try {
808a84a85c5S猫头猫                meta = await Mp3Util.getBasicMeta(urlLike);
809a84a85c5S猫头猫            } catch {}
810a84a85c5S猫头猫            const id = await FileSystem.hash(urlLike, 'MD5');
811a84a85c5S猫头猫            return {
812a84a85c5S猫头猫                id: id,
813a84a85c5S猫头猫                platform: '本地',
814a84a85c5S猫头猫                title: meta?.title ?? getFileName(urlLike),
815a84a85c5S猫头猫                artist: meta?.artist ?? '未知歌手',
816a84a85c5S猫头猫                duration: parseInt(meta?.duration ?? '0') / 1000,
817a84a85c5S猫头猫                album: meta?.album ?? '未知专辑',
818a84a85c5S猫头猫                artwork: '',
819a84a85c5S猫头猫                [internalSerializeKey]: {
820a84a85c5S猫头猫                    localPath: urlLike,
821a84a85c5S猫头猫                },
822a84a85c5S猫头猫            };
823a84a85c5S猫头猫        },
82474d0cf81S猫头猫    };
82574d0cf81S猫头猫}, '');
8267993f90eS猫头猫localFilePlugin.hash = localPluginHash;
827927dbe93S猫头猫
828d5bfeb7eS猫头猫//#endregion
829d5bfeb7eS猫头猫
830927dbe93S猫头猫async function setup() {
831927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
832927dbe93S猫头猫    try {
833927dbe93S猫头猫        // 加载插件
834927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
835927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
836927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
8371e263108S猫头猫            trace('初始化插件', _pluginUrl);
8381e263108S猫头猫            if (
8391e263108S猫头猫                _pluginUrl.isFile() &&
8401e263108S猫头猫                (_pluginUrl.name?.endsWith?.('.js') ||
8411e263108S猫头猫                    _pluginUrl.path?.endsWith?.('.js'))
8421e263108S猫头猫            ) {
843927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
844927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
8454060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
8464060c00aS猫头猫                    p => p.hash === plugin.hash,
8474060c00aS猫头猫                );
848927dbe93S猫头猫                if (_pluginIndex !== -1) {
849927dbe93S猫头猫                    // 重复插件,直接忽略
8500c266394S猫头猫                    continue;
851927dbe93S猫头猫                }
852927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
853927dbe93S猫头猫            }
854927dbe93S猫头猫        }
855927dbe93S猫头猫
856927dbe93S猫头猫        plugins = _plugins;
857927dbe93S猫头猫        pluginStateMapper.notify();
858e08d37a3S猫头猫        /** 初始化meta信息 */
859e08d37a3S猫头猫        PluginMeta.setupMeta(plugins.map(_ => _.name));
860927dbe93S猫头猫    } catch (e: any) {
8614060c00aS猫头猫        ToastAndroid.show(
8624060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
8634060c00aS猫头猫            ToastAndroid.LONG,
8644060c00aS猫头猫        );
8651a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
866927dbe93S猫头猫        throw e;
867927dbe93S猫头猫    }
868927dbe93S猫头猫}
869927dbe93S猫头猫
870927dbe93S猫头猫// 安装插件
871927dbe93S猫头猫async function installPlugin(pluginPath: string) {
87222c09412S猫头猫    // if (pluginPath.endsWith('.js')) {
873927dbe93S猫头猫    const funcCode = await readFile(pluginPath, 'utf8');
874927dbe93S猫头猫    const plugin = new Plugin(funcCode, pluginPath);
875927dbe93S猫头猫    const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
876927dbe93S猫头猫    if (_pluginIndex !== -1) {
8774d9d3c4cS猫头猫        throw new Error('插件已安装');
878927dbe93S猫头猫    }
879927dbe93S猫头猫    if (plugin.hash !== '') {
880927dbe93S猫头猫        const fn = nanoid();
881927dbe93S猫头猫        const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
882927dbe93S猫头猫        await copyFile(pluginPath, _pluginPath);
883927dbe93S猫头猫        plugin.path = _pluginPath;
884927dbe93S猫头猫        plugins = plugins.concat(plugin);
885927dbe93S猫头猫        pluginStateMapper.notify();
886a84a85c5S猫头猫        return plugin;
887927dbe93S猫头猫    }
8884d9d3c4cS猫头猫    throw new Error('插件无法解析');
88922c09412S猫头猫    // }
89022c09412S猫头猫    // throw new Error('插件不存在');
891927dbe93S猫头猫}
892927dbe93S猫头猫
89358992c6bS猫头猫async function installPluginFromUrl(url: string) {
89458992c6bS猫头猫    try {
89558992c6bS猫头猫        const funcCode = (await axios.get(url)).data;
89658992c6bS猫头猫        if (funcCode) {
89758992c6bS猫头猫            const plugin = new Plugin(funcCode, '');
89858992c6bS猫头猫            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
89958992c6bS猫头猫            if (_pluginIndex !== -1) {
9008b7ddca8S猫头猫                // 静默忽略
9018b7ddca8S猫头猫                return;
90258992c6bS猫头猫            }
90325c1bd29S猫头猫            const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
90425c1bd29S猫头猫            if (oldVersionPlugin) {
90525c1bd29S猫头猫                if (
90625c1bd29S猫头猫                    compare(
90725c1bd29S猫头猫                        oldVersionPlugin.instance.version ?? '',
90825c1bd29S猫头猫                        plugin.instance.version ?? '',
90925c1bd29S猫头猫                        '>',
91025c1bd29S猫头猫                    )
91125c1bd29S猫头猫                ) {
91225c1bd29S猫头猫                    throw new Error('已安装更新版本的插件');
91325c1bd29S猫头猫                }
91425c1bd29S猫头猫            }
91525c1bd29S猫头猫
91658992c6bS猫头猫            if (plugin.hash !== '') {
91758992c6bS猫头猫                const fn = nanoid();
91858992c6bS猫头猫                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
91958992c6bS猫头猫                await writeFile(_pluginPath, funcCode, 'utf8');
92058992c6bS猫头猫                plugin.path = _pluginPath;
92158992c6bS猫头猫                plugins = plugins.concat(plugin);
92225c1bd29S猫头猫                if (oldVersionPlugin) {
92325c1bd29S猫头猫                    plugins = plugins.filter(
92425c1bd29S猫头猫                        _ => _.hash !== oldVersionPlugin.hash,
92525c1bd29S猫头猫                    );
92625c1bd29S猫头猫                    try {
92725c1bd29S猫头猫                        await unlink(oldVersionPlugin.path);
92825c1bd29S猫头猫                    } catch {}
92925c1bd29S猫头猫                }
93058992c6bS猫头猫                pluginStateMapper.notify();
93158992c6bS猫头猫                return;
93258992c6bS猫头猫            }
93374acbfc0S猫头猫            throw new Error('插件无法解析!');
93458992c6bS猫头猫        }
93525c1bd29S猫头猫    } catch (e: any) {
936ea6d708fS猫头猫        devLog('error', 'URL安装插件失败', e, e?.message);
93758992c6bS猫头猫        errorLog('URL安装插件失败', e);
93825c1bd29S猫头猫        throw new Error(e?.message ?? '');
93958992c6bS猫头猫    }
94058992c6bS猫头猫}
94158992c6bS猫头猫
942927dbe93S猫头猫/** 卸载插件 */
943927dbe93S猫头猫async function uninstallPlugin(hash: string) {
944927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
945927dbe93S猫头猫    if (targetIndex !== -1) {
946927dbe93S猫头猫        try {
94724e5e74aS猫头猫            const pluginName = plugins[targetIndex].name;
948927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
949927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
950927dbe93S猫头猫            pluginStateMapper.notify();
95124e5e74aS猫头猫            if (plugins.every(_ => _.name !== pluginName)) {
95224e5e74aS猫头猫                await MediaMeta.removePlugin(pluginName);
95324e5e74aS猫头猫            }
954927dbe93S猫头猫        } catch {}
955927dbe93S猫头猫    }
956927dbe93S猫头猫}
957927dbe93S猫头猫
95808882a77S猫头猫async function uninstallAllPlugins() {
95908882a77S猫头猫    await Promise.all(
96008882a77S猫头猫        plugins.map(async plugin => {
96108882a77S猫头猫            try {
96208882a77S猫头猫                const pluginName = plugin.name;
96308882a77S猫头猫                await unlink(plugin.path);
96408882a77S猫头猫                await MediaMeta.removePlugin(pluginName);
96508882a77S猫头猫            } catch (e) {}
96608882a77S猫头猫        }),
96708882a77S猫头猫    );
96808882a77S猫头猫    plugins = [];
96908882a77S猫头猫    pluginStateMapper.notify();
970e08d37a3S猫头猫
971e08d37a3S猫头猫    /** 清除空余文件,异步做就可以了 */
972e08d37a3S猫头猫    readDir(pathConst.pluginPath)
973e08d37a3S猫头猫        .then(fns => {
974e08d37a3S猫头猫            fns.forEach(fn => {
975e08d37a3S猫头猫                unlink(fn.path).catch(emptyFunction);
976e08d37a3S猫头猫            });
977e08d37a3S猫头猫        })
978e08d37a3S猫头猫        .catch(emptyFunction);
97908882a77S猫头猫}
98008882a77S猫头猫
98125c1bd29S猫头猫async function updatePlugin(plugin: Plugin) {
98225c1bd29S猫头猫    const updateUrl = plugin.instance.srcUrl;
98325c1bd29S猫头猫    if (!updateUrl) {
98425c1bd29S猫头猫        throw new Error('没有更新源');
98525c1bd29S猫头猫    }
98625c1bd29S猫头猫    try {
98725c1bd29S猫头猫        await installPluginFromUrl(updateUrl);
98825c1bd29S猫头猫    } catch (e: any) {
98925c1bd29S猫头猫        if (e.message === '插件已安装') {
99025c1bd29S猫头猫            throw new Error('当前已是最新版本');
99125c1bd29S猫头猫        } else {
99225c1bd29S猫头猫            throw e;
99325c1bd29S猫头猫        }
99425c1bd29S猫头猫    }
99525c1bd29S猫头猫}
99625c1bd29S猫头猫
997927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
9982c595535S猫头猫    return getByName(mediaItem?.platform);
999927dbe93S猫头猫}
1000927dbe93S猫头猫
1001927dbe93S猫头猫function getByHash(hash: string) {
10027993f90eS猫头猫    return hash === localPluginHash
10037993f90eS猫头猫        ? localFilePlugin
10047993f90eS猫头猫        : plugins.find(_ => _.hash === hash);
1005927dbe93S猫头猫}
1006927dbe93S猫头猫
1007927dbe93S猫头猫function getByName(name: string) {
10087993f90eS猫头猫    return name === localPluginPlatform
10090e4173cdS猫头猫        ? localFilePlugin
10100e4173cdS猫头猫        : plugins.find(_ => _.name === name);
1011927dbe93S猫头猫}
1012927dbe93S猫头猫
1013927dbe93S猫头猫function getValidPlugins() {
1014927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
1015927dbe93S猫头猫}
1016927dbe93S猫头猫
10172b80a429S猫头猫function getSearchablePlugins(supportedSearchType?: ICommon.SupportMediaType) {
10182b80a429S猫头猫    return plugins.filter(
10192b80a429S猫头猫        _ =>
10202b80a429S猫头猫            _.state === 'enabled' &&
10212b80a429S猫头猫            _.instance.search &&
102239ac60f7S猫头猫            (supportedSearchType && _.instance.supportedSearchType
102339ac60f7S猫头猫                ? _.instance.supportedSearchType.includes(supportedSearchType)
10242b80a429S猫头猫                : true),
10252b80a429S猫头猫    );
1026efb9da24S猫头猫}
1027efb9da24S猫头猫
10282b80a429S猫头猫function getSortedSearchablePlugins(
10292b80a429S猫头猫    supportedSearchType?: ICommon.SupportMediaType,
10302b80a429S猫头猫) {
10312b80a429S猫头猫    return getSearchablePlugins(supportedSearchType).sort((a, b) =>
1032e08d37a3S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
1033e08d37a3S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
1034e08d37a3S猫头猫        0
1035e08d37a3S猫头猫            ? -1
1036e08d37a3S猫头猫            : 1,
1037e08d37a3S猫头猫    );
1038e08d37a3S猫头猫}
1039e08d37a3S猫头猫
104015feccc1S猫头猫function getTopListsablePlugins() {
104115feccc1S猫头猫    return plugins.filter(_ => _.state === 'enabled' && _.instance.getTopLists);
104215feccc1S猫头猫}
104315feccc1S猫头猫
104415feccc1S猫头猫function getSortedTopListsablePlugins() {
104515feccc1S猫头猫    return getTopListsablePlugins().sort((a, b) =>
104615feccc1S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
104715feccc1S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
104815feccc1S猫头猫        0
104915feccc1S猫头猫            ? -1
105015feccc1S猫头猫            : 1,
105115feccc1S猫头猫    );
105215feccc1S猫头猫}
105315feccc1S猫头猫
1054ceb900cdS猫头猫function getRecommendSheetablePlugins() {
1055ceb900cdS猫头猫    return plugins.filter(
1056ceb900cdS猫头猫        _ => _.state === 'enabled' && _.instance.getRecommendSheetsByTag,
1057ceb900cdS猫头猫    );
1058ceb900cdS猫头猫}
1059ceb900cdS猫头猫
1060ceb900cdS猫头猫function getSortedRecommendSheetablePlugins() {
1061ceb900cdS猫头猫    return getRecommendSheetablePlugins().sort((a, b) =>
1062ceb900cdS猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
1063ceb900cdS猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
1064ceb900cdS猫头猫        0
1065ceb900cdS猫头猫            ? -1
1066ceb900cdS猫头猫            : 1,
1067ceb900cdS猫头猫    );
1068ceb900cdS猫头猫}
1069ceb900cdS猫头猫
1070e08d37a3S猫头猫function useSortedPlugins() {
1071e08d37a3S猫头猫    const _plugins = pluginStateMapper.useMappedState();
1072e08d37a3S猫头猫    const _pluginMetaAll = PluginMeta.usePluginMetaAll();
1073e08d37a3S猫头猫
107434588741S猫头猫    const [sortedPlugins, setSortedPlugins] = useState(
107534588741S猫头猫        [..._plugins].sort((a, b) =>
1076e08d37a3S猫头猫            (_pluginMetaAll[a.name]?.order ?? Infinity) -
1077e08d37a3S猫头猫                (_pluginMetaAll[b.name]?.order ?? Infinity) <
1078e08d37a3S猫头猫            0
1079e08d37a3S猫头猫                ? -1
1080e08d37a3S猫头猫                : 1,
108134588741S猫头猫        ),
1082e08d37a3S猫头猫    );
108334588741S猫头猫
108434588741S猫头猫    useEffect(() => {
1085d4cd40d8S猫头猫        InteractionManager.runAfterInteractions(() => {
108634588741S猫头猫            setSortedPlugins(
108734588741S猫头猫                [..._plugins].sort((a, b) =>
108834588741S猫头猫                    (_pluginMetaAll[a.name]?.order ?? Infinity) -
108934588741S猫头猫                        (_pluginMetaAll[b.name]?.order ?? Infinity) <
109034588741S猫头猫                    0
109134588741S猫头猫                        ? -1
109234588741S猫头猫                        : 1,
109334588741S猫头猫                ),
109434588741S猫头猫            );
1095d4cd40d8S猫头猫        });
109634588741S猫头猫    }, [_plugins, _pluginMetaAll]);
109734588741S猫头猫
109834588741S猫头猫    return sortedPlugins;
1099e08d37a3S猫头猫}
1100e08d37a3S猫头猫
1101927dbe93S猫头猫const PluginManager = {
1102927dbe93S猫头猫    setup,
1103927dbe93S猫头猫    installPlugin,
110458992c6bS猫头猫    installPluginFromUrl,
110525c1bd29S猫头猫    updatePlugin,
1106927dbe93S猫头猫    uninstallPlugin,
1107927dbe93S猫头猫    getByMedia,
1108927dbe93S猫头猫    getByHash,
1109927dbe93S猫头猫    getByName,
1110927dbe93S猫头猫    getValidPlugins,
1111efb9da24S猫头猫    getSearchablePlugins,
1112e08d37a3S猫头猫    getSortedSearchablePlugins,
111315feccc1S猫头猫    getTopListsablePlugins,
1114ceb900cdS猫头猫    getSortedRecommendSheetablePlugins,
111515feccc1S猫头猫    getSortedTopListsablePlugins,
11165276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
1117e08d37a3S猫头猫    useSortedPlugins,
111808882a77S猫头猫    uninstallAllPlugins,
11195276aef9S猫头猫};
1120927dbe93S猫头猫
1121927dbe93S猫头猫export default PluginManager;
1122