xref: /MusicFree/src/core/pluginManager.ts (revision 34588741f7af4f0b6c513ac5f3230911679b5d3e)
14060c00aS猫头猫import {
2927dbe93S猫头猫    copyFile,
3927dbe93S猫头猫    exists,
4927dbe93S猫头猫    readDir,
5927dbe93S猫头猫    readFile,
6927dbe93S猫头猫    unlink,
7927dbe93S猫头猫    writeFile,
8927dbe93S猫头猫} from 'react-native-fs';
9927dbe93S猫头猫import CryptoJs from 'crypto-js';
10927dbe93S猫头猫import dayjs from 'dayjs';
11927dbe93S猫头猫import axios from 'axios';
12ef60be1cS猫头猫import bigInt from 'big-integer';
13ef60be1cS猫头猫import qs from 'qs';
14927dbe93S猫头猫import {ToastAndroid} from 'react-native';
15927dbe93S猫头猫import pathConst from '@/constants/pathConst';
1625c1bd29S猫头猫import {compare, satisfies} from 'compare-versions';
17927dbe93S猫头猫import DeviceInfo from 'react-native-device-info';
18927dbe93S猫头猫import StateMapper from '@/utils/stateMapper';
19927dbe93S猫头猫import MediaMeta from './mediaMeta';
20927dbe93S猫头猫import {nanoid} from 'nanoid';
21927dbe93S猫头猫import {errorLog, trace} from '../utils/log';
22927dbe93S猫头猫import Cache from './cache';
23cfa0fc07S猫头猫import {
240e4173cdS猫头猫    getInternalData,
250e4173cdS猫头猫    InternalDataType,
260e4173cdS猫头猫    isSameMediaItem,
270e4173cdS猫头猫    resetMediaItem,
280e4173cdS猫头猫} from '@/utils/mediaItem';
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';
45*34588741S猫头猫import {useEffect, useState} from 'react';
46927dbe93S猫头猫
47927dbe93S猫头猫axios.defaults.timeout = 1500;
48927dbe93S猫头猫
49927dbe93S猫头猫const sha256 = CryptoJs.SHA256;
50927dbe93S猫头猫
51cfa0fc07S猫头猫export enum PluginStateCode {
52927dbe93S猫头猫    /** 版本不匹配 */
53927dbe93S猫头猫    VersionNotMatch = 'VERSION NOT MATCH',
54927dbe93S猫头猫    /** 无法解析 */
55927dbe93S猫头猫    CannotParse = 'CANNOT PARSE',
56927dbe93S猫头猫}
57927dbe93S猫头猫
58d5bfeb7eS猫头猫//#region 插件类
59927dbe93S猫头猫export class Plugin {
60927dbe93S猫头猫    /** 插件名 */
61927dbe93S猫头猫    public name: string;
62927dbe93S猫头猫    /** 插件的hash,作为唯一id */
63927dbe93S猫头猫    public hash: string;
64927dbe93S猫头猫    /** 插件状态:激活、关闭、错误 */
65927dbe93S猫头猫    public state: 'enabled' | 'disabled' | 'error';
66927dbe93S猫头猫    /** 插件支持的搜索类型 */
67927dbe93S猫头猫    public supportedSearchType?: string;
68927dbe93S猫头猫    /** 插件状态信息 */
69927dbe93S猫头猫    public stateCode?: PluginStateCode;
70927dbe93S猫头猫    /** 插件的实例 */
71927dbe93S猫头猫    public instance: IPlugin.IPluginInstance;
72927dbe93S猫头猫    /** 插件路径 */
73927dbe93S猫头猫    public path: string;
74927dbe93S猫头猫    /** 插件方法 */
75927dbe93S猫头猫    public methods: PluginMethods;
76d5bfeb7eS猫头猫    /** 用户输入 */
77d5bfeb7eS猫头猫    public userEnv?: Record<string, string>;
78927dbe93S猫头猫
7974d0cf81S猫头猫    constructor(
8074d0cf81S猫头猫        funcCode: string | (() => IPlugin.IPluginInstance),
8174d0cf81S猫头猫        pluginPath: string,
8274d0cf81S猫头猫    ) {
83927dbe93S猫头猫        this.state = 'enabled';
84927dbe93S猫头猫        let _instance: IPlugin.IPluginInstance;
85927dbe93S猫头猫        try {
8674d0cf81S猫头猫            if (typeof funcCode === 'string') {
874060c00aS猫头猫                // eslint-disable-next-line no-new-func
88927dbe93S猫头猫                _instance = Function(`
89927dbe93S猫头猫            'use strict';
90927dbe93S猫头猫            try {
91927dbe93S猫头猫              return ${funcCode};
92927dbe93S猫头猫            } catch(e) {
93927dbe93S猫头猫              return null;
94927dbe93S猫头猫            }
957d7e864fS猫头猫          `)()({
967d7e864fS猫头猫                    CryptoJs,
977d7e864fS猫头猫                    axios,
987d7e864fS猫头猫                    dayjs,
997d7e864fS猫头猫                    cheerio,
1007d7e864fS猫头猫                    bigInt,
1017d7e864fS猫头猫                    qs,
1027d7e864fS猫头猫                    he,
1037d7e864fS猫头猫                    CookieManager: {
1047d7e864fS猫头猫                        flush: CookieManager.flush,
1057d7e864fS猫头猫                        get: CookieManager.get,
1067d7e864fS猫头猫                    },
1077d7e864fS猫头猫                });
10874d0cf81S猫头猫            } else {
10974d0cf81S猫头猫                _instance = funcCode();
11074d0cf81S猫头猫            }
111927dbe93S猫头猫            this.checkValid(_instance);
112927dbe93S猫头猫        } catch (e: any) {
113927dbe93S猫头猫            this.state = 'error';
114927dbe93S猫头猫            this.stateCode = PluginStateCode.CannotParse;
115927dbe93S猫头猫            if (e?.stateCode) {
116927dbe93S猫头猫                this.stateCode = e.stateCode;
117927dbe93S猫头猫            }
118927dbe93S猫头猫            errorLog(`${pluginPath}插件无法解析 `, {
119927dbe93S猫头猫                stateCode: this.stateCode,
120927dbe93S猫头猫                message: e?.message,
121927dbe93S猫头猫                stack: e?.stack,
122927dbe93S猫头猫            });
123927dbe93S猫头猫            _instance = e?.instance ?? {
124927dbe93S猫头猫                _path: '',
125927dbe93S猫头猫                platform: '',
126927dbe93S猫头猫                appVersion: '',
12720e6a092S猫头猫                async getMediaSource() {
128927dbe93S猫头猫                    return null;
129927dbe93S猫头猫                },
130927dbe93S猫头猫                async search() {
131927dbe93S猫头猫                    return {};
132927dbe93S猫头猫                },
133927dbe93S猫头猫                async getAlbumInfo() {
134927dbe93S猫头猫                    return null;
135927dbe93S猫头猫                },
136927dbe93S猫头猫            };
137927dbe93S猫头猫        }
138927dbe93S猫头猫        this.instance = _instance;
139927dbe93S猫头猫        this.path = pluginPath;
140927dbe93S猫头猫        this.name = _instance.platform;
141927dbe93S猫头猫        if (this.instance.platform === '') {
142927dbe93S猫头猫            this.hash = '';
143927dbe93S猫头猫        } else {
14474d0cf81S猫头猫            if (typeof funcCode === 'string') {
145927dbe93S猫头猫                this.hash = sha256(funcCode).toString();
14674d0cf81S猫头猫            } else {
14774d0cf81S猫头猫                this.hash = sha256(funcCode.toString()).toString();
14874d0cf81S猫头猫            }
149927dbe93S猫头猫        }
150927dbe93S猫头猫
151927dbe93S猫头猫        // 放在最后
152927dbe93S猫头猫        this.methods = new PluginMethods(this);
153927dbe93S猫头猫    }
154927dbe93S猫头猫
155927dbe93S猫头猫    private checkValid(_instance: IPlugin.IPluginInstance) {
156927dbe93S猫头猫        /** 版本号校验 */
157927dbe93S猫头猫        if (
158927dbe93S猫头猫            _instance.appVersion &&
159927dbe93S猫头猫            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
160927dbe93S猫头猫        ) {
161927dbe93S猫头猫            throw {
162927dbe93S猫头猫                instance: _instance,
163927dbe93S猫头猫                stateCode: PluginStateCode.VersionNotMatch,
164927dbe93S猫头猫            };
165927dbe93S猫头猫        }
166927dbe93S猫头猫        return true;
167927dbe93S猫头猫    }
168927dbe93S猫头猫}
169d5bfeb7eS猫头猫//#endregion
170927dbe93S猫头猫
171d5bfeb7eS猫头猫//#region 基于插件类封装的方法,供给APP侧直接调用
172927dbe93S猫头猫/** 有缓存等信息 */
173927dbe93S猫头猫class PluginMethods implements IPlugin.IPluginInstanceMethods {
174927dbe93S猫头猫    private plugin;
175927dbe93S猫头猫    constructor(plugin: Plugin) {
176927dbe93S猫头猫        this.plugin = plugin;
177927dbe93S猫头猫    }
178927dbe93S猫头猫    /** 搜索 */
179927dbe93S猫头猫    async search<T extends ICommon.SupportMediaType>(
180927dbe93S猫头猫        query: string,
181927dbe93S猫头猫        page: number,
182927dbe93S猫头猫        type: T,
183927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
184927dbe93S猫头猫        if (!this.plugin.instance.search) {
185927dbe93S猫头猫            return {
186927dbe93S猫头猫                isEnd: true,
187927dbe93S猫头猫                data: [],
188927dbe93S猫头猫            };
189927dbe93S猫头猫        }
190927dbe93S猫头猫
1914060c00aS猫头猫        const result =
1924060c00aS猫头猫            (await this.plugin.instance.search(query, page, type)) ?? {};
193927dbe93S猫头猫        if (Array.isArray(result.data)) {
194927dbe93S猫头猫            result.data.forEach(_ => {
195927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
196927dbe93S猫头猫            });
197927dbe93S猫头猫            return {
198927dbe93S猫头猫                isEnd: result.isEnd ?? true,
199927dbe93S猫头猫                data: result.data,
200927dbe93S猫头猫            };
201927dbe93S猫头猫        }
202927dbe93S猫头猫        return {
203927dbe93S猫头猫            isEnd: true,
204927dbe93S猫头猫            data: [],
205927dbe93S猫头猫        };
206927dbe93S猫头猫    }
207927dbe93S猫头猫
208927dbe93S猫头猫    /** 获取真实源 */
20920e6a092S猫头猫    async getMediaSource(
210927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
211927dbe93S猫头猫        retryCount = 1,
21220e6a092S猫头猫    ): Promise<IPlugin.IMediaSourceResult> {
213927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
214927dbe93S猫头猫        const localPath =
2150e4173cdS猫头猫            getInternalData<string>(musicItem, InternalDataType.LOCALPATH) ??
2160e4173cdS猫头猫            getInternalData<string>(
2170e4173cdS猫头猫                LocalMusicSheet.isLocalMusic(musicItem),
2180e4173cdS猫头猫                InternalDataType.LOCALPATH,
2190e4173cdS猫头猫            );
2200e4173cdS猫头猫        if (localPath && (await FileSystem.exists(localPath))) {
2210e4173cdS猫头猫            trace('本地播放', localPath);
222927dbe93S猫头猫            return {
223927dbe93S猫头猫                url: localPath,
224927dbe93S猫头猫            };
225927dbe93S猫头猫        }
2267993f90eS猫头猫        if (musicItem.platform === localPluginPlatform) {
227f5935920S猫头猫            throw new Error('本地音乐不存在');
228f5935920S猫头猫        }
229927dbe93S猫头猫        // 2. 缓存播放
230927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
231985f8e75S猫头猫        const pluginCacheControl =
232985f8e75S猫头猫            this.plugin.instance.cacheControl ?? 'no-cache';
233cfa0fc07S猫头猫        if (
234cfa0fc07S猫头猫            mediaCache &&
235cfa0fc07S猫头猫            mediaCache?.url &&
23648f4b873S猫头猫            (pluginCacheControl === CacheControl.Cache ||
23748f4b873S猫头猫                (pluginCacheControl === CacheControl.NoCache &&
238ef714860S猫头猫                    Network.isOffline()))
239cfa0fc07S猫头猫        ) {
2405276aef9S猫头猫            trace('播放', '缓存播放');
241927dbe93S猫头猫            return {
242927dbe93S猫头猫                url: mediaCache.url,
243927dbe93S猫头猫                headers: mediaCache.headers,
2444060c00aS猫头猫                userAgent:
2454060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
246927dbe93S猫头猫            };
247927dbe93S猫头猫        }
248927dbe93S猫头猫        // 3. 插件解析
24920e6a092S猫头猫        if (!this.plugin.instance.getMediaSource) {
250927dbe93S猫头猫            return {url: musicItem.url};
251927dbe93S猫头猫        }
252927dbe93S猫头猫        try {
25348f4b873S猫头猫            const {url, headers} =
25420e6a092S猫头猫                (await this.plugin.instance.getMediaSource(musicItem)) ?? {};
255927dbe93S猫头猫            if (!url) {
256927dbe93S猫头猫                throw new Error();
257927dbe93S猫头猫            }
2585276aef9S猫头猫            trace('播放', '插件播放');
259927dbe93S猫头猫            const result = {
260927dbe93S猫头猫                url,
261927dbe93S猫头猫                headers,
262927dbe93S猫头猫                userAgent: headers?.['user-agent'],
263cfa0fc07S猫头猫            } as IPlugin.IMediaSourceResult;
264927dbe93S猫头猫
26548f4b873S猫头猫            if (pluginCacheControl !== CacheControl.NoStore) {
266927dbe93S猫头猫                Cache.update(musicItem, result);
267752ffc5aS猫头猫            }
268cfa0fc07S猫头猫
269927dbe93S猫头猫            return result;
270927dbe93S猫头猫        } catch (e: any) {
271927dbe93S猫头猫            if (retryCount > 0) {
272927dbe93S猫头猫                await delay(150);
27320e6a092S猫头猫                return this.getMediaSource(musicItem, --retryCount);
274927dbe93S猫头猫            }
275927dbe93S猫头猫            errorLog('获取真实源失败', e?.message);
276927dbe93S猫头猫            throw e;
277927dbe93S猫头猫        }
278927dbe93S猫头猫    }
279927dbe93S猫头猫
280927dbe93S猫头猫    /** 获取音乐详情 */
281927dbe93S猫头猫    async getMusicInfo(
282927dbe93S猫头猫        musicItem: ICommon.IMediaBase,
28374d0cf81S猫头猫    ): Promise<Partial<IMusic.IMusicItem> | null> {
284927dbe93S猫头猫        if (!this.plugin.instance.getMusicInfo) {
28574d0cf81S猫头猫            return {};
286927dbe93S猫头猫        }
28774d0cf81S猫头猫        try {
288927dbe93S猫头猫            return (
289927dbe93S猫头猫                this.plugin.instance.getMusicInfo(
2907993f90eS猫头猫                    resetMediaItem(musicItem, undefined, true),
29174d0cf81S猫头猫                ) ?? {}
292927dbe93S猫头猫            );
29374d0cf81S猫头猫        } catch (e) {
29474d0cf81S猫头猫            return {};
29574d0cf81S猫头猫        }
296927dbe93S猫头猫    }
297927dbe93S猫头猫
298927dbe93S猫头猫    /** 获取歌词 */
299927dbe93S猫头猫    async getLyric(
300927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
301927dbe93S猫头猫        from?: IMusic.IMusicItemBase,
302927dbe93S猫头猫    ): Promise<ILyric.ILyricSource | null> {
303927dbe93S猫头猫        // 1.额外存储的meta信息
304927dbe93S猫头猫        const meta = MediaMeta.get(musicItem);
305927dbe93S猫头猫        if (meta && meta.associatedLrc) {
306927dbe93S猫头猫            // 有关联歌词
307927dbe93S猫头猫            if (
308927dbe93S猫头猫                isSameMediaItem(musicItem, from) ||
309927dbe93S猫头猫                isSameMediaItem(meta.associatedLrc, musicItem)
310927dbe93S猫头猫            ) {
311927dbe93S猫头猫                // 形成环路,断开当前的环
312927dbe93S猫头猫                await MediaMeta.update(musicItem, {
313927dbe93S猫头猫                    associatedLrc: undefined,
314927dbe93S猫头猫                });
315927dbe93S猫头猫                // 无歌词
316927dbe93S猫头猫                return null;
317927dbe93S猫头猫            }
318927dbe93S猫头猫            // 获取关联歌词
3197a91f04fS猫头猫            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
3204060c00aS猫头猫            const result = await this.getLyric(
3217a91f04fS猫头猫                {...meta.associatedLrc, ...associatedMeta},
3224060c00aS猫头猫                from ?? musicItem,
3234060c00aS猫头猫            );
324927dbe93S猫头猫            if (result) {
325927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
326927dbe93S猫头猫                return result;
327927dbe93S猫头猫            }
328927dbe93S猫头猫        }
329927dbe93S猫头猫        const cache = Cache.get(musicItem);
330927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
331927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
332927dbe93S猫头猫        // 如果存在文本
333927dbe93S猫头猫        if (rawLrc) {
334927dbe93S猫头猫            return {
335927dbe93S猫头猫                rawLrc,
336927dbe93S猫头猫                lrc: lrcUrl,
337927dbe93S猫头猫            };
338927dbe93S猫头猫        }
339927dbe93S猫头猫        // 2.本地缓存
340927dbe93S猫头猫        const localLrc =
3410e4173cdS猫头猫            meta?.[internalSerializeKey]?.local?.localLrc ||
3420e4173cdS猫头猫            cache?.[internalSerializeKey]?.local?.localLrc;
343927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
344927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
345927dbe93S猫头猫            return {
346927dbe93S猫头猫                rawLrc,
347927dbe93S猫头猫                lrc: lrcUrl,
348927dbe93S猫头猫            };
349927dbe93S猫头猫        }
350927dbe93S猫头猫        // 3.优先使用url
351927dbe93S猫头猫        if (lrcUrl) {
352927dbe93S猫头猫            try {
353927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
3542a3194f5S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
355927dbe93S猫头猫                return {
356927dbe93S猫头猫                    rawLrc,
357927dbe93S猫头猫                    lrc: lrcUrl,
358927dbe93S猫头猫                };
359927dbe93S猫头猫            } catch {
360927dbe93S猫头猫                lrcUrl = undefined;
361927dbe93S猫头猫            }
362927dbe93S猫头猫        }
363927dbe93S猫头猫        // 4. 如果地址失效
364927dbe93S猫头猫        if (!lrcUrl) {
365927dbe93S猫头猫            // 插件获得url
366927dbe93S猫头猫            try {
3677a91f04fS猫头猫                let lrcSource;
3687a91f04fS猫头猫                if (from) {
3697a91f04fS猫头猫                    lrcSource = await PluginManager.getByMedia(
3707a91f04fS猫头猫                        musicItem,
3717a91f04fS猫头猫                    )?.instance?.getLyric?.(
372927dbe93S猫头猫                        resetMediaItem(musicItem, undefined, true),
373927dbe93S猫头猫                    );
3747a91f04fS猫头猫                } else {
3757a91f04fS猫头猫                    lrcSource = await this.plugin.instance?.getLyric?.(
3767a91f04fS猫头猫                        resetMediaItem(musicItem, undefined, true),
3777a91f04fS猫头猫                    );
3787a91f04fS猫头猫                }
3797a91f04fS猫头猫
380927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
381927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
382927dbe93S猫头猫            } catch (e: any) {
383927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
384927dbe93S猫头猫            }
385927dbe93S猫头猫        }
386927dbe93S猫头猫        // 5. 最后一次请求
387927dbe93S猫头猫        if (rawLrc || lrcUrl) {
388927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
389927dbe93S猫头猫            if (lrcUrl) {
390927dbe93S猫头猫                try {
3912a3194f5S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
392927dbe93S猫头猫                } catch {}
393927dbe93S猫头猫            }
394927dbe93S猫头猫            if (rawLrc) {
395927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
396927dbe93S猫头猫                // 写入缓存
397927dbe93S猫头猫                Cache.update(musicItem, [
3980e4173cdS猫头猫                    [`${internalSerializeKey}.local.localLrc`, filename],
399927dbe93S猫头猫                ]);
400927dbe93S猫头猫                // 如果有meta
401927dbe93S猫头猫                if (meta) {
402927dbe93S猫头猫                    MediaMeta.update(musicItem, [
4030e4173cdS猫头猫                        [`${internalSerializeKey}.local.localLrc`, filename],
404927dbe93S猫头猫                    ]);
405927dbe93S猫头猫                }
406927dbe93S猫头猫                return {
407927dbe93S猫头猫                    rawLrc,
408927dbe93S猫头猫                    lrc: lrcUrl,
409927dbe93S猫头猫                };
410927dbe93S猫头猫            }
411927dbe93S猫头猫        }
412927dbe93S猫头猫
413927dbe93S猫头猫        return null;
414927dbe93S猫头猫    }
415927dbe93S猫头猫
416927dbe93S猫头猫    /** 获取歌词文本 */
417927dbe93S猫头猫    async getLyricText(
418927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
419927dbe93S猫头猫    ): Promise<string | undefined> {
420927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
421927dbe93S猫头猫    }
422927dbe93S猫头猫
423927dbe93S猫头猫    /** 获取专辑信息 */
424927dbe93S猫头猫    async getAlbumInfo(
425927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
426927dbe93S猫头猫    ): Promise<IAlbum.IAlbumItem | null> {
427927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
428927dbe93S猫头猫            return {...albumItem, musicList: []};
429927dbe93S猫头猫        }
430927dbe93S猫头猫        try {
431927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
432927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
433927dbe93S猫头猫            );
4345276aef9S猫头猫            if (!result) {
4355276aef9S猫头猫                throw new Error();
4365276aef9S猫头猫            }
437927dbe93S猫头猫            result?.musicList?.forEach(_ => {
438927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
439927dbe93S猫头猫            });
4405276aef9S猫头猫
4415276aef9S猫头猫            return {...albumItem, ...result};
4424394410dS猫头猫        } catch (e: any) {
4434394410dS猫头猫            trace('获取专辑信息失败', e?.message);
444927dbe93S猫头猫            return {...albumItem, musicList: []};
445927dbe93S猫头猫        }
446927dbe93S猫头猫    }
447927dbe93S猫头猫
448927dbe93S猫头猫    /** 查询作者信息 */
449efb9da24S猫头猫    async getArtistWorks<T extends IArtist.ArtistMediaType>(
450927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
451927dbe93S猫头猫        page: number,
452927dbe93S猫头猫        type: T,
453927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
454efb9da24S猫头猫        if (!this.plugin.instance.getArtistWorks) {
455927dbe93S猫头猫            return {
456927dbe93S猫头猫                isEnd: true,
457927dbe93S猫头猫                data: [],
458927dbe93S猫头猫            };
459927dbe93S猫头猫        }
460927dbe93S猫头猫        try {
461efb9da24S猫头猫            const result = await this.plugin.instance.getArtistWorks(
462927dbe93S猫头猫                artistItem,
463927dbe93S猫头猫                page,
464927dbe93S猫头猫                type,
465927dbe93S猫头猫            );
466927dbe93S猫头猫            if (!result.data) {
467927dbe93S猫头猫                return {
468927dbe93S猫头猫                    isEnd: true,
469927dbe93S猫头猫                    data: [],
470927dbe93S猫头猫                };
471927dbe93S猫头猫            }
472927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
473927dbe93S猫头猫            return {
474927dbe93S猫头猫                isEnd: result.isEnd ?? true,
475927dbe93S猫头猫                data: result.data,
476927dbe93S猫头猫            };
4774394410dS猫头猫        } catch (e: any) {
4784394410dS猫头猫            trace('查询作者信息失败', e?.message);
479927dbe93S猫头猫            throw e;
480927dbe93S猫头猫        }
481927dbe93S猫头猫    }
48208380090S猫头猫
48308380090S猫头猫    /** 导入歌单 */
48408380090S猫头猫    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
48508380090S猫头猫        try {
48608380090S猫头猫            const result =
48708380090S猫头猫                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
48808380090S猫头猫            result.forEach(_ => resetMediaItem(_, this.plugin.name));
48908380090S猫头猫            return result;
4900e4173cdS猫头猫        } catch (e) {
4910e4173cdS猫头猫            console.log(e);
49208380090S猫头猫            return [];
49308380090S猫头猫        }
49408380090S猫头猫    }
4954d9d3c4cS猫头猫    /** 导入单曲 */
4964d9d3c4cS猫头猫    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
4974d9d3c4cS猫头猫        try {
4984d9d3c4cS猫头猫            const result = await this.plugin.instance?.importMusicItem?.(
4994d9d3c4cS猫头猫                urlLike,
5004d9d3c4cS猫头猫            );
5014d9d3c4cS猫头猫            if (!result) {
5024d9d3c4cS猫头猫                throw new Error();
5034d9d3c4cS猫头猫            }
5044d9d3c4cS猫头猫            resetMediaItem(result, this.plugin.name);
5054d9d3c4cS猫头猫            return result;
5064d9d3c4cS猫头猫        } catch {
5074d9d3c4cS猫头猫            return null;
5084d9d3c4cS猫头猫        }
5094d9d3c4cS猫头猫    }
510927dbe93S猫头猫}
511d5bfeb7eS猫头猫//#endregion
5121a5528a0S猫头猫
513927dbe93S猫头猫let plugins: Array<Plugin> = [];
514927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
51574d0cf81S猫头猫
516d5bfeb7eS猫头猫//#region 本地音乐插件
51774d0cf81S猫头猫/** 本地插件 */
51874d0cf81S猫头猫const localFilePlugin = new Plugin(function () {
5190e4173cdS猫头猫    return {
520d5bfeb7eS猫头猫        platform: localPluginPlatform,
52174d0cf81S猫头猫        _path: '',
52274d0cf81S猫头猫        async getMusicInfo(musicBase) {
52374d0cf81S猫头猫            const localPath = getInternalData<string>(
52474d0cf81S猫头猫                musicBase,
52574d0cf81S猫头猫                InternalDataType.LOCALPATH,
5260e4173cdS猫头猫            );
52774d0cf81S猫头猫            if (localPath) {
52874d0cf81S猫头猫                const coverImg = await Mp3Util.getMediaCoverImg(localPath);
52974d0cf81S猫头猫                return {
53074d0cf81S猫头猫                    artwork: coverImg,
53174d0cf81S猫头猫                };
53274d0cf81S猫头猫            }
53374d0cf81S猫头猫            return null;
53474d0cf81S猫头猫        },
5357993f90eS猫头猫        async getLyric(musicBase) {
5367993f90eS猫头猫            const localPath = getInternalData<string>(
5377993f90eS猫头猫                musicBase,
5387993f90eS猫头猫                InternalDataType.LOCALPATH,
5397993f90eS猫头猫            );
5407993f90eS猫头猫            if (localPath) {
5417993f90eS猫头猫                const rawLrc = await Mp3Util.getLyric(localPath);
5427993f90eS猫头猫                return {
5437993f90eS猫头猫                    rawLrc,
5447993f90eS猫头猫                };
5457993f90eS猫头猫            }
5467993f90eS猫头猫            return null;
5477993f90eS猫头猫        },
54874d0cf81S猫头猫    };
54974d0cf81S猫头猫}, '');
5507993f90eS猫头猫localFilePlugin.hash = localPluginHash;
551927dbe93S猫头猫
552d5bfeb7eS猫头猫//#endregion
553d5bfeb7eS猫头猫
554927dbe93S猫头猫async function setup() {
555927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
556927dbe93S猫头猫    try {
557927dbe93S猫头猫        // 加载插件
558927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
559927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
560927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
5611e263108S猫头猫            trace('初始化插件', _pluginUrl);
5621e263108S猫头猫            if (
5631e263108S猫头猫                _pluginUrl.isFile() &&
5641e263108S猫头猫                (_pluginUrl.name?.endsWith?.('.js') ||
5651e263108S猫头猫                    _pluginUrl.path?.endsWith?.('.js'))
5661e263108S猫头猫            ) {
567927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
568927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
5694060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
5704060c00aS猫头猫                    p => p.hash === plugin.hash,
5714060c00aS猫头猫                );
572927dbe93S猫头猫                if (_pluginIndex !== -1) {
573927dbe93S猫头猫                    // 重复插件,直接忽略
574927dbe93S猫头猫                    return;
575927dbe93S猫头猫                }
576927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
577927dbe93S猫头猫            }
578927dbe93S猫头猫        }
579927dbe93S猫头猫
580927dbe93S猫头猫        plugins = _plugins;
581927dbe93S猫头猫        pluginStateMapper.notify();
582e08d37a3S猫头猫        /** 初始化meta信息 */
583e08d37a3S猫头猫        PluginMeta.setupMeta(plugins.map(_ => _.name));
584927dbe93S猫头猫    } catch (e: any) {
5854060c00aS猫头猫        ToastAndroid.show(
5864060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
5874060c00aS猫头猫            ToastAndroid.LONG,
5884060c00aS猫头猫        );
5891a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
590927dbe93S猫头猫        throw e;
591927dbe93S猫头猫    }
592927dbe93S猫头猫}
593927dbe93S猫头猫
594927dbe93S猫头猫// 安装插件
595927dbe93S猫头猫async function installPlugin(pluginPath: string) {
59622c09412S猫头猫    // if (pluginPath.endsWith('.js')) {
597927dbe93S猫头猫    const funcCode = await readFile(pluginPath, 'utf8');
598927dbe93S猫头猫    const plugin = new Plugin(funcCode, pluginPath);
599927dbe93S猫头猫    const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
600927dbe93S猫头猫    if (_pluginIndex !== -1) {
6014d9d3c4cS猫头猫        throw new Error('插件已安装');
602927dbe93S猫头猫    }
603927dbe93S猫头猫    if (plugin.hash !== '') {
604927dbe93S猫头猫        const fn = nanoid();
605927dbe93S猫头猫        const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
606927dbe93S猫头猫        await copyFile(pluginPath, _pluginPath);
607927dbe93S猫头猫        plugin.path = _pluginPath;
608927dbe93S猫头猫        plugins = plugins.concat(plugin);
609927dbe93S猫头猫        pluginStateMapper.notify();
6104d9d3c4cS猫头猫        return;
611927dbe93S猫头猫    }
6124d9d3c4cS猫头猫    throw new Error('插件无法解析');
61322c09412S猫头猫    // }
61422c09412S猫头猫    // throw new Error('插件不存在');
615927dbe93S猫头猫}
616927dbe93S猫头猫
61758992c6bS猫头猫async function installPluginFromUrl(url: string) {
61858992c6bS猫头猫    try {
61958992c6bS猫头猫        const funcCode = (await axios.get(url)).data;
62058992c6bS猫头猫        if (funcCode) {
62158992c6bS猫头猫            const plugin = new Plugin(funcCode, '');
62258992c6bS猫头猫            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
62358992c6bS猫头猫            if (_pluginIndex !== -1) {
6248b7ddca8S猫头猫                // 静默忽略
6258b7ddca8S猫头猫                return;
62658992c6bS猫头猫            }
62725c1bd29S猫头猫            const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
62825c1bd29S猫头猫            if (oldVersionPlugin) {
62925c1bd29S猫头猫                if (
63025c1bd29S猫头猫                    compare(
63125c1bd29S猫头猫                        oldVersionPlugin.instance.version ?? '',
63225c1bd29S猫头猫                        plugin.instance.version ?? '',
63325c1bd29S猫头猫                        '>',
63425c1bd29S猫头猫                    )
63525c1bd29S猫头猫                ) {
63625c1bd29S猫头猫                    throw new Error('已安装更新版本的插件');
63725c1bd29S猫头猫                }
63825c1bd29S猫头猫            }
63925c1bd29S猫头猫
64058992c6bS猫头猫            if (plugin.hash !== '') {
64158992c6bS猫头猫                const fn = nanoid();
64258992c6bS猫头猫                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
64358992c6bS猫头猫                await writeFile(_pluginPath, funcCode, 'utf8');
64458992c6bS猫头猫                plugin.path = _pluginPath;
64558992c6bS猫头猫                plugins = plugins.concat(plugin);
64625c1bd29S猫头猫                if (oldVersionPlugin) {
64725c1bd29S猫头猫                    plugins = plugins.filter(
64825c1bd29S猫头猫                        _ => _.hash !== oldVersionPlugin.hash,
64925c1bd29S猫头猫                    );
65025c1bd29S猫头猫                    try {
65125c1bd29S猫头猫                        await unlink(oldVersionPlugin.path);
65225c1bd29S猫头猫                    } catch {}
65325c1bd29S猫头猫                }
65458992c6bS猫头猫                pluginStateMapper.notify();
65558992c6bS猫头猫                return;
65658992c6bS猫头猫            }
65774acbfc0S猫头猫            throw new Error('插件无法解析!');
65858992c6bS猫头猫        }
65925c1bd29S猫头猫    } catch (e: any) {
66058992c6bS猫头猫        errorLog('URL安装插件失败', e);
66125c1bd29S猫头猫        throw new Error(e?.message ?? '');
66258992c6bS猫头猫    }
66358992c6bS猫头猫}
66458992c6bS猫头猫
665927dbe93S猫头猫/** 卸载插件 */
666927dbe93S猫头猫async function uninstallPlugin(hash: string) {
667927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
668927dbe93S猫头猫    if (targetIndex !== -1) {
669927dbe93S猫头猫        try {
67024e5e74aS猫头猫            const pluginName = plugins[targetIndex].name;
671927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
672927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
673927dbe93S猫头猫            pluginStateMapper.notify();
67424e5e74aS猫头猫            if (plugins.every(_ => _.name !== pluginName)) {
67524e5e74aS猫头猫                await MediaMeta.removePlugin(pluginName);
67624e5e74aS猫头猫            }
677927dbe93S猫头猫        } catch {}
678927dbe93S猫头猫    }
679927dbe93S猫头猫}
680927dbe93S猫头猫
68108882a77S猫头猫async function uninstallAllPlugins() {
68208882a77S猫头猫    await Promise.all(
68308882a77S猫头猫        plugins.map(async plugin => {
68408882a77S猫头猫            try {
68508882a77S猫头猫                const pluginName = plugin.name;
68608882a77S猫头猫                await unlink(plugin.path);
68708882a77S猫头猫                await MediaMeta.removePlugin(pluginName);
68808882a77S猫头猫            } catch (e) {}
68908882a77S猫头猫        }),
69008882a77S猫头猫    );
69108882a77S猫头猫    plugins = [];
69208882a77S猫头猫    pluginStateMapper.notify();
693e08d37a3S猫头猫
694e08d37a3S猫头猫    /** 清除空余文件,异步做就可以了 */
695e08d37a3S猫头猫    readDir(pathConst.pluginPath)
696e08d37a3S猫头猫        .then(fns => {
697e08d37a3S猫头猫            fns.forEach(fn => {
698e08d37a3S猫头猫                unlink(fn.path).catch(emptyFunction);
699e08d37a3S猫头猫            });
700e08d37a3S猫头猫        })
701e08d37a3S猫头猫        .catch(emptyFunction);
70208882a77S猫头猫}
70308882a77S猫头猫
70425c1bd29S猫头猫async function updatePlugin(plugin: Plugin) {
70525c1bd29S猫头猫    const updateUrl = plugin.instance.srcUrl;
70625c1bd29S猫头猫    if (!updateUrl) {
70725c1bd29S猫头猫        throw new Error('没有更新源');
70825c1bd29S猫头猫    }
70925c1bd29S猫头猫    try {
71025c1bd29S猫头猫        await installPluginFromUrl(updateUrl);
71125c1bd29S猫头猫    } catch (e: any) {
71225c1bd29S猫头猫        if (e.message === '插件已安装') {
71325c1bd29S猫头猫            throw new Error('当前已是最新版本');
71425c1bd29S猫头猫        } else {
71525c1bd29S猫头猫            throw e;
71625c1bd29S猫头猫        }
71725c1bd29S猫头猫    }
71825c1bd29S猫头猫}
71925c1bd29S猫头猫
720927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
721927dbe93S猫头猫    return getByName(mediaItem.platform);
722927dbe93S猫头猫}
723927dbe93S猫头猫
724927dbe93S猫头猫function getByHash(hash: string) {
7257993f90eS猫头猫    return hash === localPluginHash
7267993f90eS猫头猫        ? localFilePlugin
7277993f90eS猫头猫        : plugins.find(_ => _.hash === hash);
728927dbe93S猫头猫}
729927dbe93S猫头猫
730927dbe93S猫头猫function getByName(name: string) {
7317993f90eS猫头猫    return name === localPluginPlatform
7320e4173cdS猫头猫        ? localFilePlugin
7330e4173cdS猫头猫        : plugins.find(_ => _.name === name);
734927dbe93S猫头猫}
735927dbe93S猫头猫
736927dbe93S猫头猫function getValidPlugins() {
737927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
738927dbe93S猫头猫}
739927dbe93S猫头猫
740efb9da24S猫头猫function getSearchablePlugins() {
741efb9da24S猫头猫    return plugins.filter(_ => _.state === 'enabled' && _.instance.search);
742efb9da24S猫头猫}
743efb9da24S猫头猫
744e08d37a3S猫头猫function getSortedSearchablePlugins() {
745e08d37a3S猫头猫    return getSearchablePlugins().sort((a, b) =>
746e08d37a3S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
747e08d37a3S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
748e08d37a3S猫头猫        0
749e08d37a3S猫头猫            ? -1
750e08d37a3S猫头猫            : 1,
751e08d37a3S猫头猫    );
752e08d37a3S猫头猫}
753e08d37a3S猫头猫
754e08d37a3S猫头猫function useSortedPlugins() {
755e08d37a3S猫头猫    const _plugins = pluginStateMapper.useMappedState();
756e08d37a3S猫头猫    const _pluginMetaAll = PluginMeta.usePluginMetaAll();
757e08d37a3S猫头猫
758*34588741S猫头猫    const [sortedPlugins, setSortedPlugins] = useState(
759*34588741S猫头猫        [..._plugins].sort((a, b) =>
760e08d37a3S猫头猫            (_pluginMetaAll[a.name]?.order ?? Infinity) -
761e08d37a3S猫头猫                (_pluginMetaAll[b.name]?.order ?? Infinity) <
762e08d37a3S猫头猫            0
763e08d37a3S猫头猫                ? -1
764e08d37a3S猫头猫                : 1,
765*34588741S猫头猫        ),
766e08d37a3S猫头猫    );
767*34588741S猫头猫
768*34588741S猫头猫    useEffect(() => {
769*34588741S猫头猫        setSortedPlugins(
770*34588741S猫头猫            [..._plugins].sort((a, b) =>
771*34588741S猫头猫                (_pluginMetaAll[a.name]?.order ?? Infinity) -
772*34588741S猫头猫                    (_pluginMetaAll[b.name]?.order ?? Infinity) <
773*34588741S猫头猫                0
774*34588741S猫头猫                    ? -1
775*34588741S猫头猫                    : 1,
776*34588741S猫头猫            ),
777*34588741S猫头猫        );
778*34588741S猫头猫    }, [_plugins, _pluginMetaAll]);
779*34588741S猫头猫
780*34588741S猫头猫    return sortedPlugins;
781e08d37a3S猫头猫}
782e08d37a3S猫头猫
783927dbe93S猫头猫const PluginManager = {
784927dbe93S猫头猫    setup,
785927dbe93S猫头猫    installPlugin,
78658992c6bS猫头猫    installPluginFromUrl,
78725c1bd29S猫头猫    updatePlugin,
788927dbe93S猫头猫    uninstallPlugin,
789927dbe93S猫头猫    getByMedia,
790927dbe93S猫头猫    getByHash,
791927dbe93S猫头猫    getByName,
792927dbe93S猫头猫    getValidPlugins,
793efb9da24S猫头猫    getSearchablePlugins,
794e08d37a3S猫头猫    getSortedSearchablePlugins,
7955276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
796e08d37a3S猫头猫    useSortedPlugins,
79708882a77S猫头猫    uninstallAllPlugins,
7985276aef9S猫头猫};
799927dbe93S猫头猫
800927dbe93S猫头猫export default PluginManager;
801