xref: /MusicFree/src/core/pluginManager.ts (revision e0caf3427c927f4cf2efda9969f9a6f4fb0ef565)
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';
46927dbe93S猫头猫
4761aca335S猫头猫axios.defaults.timeout = 2000;
48927dbe93S猫头猫
49927dbe93S猫头猫const sha256 = CryptoJs.SHA256;
50927dbe93S猫头猫
51cfa0fc07S猫头猫export enum PluginStateCode {
52927dbe93S猫头猫    /** 版本不匹配 */
53927dbe93S猫头猫    VersionNotMatch = 'VERSION NOT MATCH',
54927dbe93S猫头猫    /** 无法解析 */
55927dbe93S猫头猫    CannotParse = 'CANNOT PARSE',
56927dbe93S猫头猫}
57927dbe93S猫头猫
589c34d637S猫头猫const packages: Record<string, any> = {
599c34d637S猫头猫    cheerio,
609c34d637S猫头猫    'crypto-js': CryptoJs,
619c34d637S猫头猫    axios,
629c34d637S猫头猫    dayjs,
639c34d637S猫头猫    'big-integer': bigInt,
649c34d637S猫头猫    qs,
659c34d637S猫头猫    he,
663b3d6357S猫头猫    '@react-native-cookies/cookies': CookieManager,
679c34d637S猫头猫};
689c34d637S猫头猫
69b43683eaS猫头猫const _require = (packageName: string) => {
70b43683eaS猫头猫    let pkg = packages[packageName];
71b43683eaS猫头猫    pkg.default = pkg;
72b43683eaS猫头猫    return pkg;
73b43683eaS猫头猫};
749c34d637S猫头猫
7553f8cd8eS猫头猫const _consoleBind = function (
7653f8cd8eS猫头猫    method: 'log' | 'error' | 'info' | 'warn',
7753f8cd8eS猫头猫    ...args: any
7853f8cd8eS猫头猫) {
7953f8cd8eS猫头猫    const fn = console[method];
8053f8cd8eS猫头猫    if (fn) {
8153f8cd8eS猫头猫        fn(...args);
8253f8cd8eS猫头猫        devLog(method, ...args);
8353f8cd8eS猫头猫    }
8453f8cd8eS猫头猫};
8553f8cd8eS猫头猫
8653f8cd8eS猫头猫const _console = {
8753f8cd8eS猫头猫    log: _consoleBind.bind(null, 'log'),
8853f8cd8eS猫头猫    warn: _consoleBind.bind(null, 'warn'),
8953f8cd8eS猫头猫    info: _consoleBind.bind(null, 'info'),
9053f8cd8eS猫头猫    error: _consoleBind.bind(null, 'error'),
9153f8cd8eS猫头猫};
9253f8cd8eS猫头猫
93d5bfeb7eS猫头猫//#region 插件类
94927dbe93S猫头猫export class Plugin {
95927dbe93S猫头猫    /** 插件名 */
96927dbe93S猫头猫    public name: string;
97927dbe93S猫头猫    /** 插件的hash,作为唯一id */
98927dbe93S猫头猫    public hash: string;
99927dbe93S猫头猫    /** 插件状态:激活、关闭、错误 */
100927dbe93S猫头猫    public state: 'enabled' | 'disabled' | 'error';
101927dbe93S猫头猫    /** 插件状态信息 */
102927dbe93S猫头猫    public stateCode?: PluginStateCode;
103927dbe93S猫头猫    /** 插件的实例 */
104927dbe93S猫头猫    public instance: IPlugin.IPluginInstance;
105927dbe93S猫头猫    /** 插件路径 */
106927dbe93S猫头猫    public path: string;
107927dbe93S猫头猫    /** 插件方法 */
108927dbe93S猫头猫    public methods: PluginMethods;
109927dbe93S猫头猫
11074d0cf81S猫头猫    constructor(
11174d0cf81S猫头猫        funcCode: string | (() => IPlugin.IPluginInstance),
11274d0cf81S猫头猫        pluginPath: string,
11374d0cf81S猫头猫    ) {
114927dbe93S猫头猫        this.state = 'enabled';
115927dbe93S猫头猫        let _instance: IPlugin.IPluginInstance;
1163b3d6357S猫头猫        const _module: any = {exports: {}};
117927dbe93S猫头猫        try {
11874d0cf81S猫头猫            if (typeof funcCode === 'string') {
119*e0caf342S猫头猫                // 插件的环境变量
120*e0caf342S猫头猫                const env = {
121*e0caf342S猫头猫                    getUserVariables: () => {
122*e0caf342S猫头猫                        return (
123*e0caf342S猫头猫                            PluginMeta.getPluginMeta(this)?.userVariables ?? {}
124*e0caf342S猫头猫                        );
125*e0caf342S猫头猫                    },
126*e0caf342S猫头猫                };
127*e0caf342S猫头猫
1284060c00aS猫头猫                // eslint-disable-next-line no-new-func
129927dbe93S猫头猫                _instance = Function(`
130927dbe93S猫头猫                    'use strict';
131*e0caf342S猫头猫                    return function(require, __musicfree_require, module, exports, console, env) {
1329c34d637S猫头猫                        ${funcCode}
133927dbe93S猫头猫                    }
134*e0caf342S猫头猫                `)()(
135*e0caf342S猫头猫                    _require,
136*e0caf342S猫头猫                    _require,
137*e0caf342S猫头猫                    _module,
138*e0caf342S猫头猫                    _module.exports,
139*e0caf342S猫头猫                    _console,
140*e0caf342S猫头猫                    env,
141*e0caf342S猫头猫                );
1423b3d6357S猫头猫                if (_module.exports.default) {
1433b3d6357S猫头猫                    _instance = _module.exports
1443b3d6357S猫头猫                        .default as IPlugin.IPluginInstance;
1453b3d6357S猫头猫                } else {
1469c34d637S猫头猫                    _instance = _module.exports as IPlugin.IPluginInstance;
1473b3d6357S猫头猫                }
14874d0cf81S猫头猫            } else {
14974d0cf81S猫头猫                _instance = funcCode();
15074d0cf81S猫头猫            }
151927dbe93S猫头猫            this.checkValid(_instance);
152927dbe93S猫头猫        } catch (e: any) {
153b43683eaS猫头猫            console.log(e);
154927dbe93S猫头猫            this.state = 'error';
155927dbe93S猫头猫            this.stateCode = PluginStateCode.CannotParse;
156927dbe93S猫头猫            if (e?.stateCode) {
157927dbe93S猫头猫                this.stateCode = e.stateCode;
158927dbe93S猫头猫            }
159927dbe93S猫头猫            errorLog(`${pluginPath}插件无法解析 `, {
160927dbe93S猫头猫                stateCode: this.stateCode,
161927dbe93S猫头猫                message: e?.message,
162927dbe93S猫头猫                stack: e?.stack,
163927dbe93S猫头猫            });
164927dbe93S猫头猫            _instance = e?.instance ?? {
165927dbe93S猫头猫                _path: '',
166927dbe93S猫头猫                platform: '',
167927dbe93S猫头猫                appVersion: '',
16820e6a092S猫头猫                async getMediaSource() {
169927dbe93S猫头猫                    return null;
170927dbe93S猫头猫                },
171927dbe93S猫头猫                async search() {
172927dbe93S猫头猫                    return {};
173927dbe93S猫头猫                },
174927dbe93S猫头猫                async getAlbumInfo() {
175927dbe93S猫头猫                    return null;
176927dbe93S猫头猫                },
177927dbe93S猫头猫            };
178927dbe93S猫头猫        }
179927dbe93S猫头猫        this.instance = _instance;
180927dbe93S猫头猫        this.path = pluginPath;
181927dbe93S猫头猫        this.name = _instance.platform;
182ab8941d9S猫头猫        if (
183ab8941d9S猫头猫            this.instance.platform === '' ||
184ab8941d9S猫头猫            this.instance.platform === undefined
185ab8941d9S猫头猫        ) {
186927dbe93S猫头猫            this.hash = '';
187927dbe93S猫头猫        } else {
18874d0cf81S猫头猫            if (typeof funcCode === 'string') {
189927dbe93S猫头猫                this.hash = sha256(funcCode).toString();
19074d0cf81S猫头猫            } else {
19174d0cf81S猫头猫                this.hash = sha256(funcCode.toString()).toString();
19274d0cf81S猫头猫            }
193927dbe93S猫头猫        }
194927dbe93S猫头猫
195927dbe93S猫头猫        // 放在最后
196927dbe93S猫头猫        this.methods = new PluginMethods(this);
197927dbe93S猫头猫    }
198927dbe93S猫头猫
199927dbe93S猫头猫    private checkValid(_instance: IPlugin.IPluginInstance) {
200927dbe93S猫头猫        /** 版本号校验 */
201927dbe93S猫头猫        if (
202927dbe93S猫头猫            _instance.appVersion &&
203927dbe93S猫头猫            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
204927dbe93S猫头猫        ) {
205927dbe93S猫头猫            throw {
206927dbe93S猫头猫                instance: _instance,
207927dbe93S猫头猫                stateCode: PluginStateCode.VersionNotMatch,
208927dbe93S猫头猫            };
209927dbe93S猫头猫        }
210927dbe93S猫头猫        return true;
211927dbe93S猫头猫    }
212927dbe93S猫头猫}
213d5bfeb7eS猫头猫//#endregion
214927dbe93S猫头猫
215d5bfeb7eS猫头猫//#region 基于插件类封装的方法,供给APP侧直接调用
216927dbe93S猫头猫/** 有缓存等信息 */
217927dbe93S猫头猫class PluginMethods implements IPlugin.IPluginInstanceMethods {
218927dbe93S猫头猫    private plugin;
219927dbe93S猫头猫    constructor(plugin: Plugin) {
220927dbe93S猫头猫        this.plugin = plugin;
221927dbe93S猫头猫    }
222927dbe93S猫头猫    /** 搜索 */
223927dbe93S猫头猫    async search<T extends ICommon.SupportMediaType>(
224927dbe93S猫头猫        query: string,
225927dbe93S猫头猫        page: number,
226927dbe93S猫头猫        type: T,
227927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
228927dbe93S猫头猫        if (!this.plugin.instance.search) {
229927dbe93S猫头猫            return {
230927dbe93S猫头猫                isEnd: true,
231927dbe93S猫头猫                data: [],
232927dbe93S猫头猫            };
233927dbe93S猫头猫        }
234927dbe93S猫头猫
2354060c00aS猫头猫        const result =
2364060c00aS猫头猫            (await this.plugin.instance.search(query, page, type)) ?? {};
237927dbe93S猫头猫        if (Array.isArray(result.data)) {
238927dbe93S猫头猫            result.data.forEach(_ => {
239927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
240927dbe93S猫头猫            });
241927dbe93S猫头猫            return {
242927dbe93S猫头猫                isEnd: result.isEnd ?? true,
243927dbe93S猫头猫                data: result.data,
244927dbe93S猫头猫            };
245927dbe93S猫头猫        }
246927dbe93S猫头猫        return {
247927dbe93S猫头猫            isEnd: true,
248927dbe93S猫头猫            data: [],
249927dbe93S猫头猫        };
250927dbe93S猫头猫    }
251927dbe93S猫头猫
252927dbe93S猫头猫    /** 获取真实源 */
25320e6a092S猫头猫    async getMediaSource(
254927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
255abaede57S猫头猫        quality: IMusic.IQualityKey = 'standard',
256927dbe93S猫头猫        retryCount = 1,
257dc160d50S猫头猫        notUpdateCache = false,
258192ae2b0S猫头猫    ): Promise<IPlugin.IMediaSourceResult | null> {
259927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
260927dbe93S猫头猫        const localPath =
2610e4173cdS猫头猫            getInternalData<string>(musicItem, InternalDataType.LOCALPATH) ??
2620e4173cdS猫头猫            getInternalData<string>(
2630e4173cdS猫头猫                LocalMusicSheet.isLocalMusic(musicItem),
2640e4173cdS猫头猫                InternalDataType.LOCALPATH,
2650e4173cdS猫头猫            );
2660e4173cdS猫头猫        if (localPath && (await FileSystem.exists(localPath))) {
2670e4173cdS猫头猫            trace('本地播放', localPath);
268927dbe93S猫头猫            return {
269927dbe93S猫头猫                url: localPath,
270927dbe93S猫头猫            };
271927dbe93S猫头猫        }
2727993f90eS猫头猫        if (musicItem.platform === localPluginPlatform) {
273f5935920S猫头猫            throw new Error('本地音乐不存在');
274f5935920S猫头猫        }
275927dbe93S猫头猫        // 2. 缓存播放
276927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
277985f8e75S猫头猫        const pluginCacheControl =
278985f8e75S猫头猫            this.plugin.instance.cacheControl ?? 'no-cache';
279cfa0fc07S猫头猫        if (
280cfa0fc07S猫头猫            mediaCache &&
281abaede57S猫头猫            mediaCache?.qualities?.[quality]?.url &&
28248f4b873S猫头猫            (pluginCacheControl === CacheControl.Cache ||
28348f4b873S猫头猫                (pluginCacheControl === CacheControl.NoCache &&
284ef714860S猫头猫                    Network.isOffline()))
285cfa0fc07S猫头猫        ) {
2865276aef9S猫头猫            trace('播放', '缓存播放');
287abaede57S猫头猫            const qualityInfo = mediaCache.qualities[quality];
288927dbe93S猫头猫            return {
289abaede57S猫头猫                url: qualityInfo.url,
290927dbe93S猫头猫                headers: mediaCache.headers,
2914060c00aS猫头猫                userAgent:
2924060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
293927dbe93S猫头猫            };
294927dbe93S猫头猫        }
295927dbe93S猫头猫        // 3. 插件解析
29620e6a092S猫头猫        if (!this.plugin.instance.getMediaSource) {
297abaede57S猫头猫            return {url: musicItem?.qualities?.[quality]?.url ?? musicItem.url};
298927dbe93S猫头猫        }
299927dbe93S猫头猫        try {
300abaede57S猫头猫            const {url, headers} = (await this.plugin.instance.getMediaSource(
301abaede57S猫头猫                musicItem,
302abaede57S猫头猫                quality,
303abaede57S猫头猫            )) ?? {url: musicItem?.qualities?.[quality]?.url};
304927dbe93S猫头猫            if (!url) {
305a28eac61S猫头猫                throw new Error('NOT RETRY');
306927dbe93S猫头猫            }
3075276aef9S猫头猫            trace('播放', '插件播放');
308927dbe93S猫头猫            const result = {
309927dbe93S猫头猫                url,
310927dbe93S猫头猫                headers,
311927dbe93S猫头猫                userAgent: headers?.['user-agent'],
312cfa0fc07S猫头猫            } as IPlugin.IMediaSourceResult;
313927dbe93S猫头猫
314dc160d50S猫头猫            if (
315dc160d50S猫头猫                pluginCacheControl !== CacheControl.NoStore &&
316dc160d50S猫头猫                !notUpdateCache
317dc160d50S猫头猫            ) {
318abaede57S猫头猫                Cache.update(musicItem, [
319abaede57S猫头猫                    ['headers', result.headers],
320abaede57S猫头猫                    ['userAgent', result.userAgent],
321abaede57S猫头猫                    [`qualities.${quality}.url`, url],
322abaede57S猫头猫                ]);
323752ffc5aS猫头猫            }
324cfa0fc07S猫头猫
325927dbe93S猫头猫            return result;
326927dbe93S猫头猫        } catch (e: any) {
327a28eac61S猫头猫            if (retryCount > 0 && e?.message !== 'NOT RETRY') {
328927dbe93S猫头猫                await delay(150);
329abaede57S猫头猫                return this.getMediaSource(musicItem, quality, --retryCount);
330927dbe93S猫头猫            }
331927dbe93S猫头猫            errorLog('获取真实源失败', e?.message);
332ea6d708fS猫头猫            devLog('error', '获取真实源失败', e, e?.message);
333192ae2b0S猫头猫            return null;
334927dbe93S猫头猫        }
335927dbe93S猫头猫    }
336927dbe93S猫头猫
337927dbe93S猫头猫    /** 获取音乐详情 */
338927dbe93S猫头猫    async getMusicInfo(
339927dbe93S猫头猫        musicItem: ICommon.IMediaBase,
34074d0cf81S猫头猫    ): Promise<Partial<IMusic.IMusicItem> | null> {
341927dbe93S猫头猫        if (!this.plugin.instance.getMusicInfo) {
342d704daedS猫头猫            return null;
343927dbe93S猫头猫        }
34474d0cf81S猫头猫        try {
345927dbe93S猫头猫            return (
346927dbe93S猫头猫                this.plugin.instance.getMusicInfo(
3477993f90eS猫头猫                    resetMediaItem(musicItem, undefined, true),
348d704daedS猫头猫                ) ?? null
349927dbe93S猫头猫            );
350ea6d708fS猫头猫        } catch (e: any) {
351ea6d708fS猫头猫            devLog('error', '获取音乐详情失败', e, e?.message);
352d704daedS猫头猫            return null;
35374d0cf81S猫头猫        }
354927dbe93S猫头猫    }
355927dbe93S猫头猫
356927dbe93S猫头猫    /** 获取歌词 */
357927dbe93S猫头猫    async getLyric(
358927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
359927dbe93S猫头猫        from?: IMusic.IMusicItemBase,
360927dbe93S猫头猫    ): Promise<ILyric.ILyricSource | null> {
361927dbe93S猫头猫        // 1.额外存储的meta信息
362927dbe93S猫头猫        const meta = MediaMeta.get(musicItem);
363927dbe93S猫头猫        if (meta && meta.associatedLrc) {
364927dbe93S猫头猫            // 有关联歌词
365927dbe93S猫头猫            if (
366927dbe93S猫头猫                isSameMediaItem(musicItem, from) ||
367927dbe93S猫头猫                isSameMediaItem(meta.associatedLrc, musicItem)
368927dbe93S猫头猫            ) {
369927dbe93S猫头猫                // 形成环路,断开当前的环
370927dbe93S猫头猫                await MediaMeta.update(musicItem, {
371927dbe93S猫头猫                    associatedLrc: undefined,
372927dbe93S猫头猫                });
373927dbe93S猫头猫                // 无歌词
374927dbe93S猫头猫                return null;
375927dbe93S猫头猫            }
376927dbe93S猫头猫            // 获取关联歌词
3777a91f04fS猫头猫            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
3784060c00aS猫头猫            const result = await this.getLyric(
3797a91f04fS猫头猫                {...meta.associatedLrc, ...associatedMeta},
3804060c00aS猫头猫                from ?? musicItem,
3814060c00aS猫头猫            );
382927dbe93S猫头猫            if (result) {
383927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
384927dbe93S猫头猫                return result;
385927dbe93S猫头猫            }
386927dbe93S猫头猫        }
387927dbe93S猫头猫        const cache = Cache.get(musicItem);
388927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
389927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
390927dbe93S猫头猫        // 如果存在文本
391927dbe93S猫头猫        if (rawLrc) {
392927dbe93S猫头猫            return {
393927dbe93S猫头猫                rawLrc,
394927dbe93S猫头猫                lrc: lrcUrl,
395927dbe93S猫头猫            };
396927dbe93S猫头猫        }
397927dbe93S猫头猫        // 2.本地缓存
398927dbe93S猫头猫        const localLrc =
3990e4173cdS猫头猫            meta?.[internalSerializeKey]?.local?.localLrc ||
4000e4173cdS猫头猫            cache?.[internalSerializeKey]?.local?.localLrc;
401927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
402927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
403927dbe93S猫头猫            return {
404927dbe93S猫头猫                rawLrc,
405927dbe93S猫头猫                lrc: lrcUrl,
406927dbe93S猫头猫            };
407927dbe93S猫头猫        }
408927dbe93S猫头猫        // 3.优先使用url
409927dbe93S猫头猫        if (lrcUrl) {
410927dbe93S猫头猫            try {
411927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
41261aca335S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 2000})).data;
413927dbe93S猫头猫                return {
414927dbe93S猫头猫                    rawLrc,
415927dbe93S猫头猫                    lrc: lrcUrl,
416927dbe93S猫头猫                };
417927dbe93S猫头猫            } catch {
418927dbe93S猫头猫                lrcUrl = undefined;
419927dbe93S猫头猫            }
420927dbe93S猫头猫        }
421927dbe93S猫头猫        // 4. 如果地址失效
422927dbe93S猫头猫        if (!lrcUrl) {
423927dbe93S猫头猫            // 插件获得url
424927dbe93S猫头猫            try {
4257a91f04fS猫头猫                let lrcSource;
4267a91f04fS猫头猫                if (from) {
4277a91f04fS猫头猫                    lrcSource = await PluginManager.getByMedia(
4287a91f04fS猫头猫                        musicItem,
4297a91f04fS猫头猫                    )?.instance?.getLyric?.(
430927dbe93S猫头猫                        resetMediaItem(musicItem, undefined, true),
431927dbe93S猫头猫                    );
4327a91f04fS猫头猫                } else {
4337a91f04fS猫头猫                    lrcSource = await this.plugin.instance?.getLyric?.(
4347a91f04fS猫头猫                        resetMediaItem(musicItem, undefined, true),
4357a91f04fS猫头猫                    );
4367a91f04fS猫头猫                }
4377a91f04fS猫头猫
438927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
439927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
440927dbe93S猫头猫            } catch (e: any) {
441927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
442ea6d708fS猫头猫                devLog('error', '插件获取歌词失败', e, e?.message);
443927dbe93S猫头猫            }
444927dbe93S猫头猫        }
445927dbe93S猫头猫        // 5. 最后一次请求
446927dbe93S猫头猫        if (rawLrc || lrcUrl) {
447927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
448927dbe93S猫头猫            if (lrcUrl) {
449927dbe93S猫头猫                try {
45061aca335S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 2000})).data;
451927dbe93S猫头猫                } catch {}
452927dbe93S猫头猫            }
453927dbe93S猫头猫            if (rawLrc) {
454927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
455927dbe93S猫头猫                // 写入缓存
456927dbe93S猫头猫                Cache.update(musicItem, [
4570e4173cdS猫头猫                    [`${internalSerializeKey}.local.localLrc`, filename],
458927dbe93S猫头猫                ]);
459927dbe93S猫头猫                // 如果有meta
460927dbe93S猫头猫                if (meta) {
461927dbe93S猫头猫                    MediaMeta.update(musicItem, [
4620e4173cdS猫头猫                        [`${internalSerializeKey}.local.localLrc`, filename],
463927dbe93S猫头猫                    ]);
464927dbe93S猫头猫                }
465927dbe93S猫头猫                return {
466927dbe93S猫头猫                    rawLrc,
467927dbe93S猫头猫                    lrc: lrcUrl,
468927dbe93S猫头猫                };
469927dbe93S猫头猫            }
470927dbe93S猫头猫        }
4713a6f67b1S猫头猫        // 6. 如果是本地文件
4723a6f67b1S猫头猫        const isDownloaded = LocalMusicSheet.isLocalMusic(musicItem);
4733a6f67b1S猫头猫        if (musicItem.platform !== localPluginPlatform && isDownloaded) {
4743a6f67b1S猫头猫            const res = await localFilePlugin.instance!.getLyric!(isDownloaded);
4753a6f67b1S猫头猫            if (res) {
4763a6f67b1S猫头猫                return res;
4773a6f67b1S猫头猫            }
4783a6f67b1S猫头猫        }
479ea6d708fS猫头猫        devLog('warn', '无歌词');
480927dbe93S猫头猫
481927dbe93S猫头猫        return null;
482927dbe93S猫头猫    }
483927dbe93S猫头猫
484927dbe93S猫头猫    /** 获取歌词文本 */
485927dbe93S猫头猫    async getLyricText(
486927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
487927dbe93S猫头猫    ): Promise<string | undefined> {
488927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
489927dbe93S猫头猫    }
490927dbe93S猫头猫
491927dbe93S猫头猫    /** 获取专辑信息 */
492927dbe93S猫头猫    async getAlbumInfo(
493927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
494f9afcc0dS猫头猫        page: number = 1,
495f9afcc0dS猫头猫    ): Promise<IPlugin.IAlbumInfoResult | null> {
496927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
497f9afcc0dS猫头猫            return {
498f9afcc0dS猫头猫                albumItem,
499f9afcc0dS猫头猫                musicList: albumItem?.musicList ?? [],
500f9afcc0dS猫头猫                isEnd: true,
501f9afcc0dS猫头猫            };
502927dbe93S猫头猫        }
503927dbe93S猫头猫        try {
504927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
505927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
506f9afcc0dS猫头猫                page,
507927dbe93S猫头猫            );
5085276aef9S猫头猫            if (!result) {
5095276aef9S猫头猫                throw new Error();
5105276aef9S猫头猫            }
511927dbe93S猫头猫            result?.musicList?.forEach(_ => {
512927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
51396744680S猫头猫                _.album = albumItem.title;
514927dbe93S猫头猫            });
5155276aef9S猫头猫
516f9afcc0dS猫头猫            if (page <= 1) {
517f9afcc0dS猫头猫                // 合并信息
518f9afcc0dS猫头猫                return {
519f9afcc0dS猫头猫                    albumItem: {...albumItem, ...(result?.albumItem ?? {})},
520f9afcc0dS猫头猫                    isEnd: result.isEnd === false ? false : true,
521f9afcc0dS猫头猫                    musicList: result.musicList,
522f9afcc0dS猫头猫                };
523f9afcc0dS猫头猫            } else {
524f9afcc0dS猫头猫                return {
525f9afcc0dS猫头猫                    isEnd: result.isEnd === false ? false : true,
526f9afcc0dS猫头猫                    musicList: result.musicList,
527f9afcc0dS猫头猫                };
528f9afcc0dS猫头猫            }
5294394410dS猫头猫        } catch (e: any) {
5304394410dS猫头猫            trace('获取专辑信息失败', e?.message);
531ea6d708fS猫头猫            devLog('error', '获取专辑信息失败', e, e?.message);
532ea6d708fS猫头猫
533f9afcc0dS猫头猫            return null;
534927dbe93S猫头猫        }
535927dbe93S猫头猫    }
536927dbe93S猫头猫
5375830c002S猫头猫    /** 获取歌单信息 */
5385830c002S猫头猫    async getMusicSheetInfo(
5395830c002S猫头猫        sheetItem: IMusic.IMusicSheetItem,
5405830c002S猫头猫        page: number = 1,
5415830c002S猫头猫    ): Promise<IPlugin.ISheetInfoResult | null> {
5425281926bS猫头猫        if (!this.plugin.instance.getMusicSheetInfo) {
5435830c002S猫头猫            return {
5445830c002S猫头猫                sheetItem,
5455830c002S猫头猫                musicList: sheetItem?.musicList ?? [],
5465830c002S猫头猫                isEnd: true,
5475830c002S猫头猫            };
5485830c002S猫头猫        }
5495830c002S猫头猫        try {
5505830c002S猫头猫            const result = await this.plugin.instance?.getMusicSheetInfo?.(
5515830c002S猫头猫                resetMediaItem(sheetItem, undefined, true),
5525830c002S猫头猫                page,
5535830c002S猫头猫            );
5545830c002S猫头猫            if (!result) {
5555830c002S猫头猫                throw new Error();
5565830c002S猫头猫            }
5575830c002S猫头猫            result?.musicList?.forEach(_ => {
5585830c002S猫头猫                resetMediaItem(_, this.plugin.name);
5595830c002S猫头猫            });
5605830c002S猫头猫
5615830c002S猫头猫            if (page <= 1) {
5625830c002S猫头猫                // 合并信息
5635830c002S猫头猫                return {
5645830c002S猫头猫                    sheetItem: {...sheetItem, ...(result?.sheetItem ?? {})},
5655830c002S猫头猫                    isEnd: result.isEnd === false ? false : true,
5665830c002S猫头猫                    musicList: result.musicList,
5675830c002S猫头猫                };
5685830c002S猫头猫            } else {
5695830c002S猫头猫                return {
5705830c002S猫头猫                    isEnd: result.isEnd === false ? false : true,
5715830c002S猫头猫                    musicList: result.musicList,
5725830c002S猫头猫                };
5735830c002S猫头猫            }
5745830c002S猫头猫        } catch (e: any) {
5755830c002S猫头猫            trace('获取歌单信息失败', e, e?.message);
5765830c002S猫头猫            devLog('error', '获取歌单信息失败', e, e?.message);
5775830c002S猫头猫
5785830c002S猫头猫            return null;
5795830c002S猫头猫        }
5805830c002S猫头猫    }
5815830c002S猫头猫
582927dbe93S猫头猫    /** 查询作者信息 */
583efb9da24S猫头猫    async getArtistWorks<T extends IArtist.ArtistMediaType>(
584927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
585927dbe93S猫头猫        page: number,
586927dbe93S猫头猫        type: T,
587927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
588efb9da24S猫头猫        if (!this.plugin.instance.getArtistWorks) {
589927dbe93S猫头猫            return {
590927dbe93S猫头猫                isEnd: true,
591927dbe93S猫头猫                data: [],
592927dbe93S猫头猫            };
593927dbe93S猫头猫        }
594927dbe93S猫头猫        try {
595efb9da24S猫头猫            const result = await this.plugin.instance.getArtistWorks(
596927dbe93S猫头猫                artistItem,
597927dbe93S猫头猫                page,
598927dbe93S猫头猫                type,
599927dbe93S猫头猫            );
600927dbe93S猫头猫            if (!result.data) {
601927dbe93S猫头猫                return {
602927dbe93S猫头猫                    isEnd: true,
603927dbe93S猫头猫                    data: [],
604927dbe93S猫头猫                };
605927dbe93S猫头猫            }
606927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
607927dbe93S猫头猫            return {
608927dbe93S猫头猫                isEnd: result.isEnd ?? true,
609927dbe93S猫头猫                data: result.data,
610927dbe93S猫头猫            };
6114394410dS猫头猫        } catch (e: any) {
6124394410dS猫头猫            trace('查询作者信息失败', e?.message);
613ea6d708fS猫头猫            devLog('error', '查询作者信息失败', e, e?.message);
614ea6d708fS猫头猫
615927dbe93S猫头猫            throw e;
616927dbe93S猫头猫        }
617927dbe93S猫头猫    }
61808380090S猫头猫
61908380090S猫头猫    /** 导入歌单 */
62008380090S猫头猫    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
62108380090S猫头猫        try {
62208380090S猫头猫            const result =
62308380090S猫头猫                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
62408380090S猫头猫            result.forEach(_ => resetMediaItem(_, this.plugin.name));
62508380090S猫头猫            return result;
626ea6d708fS猫头猫        } catch (e: any) {
6270e4173cdS猫头猫            console.log(e);
628ea6d708fS猫头猫            devLog('error', '导入歌单失败', e, e?.message);
629ea6d708fS猫头猫
63008380090S猫头猫            return [];
63108380090S猫头猫        }
63208380090S猫头猫    }
6334d9d3c4cS猫头猫    /** 导入单曲 */
6344d9d3c4cS猫头猫    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
6354d9d3c4cS猫头猫        try {
6364d9d3c4cS猫头猫            const result = await this.plugin.instance?.importMusicItem?.(
6374d9d3c4cS猫头猫                urlLike,
6384d9d3c4cS猫头猫            );
6394d9d3c4cS猫头猫            if (!result) {
6404d9d3c4cS猫头猫                throw new Error();
6414d9d3c4cS猫头猫            }
6424d9d3c4cS猫头猫            resetMediaItem(result, this.plugin.name);
6434d9d3c4cS猫头猫            return result;
644ea6d708fS猫头猫        } catch (e: any) {
645ea6d708fS猫头猫            devLog('error', '导入单曲失败', e, e?.message);
646ea6d708fS猫头猫
6474d9d3c4cS猫头猫            return null;
6484d9d3c4cS猫头猫        }
6494d9d3c4cS猫头猫    }
650d52aa40eS猫头猫    /** 获取榜单 */
65192b6c95aS猫头猫    async getTopLists(): Promise<IMusic.IMusicSheetGroupItem[]> {
652d52aa40eS猫头猫        try {
653d52aa40eS猫头猫            const result = await this.plugin.instance?.getTopLists?.();
654d52aa40eS猫头猫            if (!result) {
655d52aa40eS猫头猫                throw new Error();
656d52aa40eS猫头猫            }
657d52aa40eS猫头猫            return result;
658d52aa40eS猫头猫        } catch (e: any) {
659d52aa40eS猫头猫            devLog('error', '获取榜单失败', e, e?.message);
660d52aa40eS猫头猫            return [];
661d52aa40eS猫头猫        }
662d52aa40eS猫头猫    }
663d52aa40eS猫头猫    /** 获取榜单详情 */
664d52aa40eS猫头猫    async getTopListDetail(
66592b6c95aS猫头猫        topListItem: IMusic.IMusicSheetItemBase,
66692b6c95aS猫头猫    ): Promise<ICommon.WithMusicList<IMusic.IMusicSheetItemBase>> {
667d52aa40eS猫头猫        try {
668d52aa40eS猫头猫            const result = await this.plugin.instance?.getTopListDetail?.(
669d52aa40eS猫头猫                topListItem,
670d52aa40eS猫头猫            );
671d52aa40eS猫头猫            if (!result) {
672d52aa40eS猫头猫                throw new Error();
673d52aa40eS猫头猫            }
674d384662fS猫头猫            if (result.musicList) {
675d384662fS猫头猫                result.musicList.forEach(_ =>
676d384662fS猫头猫                    resetMediaItem(_, this.plugin.name),
677d384662fS猫头猫                );
678d384662fS猫头猫            }
679d52aa40eS猫头猫            return result;
680d52aa40eS猫头猫        } catch (e: any) {
681d52aa40eS猫头猫            devLog('error', '获取榜单详情失败', e, e?.message);
682d52aa40eS猫头猫            return {
683d52aa40eS猫头猫                ...topListItem,
684d52aa40eS猫头猫                musicList: [],
685d52aa40eS猫头猫            };
686d52aa40eS猫头猫        }
687d52aa40eS猫头猫    }
688ceb900cdS猫头猫
6895830c002S猫头猫    /** 获取推荐歌单的tag */
690ceb900cdS猫头猫    async getRecommendSheetTags(): Promise<IPlugin.IGetRecommendSheetTagsResult> {
691ceb900cdS猫头猫        try {
692ceb900cdS猫头猫            const result =
693ceb900cdS猫头猫                await this.plugin.instance?.getRecommendSheetTags?.();
694ceb900cdS猫头猫            if (!result) {
695ceb900cdS猫头猫                throw new Error();
696ceb900cdS猫头猫            }
697ceb900cdS猫头猫            return result;
698ceb900cdS猫头猫        } catch (e: any) {
699ceb900cdS猫头猫            devLog('error', '获取推荐歌单失败', e, e?.message);
700ceb900cdS猫头猫            return {
701ceb900cdS猫头猫                data: [],
702ceb900cdS猫头猫            };
703ceb900cdS猫头猫        }
704ceb900cdS猫头猫    }
7055830c002S猫头猫    /** 获取某个tag的推荐歌单 */
706ceb900cdS猫头猫    async getRecommendSheetsByTag(
707ceb900cdS猫头猫        tagItem: ICommon.IUnique,
708ceb900cdS猫头猫        page?: number,
709ceb900cdS猫头猫    ): Promise<ICommon.PaginationResponse<IMusic.IMusicSheetItemBase>> {
710ceb900cdS猫头猫        try {
711ceb900cdS猫头猫            const result =
712ceb900cdS猫头猫                await this.plugin.instance?.getRecommendSheetsByTag?.(
713ceb900cdS猫头猫                    tagItem,
714ceb900cdS猫头猫                    page ?? 1,
715ceb900cdS猫头猫                );
716ceb900cdS猫头猫            if (!result) {
717ceb900cdS猫头猫                throw new Error();
718ceb900cdS猫头猫            }
719ceb900cdS猫头猫            if (result.isEnd !== false) {
720ceb900cdS猫头猫                result.isEnd = true;
721ceb900cdS猫头猫            }
722ceb900cdS猫头猫            if (!result.data) {
723ceb900cdS猫头猫                result.data = [];
724ceb900cdS猫头猫            }
725ceb900cdS猫头猫            result.data.forEach(item => resetMediaItem(item, this.plugin.name));
726ceb900cdS猫头猫
727ceb900cdS猫头猫            return result;
728ceb900cdS猫头猫        } catch (e: any) {
729ceb900cdS猫头猫            devLog('error', '获取推荐歌单详情失败', e, e?.message);
730ceb900cdS猫头猫            return {
731ceb900cdS猫头猫                isEnd: true,
732ceb900cdS猫头猫                data: [],
733ceb900cdS猫头猫            };
734ceb900cdS猫头猫        }
735ceb900cdS猫头猫    }
736927dbe93S猫头猫}
737d5bfeb7eS猫头猫//#endregion
7381a5528a0S猫头猫
739927dbe93S猫头猫let plugins: Array<Plugin> = [];
740927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
74174d0cf81S猫头猫
742d5bfeb7eS猫头猫//#region 本地音乐插件
74374d0cf81S猫头猫/** 本地插件 */
74474d0cf81S猫头猫const localFilePlugin = new Plugin(function () {
7450e4173cdS猫头猫    return {
746d5bfeb7eS猫头猫        platform: localPluginPlatform,
74774d0cf81S猫头猫        _path: '',
74874d0cf81S猫头猫        async getMusicInfo(musicBase) {
74974d0cf81S猫头猫            const localPath = getInternalData<string>(
75074d0cf81S猫头猫                musicBase,
75174d0cf81S猫头猫                InternalDataType.LOCALPATH,
7520e4173cdS猫头猫            );
75374d0cf81S猫头猫            if (localPath) {
75474d0cf81S猫头猫                const coverImg = await Mp3Util.getMediaCoverImg(localPath);
75574d0cf81S猫头猫                return {
75674d0cf81S猫头猫                    artwork: coverImg,
75774d0cf81S猫头猫                };
75874d0cf81S猫头猫            }
75974d0cf81S猫头猫            return null;
76074d0cf81S猫头猫        },
7617993f90eS猫头猫        async getLyric(musicBase) {
7627993f90eS猫头猫            const localPath = getInternalData<string>(
7637993f90eS猫头猫                musicBase,
7647993f90eS猫头猫                InternalDataType.LOCALPATH,
7657993f90eS猫头猫            );
7663a6f67b1S猫头猫            let rawLrc: string | null = null;
7677993f90eS猫头猫            if (localPath) {
7683a6f67b1S猫头猫                // 读取内嵌歌词
7693a6f67b1S猫头猫                try {
7703a6f67b1S猫头猫                    rawLrc = await Mp3Util.getLyric(localPath);
7713a6f67b1S猫头猫                } catch (e) {
7723a6f67b1S猫头猫                    console.log('e', e);
7737993f90eS猫头猫                }
7743a6f67b1S猫头猫                if (!rawLrc) {
7753a6f67b1S猫头猫                    // 读取配置歌词
7763a6f67b1S猫头猫                    const lastDot = localPath.lastIndexOf('.');
7773a6f67b1S猫头猫                    const lrcPath = localPath.slice(0, lastDot) + '.lrc';
7783a6f67b1S猫头猫
7793a6f67b1S猫头猫                    try {
7803a6f67b1S猫头猫                        if (await exists(lrcPath)) {
7813a6f67b1S猫头猫                            rawLrc = await readFile(lrcPath, 'utf8');
7823a6f67b1S猫头猫                        }
7833a6f67b1S猫头猫                    } catch {}
7843a6f67b1S猫头猫                }
7853a6f67b1S猫头猫            }
7863a6f67b1S猫头猫
7873a6f67b1S猫头猫            return rawLrc
7883a6f67b1S猫头猫                ? {
7893a6f67b1S猫头猫                      rawLrc,
7903a6f67b1S猫头猫                  }
7913a6f67b1S猫头猫                : null;
7927993f90eS猫头猫        },
79374d0cf81S猫头猫    };
79474d0cf81S猫头猫}, '');
7957993f90eS猫头猫localFilePlugin.hash = localPluginHash;
796927dbe93S猫头猫
797d5bfeb7eS猫头猫//#endregion
798d5bfeb7eS猫头猫
799927dbe93S猫头猫async function setup() {
800927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
801927dbe93S猫头猫    try {
802927dbe93S猫头猫        // 加载插件
803927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
804927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
805927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
8061e263108S猫头猫            trace('初始化插件', _pluginUrl);
8071e263108S猫头猫            if (
8081e263108S猫头猫                _pluginUrl.isFile() &&
8091e263108S猫头猫                (_pluginUrl.name?.endsWith?.('.js') ||
8101e263108S猫头猫                    _pluginUrl.path?.endsWith?.('.js'))
8111e263108S猫头猫            ) {
812927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
813927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
8144060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
8154060c00aS猫头猫                    p => p.hash === plugin.hash,
8164060c00aS猫头猫                );
817927dbe93S猫头猫                if (_pluginIndex !== -1) {
818927dbe93S猫头猫                    // 重复插件,直接忽略
8190c266394S猫头猫                    continue;
820927dbe93S猫头猫                }
821927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
822927dbe93S猫头猫            }
823927dbe93S猫头猫        }
824927dbe93S猫头猫
825927dbe93S猫头猫        plugins = _plugins;
826927dbe93S猫头猫        pluginStateMapper.notify();
827e08d37a3S猫头猫        /** 初始化meta信息 */
828e08d37a3S猫头猫        PluginMeta.setupMeta(plugins.map(_ => _.name));
829927dbe93S猫头猫    } catch (e: any) {
8304060c00aS猫头猫        ToastAndroid.show(
8314060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
8324060c00aS猫头猫            ToastAndroid.LONG,
8334060c00aS猫头猫        );
8341a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
835927dbe93S猫头猫        throw e;
836927dbe93S猫头猫    }
837927dbe93S猫头猫}
838927dbe93S猫头猫
839927dbe93S猫头猫// 安装插件
840927dbe93S猫头猫async function installPlugin(pluginPath: string) {
84122c09412S猫头猫    // if (pluginPath.endsWith('.js')) {
842927dbe93S猫头猫    const funcCode = await readFile(pluginPath, 'utf8');
843927dbe93S猫头猫    const plugin = new Plugin(funcCode, pluginPath);
844927dbe93S猫头猫    const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
845927dbe93S猫头猫    if (_pluginIndex !== -1) {
8464d9d3c4cS猫头猫        throw new Error('插件已安装');
847927dbe93S猫头猫    }
848927dbe93S猫头猫    if (plugin.hash !== '') {
849927dbe93S猫头猫        const fn = nanoid();
850927dbe93S猫头猫        const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
851927dbe93S猫头猫        await copyFile(pluginPath, _pluginPath);
852927dbe93S猫头猫        plugin.path = _pluginPath;
853927dbe93S猫头猫        plugins = plugins.concat(plugin);
854927dbe93S猫头猫        pluginStateMapper.notify();
8554d9d3c4cS猫头猫        return;
856927dbe93S猫头猫    }
8574d9d3c4cS猫头猫    throw new Error('插件无法解析');
85822c09412S猫头猫    // }
85922c09412S猫头猫    // throw new Error('插件不存在');
860927dbe93S猫头猫}
861927dbe93S猫头猫
86258992c6bS猫头猫async function installPluginFromUrl(url: string) {
86358992c6bS猫头猫    try {
86458992c6bS猫头猫        const funcCode = (await axios.get(url)).data;
86558992c6bS猫头猫        if (funcCode) {
86658992c6bS猫头猫            const plugin = new Plugin(funcCode, '');
86758992c6bS猫头猫            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
86858992c6bS猫头猫            if (_pluginIndex !== -1) {
8698b7ddca8S猫头猫                // 静默忽略
8708b7ddca8S猫头猫                return;
87158992c6bS猫头猫            }
87225c1bd29S猫头猫            const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
87325c1bd29S猫头猫            if (oldVersionPlugin) {
87425c1bd29S猫头猫                if (
87525c1bd29S猫头猫                    compare(
87625c1bd29S猫头猫                        oldVersionPlugin.instance.version ?? '',
87725c1bd29S猫头猫                        plugin.instance.version ?? '',
87825c1bd29S猫头猫                        '>',
87925c1bd29S猫头猫                    )
88025c1bd29S猫头猫                ) {
88125c1bd29S猫头猫                    throw new Error('已安装更新版本的插件');
88225c1bd29S猫头猫                }
88325c1bd29S猫头猫            }
88425c1bd29S猫头猫
88558992c6bS猫头猫            if (plugin.hash !== '') {
88658992c6bS猫头猫                const fn = nanoid();
88758992c6bS猫头猫                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
88858992c6bS猫头猫                await writeFile(_pluginPath, funcCode, 'utf8');
88958992c6bS猫头猫                plugin.path = _pluginPath;
89058992c6bS猫头猫                plugins = plugins.concat(plugin);
89125c1bd29S猫头猫                if (oldVersionPlugin) {
89225c1bd29S猫头猫                    plugins = plugins.filter(
89325c1bd29S猫头猫                        _ => _.hash !== oldVersionPlugin.hash,
89425c1bd29S猫头猫                    );
89525c1bd29S猫头猫                    try {
89625c1bd29S猫头猫                        await unlink(oldVersionPlugin.path);
89725c1bd29S猫头猫                    } catch {}
89825c1bd29S猫头猫                }
89958992c6bS猫头猫                pluginStateMapper.notify();
90058992c6bS猫头猫                return;
90158992c6bS猫头猫            }
90274acbfc0S猫头猫            throw new Error('插件无法解析!');
90358992c6bS猫头猫        }
90425c1bd29S猫头猫    } catch (e: any) {
905ea6d708fS猫头猫        devLog('error', 'URL安装插件失败', e, e?.message);
90658992c6bS猫头猫        errorLog('URL安装插件失败', e);
90725c1bd29S猫头猫        throw new Error(e?.message ?? '');
90858992c6bS猫头猫    }
90958992c6bS猫头猫}
91058992c6bS猫头猫
911927dbe93S猫头猫/** 卸载插件 */
912927dbe93S猫头猫async function uninstallPlugin(hash: string) {
913927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
914927dbe93S猫头猫    if (targetIndex !== -1) {
915927dbe93S猫头猫        try {
91624e5e74aS猫头猫            const pluginName = plugins[targetIndex].name;
917927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
918927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
919927dbe93S猫头猫            pluginStateMapper.notify();
92024e5e74aS猫头猫            if (plugins.every(_ => _.name !== pluginName)) {
92124e5e74aS猫头猫                await MediaMeta.removePlugin(pluginName);
92224e5e74aS猫头猫            }
923927dbe93S猫头猫        } catch {}
924927dbe93S猫头猫    }
925927dbe93S猫头猫}
926927dbe93S猫头猫
92708882a77S猫头猫async function uninstallAllPlugins() {
92808882a77S猫头猫    await Promise.all(
92908882a77S猫头猫        plugins.map(async plugin => {
93008882a77S猫头猫            try {
93108882a77S猫头猫                const pluginName = plugin.name;
93208882a77S猫头猫                await unlink(plugin.path);
93308882a77S猫头猫                await MediaMeta.removePlugin(pluginName);
93408882a77S猫头猫            } catch (e) {}
93508882a77S猫头猫        }),
93608882a77S猫头猫    );
93708882a77S猫头猫    plugins = [];
93808882a77S猫头猫    pluginStateMapper.notify();
939e08d37a3S猫头猫
940e08d37a3S猫头猫    /** 清除空余文件,异步做就可以了 */
941e08d37a3S猫头猫    readDir(pathConst.pluginPath)
942e08d37a3S猫头猫        .then(fns => {
943e08d37a3S猫头猫            fns.forEach(fn => {
944e08d37a3S猫头猫                unlink(fn.path).catch(emptyFunction);
945e08d37a3S猫头猫            });
946e08d37a3S猫头猫        })
947e08d37a3S猫头猫        .catch(emptyFunction);
94808882a77S猫头猫}
94908882a77S猫头猫
95025c1bd29S猫头猫async function updatePlugin(plugin: Plugin) {
95125c1bd29S猫头猫    const updateUrl = plugin.instance.srcUrl;
95225c1bd29S猫头猫    if (!updateUrl) {
95325c1bd29S猫头猫        throw new Error('没有更新源');
95425c1bd29S猫头猫    }
95525c1bd29S猫头猫    try {
95625c1bd29S猫头猫        await installPluginFromUrl(updateUrl);
95725c1bd29S猫头猫    } catch (e: any) {
95825c1bd29S猫头猫        if (e.message === '插件已安装') {
95925c1bd29S猫头猫            throw new Error('当前已是最新版本');
96025c1bd29S猫头猫        } else {
96125c1bd29S猫头猫            throw e;
96225c1bd29S猫头猫        }
96325c1bd29S猫头猫    }
96425c1bd29S猫头猫}
96525c1bd29S猫头猫
966927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
9672c595535S猫头猫    return getByName(mediaItem?.platform);
968927dbe93S猫头猫}
969927dbe93S猫头猫
970927dbe93S猫头猫function getByHash(hash: string) {
9717993f90eS猫头猫    return hash === localPluginHash
9727993f90eS猫头猫        ? localFilePlugin
9737993f90eS猫头猫        : plugins.find(_ => _.hash === hash);
974927dbe93S猫头猫}
975927dbe93S猫头猫
976927dbe93S猫头猫function getByName(name: string) {
9777993f90eS猫头猫    return name === localPluginPlatform
9780e4173cdS猫头猫        ? localFilePlugin
9790e4173cdS猫头猫        : plugins.find(_ => _.name === name);
980927dbe93S猫头猫}
981927dbe93S猫头猫
982927dbe93S猫头猫function getValidPlugins() {
983927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
984927dbe93S猫头猫}
985927dbe93S猫头猫
9862b80a429S猫头猫function getSearchablePlugins(supportedSearchType?: ICommon.SupportMediaType) {
9872b80a429S猫头猫    return plugins.filter(
9882b80a429S猫头猫        _ =>
9892b80a429S猫头猫            _.state === 'enabled' &&
9902b80a429S猫头猫            _.instance.search &&
99139ac60f7S猫头猫            (supportedSearchType && _.instance.supportedSearchType
99239ac60f7S猫头猫                ? _.instance.supportedSearchType.includes(supportedSearchType)
9932b80a429S猫头猫                : true),
9942b80a429S猫头猫    );
995efb9da24S猫头猫}
996efb9da24S猫头猫
9972b80a429S猫头猫function getSortedSearchablePlugins(
9982b80a429S猫头猫    supportedSearchType?: ICommon.SupportMediaType,
9992b80a429S猫头猫) {
10002b80a429S猫头猫    return getSearchablePlugins(supportedSearchType).sort((a, b) =>
1001e08d37a3S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
1002e08d37a3S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
1003e08d37a3S猫头猫        0
1004e08d37a3S猫头猫            ? -1
1005e08d37a3S猫头猫            : 1,
1006e08d37a3S猫头猫    );
1007e08d37a3S猫头猫}
1008e08d37a3S猫头猫
100915feccc1S猫头猫function getTopListsablePlugins() {
101015feccc1S猫头猫    return plugins.filter(_ => _.state === 'enabled' && _.instance.getTopLists);
101115feccc1S猫头猫}
101215feccc1S猫头猫
101315feccc1S猫头猫function getSortedTopListsablePlugins() {
101415feccc1S猫头猫    return getTopListsablePlugins().sort((a, b) =>
101515feccc1S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
101615feccc1S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
101715feccc1S猫头猫        0
101815feccc1S猫头猫            ? -1
101915feccc1S猫头猫            : 1,
102015feccc1S猫头猫    );
102115feccc1S猫头猫}
102215feccc1S猫头猫
1023ceb900cdS猫头猫function getRecommendSheetablePlugins() {
1024ceb900cdS猫头猫    return plugins.filter(
1025ceb900cdS猫头猫        _ => _.state === 'enabled' && _.instance.getRecommendSheetsByTag,
1026ceb900cdS猫头猫    );
1027ceb900cdS猫头猫}
1028ceb900cdS猫头猫
1029ceb900cdS猫头猫function getSortedRecommendSheetablePlugins() {
1030ceb900cdS猫头猫    return getRecommendSheetablePlugins().sort((a, b) =>
1031ceb900cdS猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
1032ceb900cdS猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
1033ceb900cdS猫头猫        0
1034ceb900cdS猫头猫            ? -1
1035ceb900cdS猫头猫            : 1,
1036ceb900cdS猫头猫    );
1037ceb900cdS猫头猫}
1038ceb900cdS猫头猫
1039e08d37a3S猫头猫function useSortedPlugins() {
1040e08d37a3S猫头猫    const _plugins = pluginStateMapper.useMappedState();
1041e08d37a3S猫头猫    const _pluginMetaAll = PluginMeta.usePluginMetaAll();
1042e08d37a3S猫头猫
104334588741S猫头猫    const [sortedPlugins, setSortedPlugins] = useState(
104434588741S猫头猫        [..._plugins].sort((a, b) =>
1045e08d37a3S猫头猫            (_pluginMetaAll[a.name]?.order ?? Infinity) -
1046e08d37a3S猫头猫                (_pluginMetaAll[b.name]?.order ?? Infinity) <
1047e08d37a3S猫头猫            0
1048e08d37a3S猫头猫                ? -1
1049e08d37a3S猫头猫                : 1,
105034588741S猫头猫        ),
1051e08d37a3S猫头猫    );
105234588741S猫头猫
105334588741S猫头猫    useEffect(() => {
1054d4cd40d8S猫头猫        InteractionManager.runAfterInteractions(() => {
105534588741S猫头猫            setSortedPlugins(
105634588741S猫头猫                [..._plugins].sort((a, b) =>
105734588741S猫头猫                    (_pluginMetaAll[a.name]?.order ?? Infinity) -
105834588741S猫头猫                        (_pluginMetaAll[b.name]?.order ?? Infinity) <
105934588741S猫头猫                    0
106034588741S猫头猫                        ? -1
106134588741S猫头猫                        : 1,
106234588741S猫头猫                ),
106334588741S猫头猫            );
1064d4cd40d8S猫头猫        });
106534588741S猫头猫    }, [_plugins, _pluginMetaAll]);
106634588741S猫头猫
106734588741S猫头猫    return sortedPlugins;
1068e08d37a3S猫头猫}
1069e08d37a3S猫头猫
1070927dbe93S猫头猫const PluginManager = {
1071927dbe93S猫头猫    setup,
1072927dbe93S猫头猫    installPlugin,
107358992c6bS猫头猫    installPluginFromUrl,
107425c1bd29S猫头猫    updatePlugin,
1075927dbe93S猫头猫    uninstallPlugin,
1076927dbe93S猫头猫    getByMedia,
1077927dbe93S猫头猫    getByHash,
1078927dbe93S猫头猫    getByName,
1079927dbe93S猫头猫    getValidPlugins,
1080efb9da24S猫头猫    getSearchablePlugins,
1081e08d37a3S猫头猫    getSortedSearchablePlugins,
108215feccc1S猫头猫    getTopListsablePlugins,
1083ceb900cdS猫头猫    getSortedRecommendSheetablePlugins,
108415feccc1S猫头猫    getSortedTopListsablePlugins,
10855276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
1086e08d37a3S猫头猫    useSortedPlugins,
108708882a77S猫头猫    uninstallAllPlugins,
10885276aef9S猫头猫};
1089927dbe93S猫头猫
1090927dbe93S猫头猫export default PluginManager;
1091