xref: /MusicFree/src/core/pluginManager.ts (revision 192ae2b0d7c144adaf6e33defbf47178eed3cc98)
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';
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';
4534588741S猫头猫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,
211abaede57S猫头猫        quality: IMusic.IQualityKey = 'standard',
212927dbe93S猫头猫        retryCount = 1,
213*192ae2b0S猫头猫    ): Promise<IPlugin.IMediaSourceResult | null> {
214927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
215927dbe93S猫头猫        const localPath =
2160e4173cdS猫头猫            getInternalData<string>(musicItem, InternalDataType.LOCALPATH) ??
2170e4173cdS猫头猫            getInternalData<string>(
2180e4173cdS猫头猫                LocalMusicSheet.isLocalMusic(musicItem),
2190e4173cdS猫头猫                InternalDataType.LOCALPATH,
2200e4173cdS猫头猫            );
2210e4173cdS猫头猫        if (localPath && (await FileSystem.exists(localPath))) {
2220e4173cdS猫头猫            trace('本地播放', localPath);
223927dbe93S猫头猫            return {
224927dbe93S猫头猫                url: localPath,
225927dbe93S猫头猫            };
226927dbe93S猫头猫        }
2277993f90eS猫头猫        if (musicItem.platform === localPluginPlatform) {
228f5935920S猫头猫            throw new Error('本地音乐不存在');
229f5935920S猫头猫        }
230927dbe93S猫头猫        // 2. 缓存播放
231927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
232985f8e75S猫头猫        const pluginCacheControl =
233985f8e75S猫头猫            this.plugin.instance.cacheControl ?? 'no-cache';
234cfa0fc07S猫头猫        if (
235cfa0fc07S猫头猫            mediaCache &&
236abaede57S猫头猫            mediaCache?.qualities?.[quality]?.url &&
23748f4b873S猫头猫            (pluginCacheControl === CacheControl.Cache ||
23848f4b873S猫头猫                (pluginCacheControl === CacheControl.NoCache &&
239ef714860S猫头猫                    Network.isOffline()))
240cfa0fc07S猫头猫        ) {
2415276aef9S猫头猫            trace('播放', '缓存播放');
242abaede57S猫头猫            const qualityInfo = mediaCache.qualities[quality];
243927dbe93S猫头猫            return {
244abaede57S猫头猫                url: qualityInfo.url,
245927dbe93S猫头猫                headers: mediaCache.headers,
2464060c00aS猫头猫                userAgent:
2474060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
248927dbe93S猫头猫            };
249927dbe93S猫头猫        }
250927dbe93S猫头猫        // 3. 插件解析
25120e6a092S猫头猫        if (!this.plugin.instance.getMediaSource) {
252abaede57S猫头猫            return {url: musicItem?.qualities?.[quality]?.url ?? musicItem.url};
253927dbe93S猫头猫        }
254927dbe93S猫头猫        try {
255abaede57S猫头猫            const {url, headers} = (await this.plugin.instance.getMediaSource(
256abaede57S猫头猫                musicItem,
257abaede57S猫头猫                quality,
258abaede57S猫头猫            )) ?? {url: musicItem?.qualities?.[quality]?.url};
259927dbe93S猫头猫            if (!url) {
260a28eac61S猫头猫                throw new Error('NOT RETRY');
261927dbe93S猫头猫            }
2625276aef9S猫头猫            trace('播放', '插件播放');
263927dbe93S猫头猫            const result = {
264927dbe93S猫头猫                url,
265927dbe93S猫头猫                headers,
266927dbe93S猫头猫                userAgent: headers?.['user-agent'],
267cfa0fc07S猫头猫            } as IPlugin.IMediaSourceResult;
268927dbe93S猫头猫
26948f4b873S猫头猫            if (pluginCacheControl !== CacheControl.NoStore) {
270abaede57S猫头猫                Cache.update(musicItem, [
271abaede57S猫头猫                    ['headers', result.headers],
272abaede57S猫头猫                    ['userAgent', result.userAgent],
273abaede57S猫头猫                    [`qualities.${quality}.url`, url],
274abaede57S猫头猫                ]);
275752ffc5aS猫头猫            }
276cfa0fc07S猫头猫
277927dbe93S猫头猫            return result;
278927dbe93S猫头猫        } catch (e: any) {
279a28eac61S猫头猫            if (retryCount > 0 && e?.message !== 'NOT RETRY') {
280927dbe93S猫头猫                await delay(150);
281abaede57S猫头猫                return this.getMediaSource(musicItem, quality, --retryCount);
282927dbe93S猫头猫            }
283927dbe93S猫头猫            errorLog('获取真实源失败', e?.message);
284*192ae2b0S猫头猫            return null;
285927dbe93S猫头猫        }
286927dbe93S猫头猫    }
287927dbe93S猫头猫
288927dbe93S猫头猫    /** 获取音乐详情 */
289927dbe93S猫头猫    async getMusicInfo(
290927dbe93S猫头猫        musicItem: ICommon.IMediaBase,
29174d0cf81S猫头猫    ): Promise<Partial<IMusic.IMusicItem> | null> {
292927dbe93S猫头猫        if (!this.plugin.instance.getMusicInfo) {
293d704daedS猫头猫            return null;
294927dbe93S猫头猫        }
29574d0cf81S猫头猫        try {
296927dbe93S猫头猫            return (
297927dbe93S猫头猫                this.plugin.instance.getMusicInfo(
2987993f90eS猫头猫                    resetMediaItem(musicItem, undefined, true),
299d704daedS猫头猫                ) ?? null
300927dbe93S猫头猫            );
30174d0cf81S猫头猫        } catch (e) {
302d704daedS猫头猫            return null;
30374d0cf81S猫头猫        }
304927dbe93S猫头猫    }
305927dbe93S猫头猫
306927dbe93S猫头猫    /** 获取歌词 */
307927dbe93S猫头猫    async getLyric(
308927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
309927dbe93S猫头猫        from?: IMusic.IMusicItemBase,
310927dbe93S猫头猫    ): Promise<ILyric.ILyricSource | null> {
311927dbe93S猫头猫        // 1.额外存储的meta信息
312927dbe93S猫头猫        const meta = MediaMeta.get(musicItem);
313927dbe93S猫头猫        if (meta && meta.associatedLrc) {
314927dbe93S猫头猫            // 有关联歌词
315927dbe93S猫头猫            if (
316927dbe93S猫头猫                isSameMediaItem(musicItem, from) ||
317927dbe93S猫头猫                isSameMediaItem(meta.associatedLrc, musicItem)
318927dbe93S猫头猫            ) {
319927dbe93S猫头猫                // 形成环路,断开当前的环
320927dbe93S猫头猫                await MediaMeta.update(musicItem, {
321927dbe93S猫头猫                    associatedLrc: undefined,
322927dbe93S猫头猫                });
323927dbe93S猫头猫                // 无歌词
324927dbe93S猫头猫                return null;
325927dbe93S猫头猫            }
326927dbe93S猫头猫            // 获取关联歌词
3277a91f04fS猫头猫            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
3284060c00aS猫头猫            const result = await this.getLyric(
3297a91f04fS猫头猫                {...meta.associatedLrc, ...associatedMeta},
3304060c00aS猫头猫                from ?? musicItem,
3314060c00aS猫头猫            );
332927dbe93S猫头猫            if (result) {
333927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
334927dbe93S猫头猫                return result;
335927dbe93S猫头猫            }
336927dbe93S猫头猫        }
337927dbe93S猫头猫        const cache = Cache.get(musicItem);
338927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
339927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
340927dbe93S猫头猫        // 如果存在文本
341927dbe93S猫头猫        if (rawLrc) {
342927dbe93S猫头猫            return {
343927dbe93S猫头猫                rawLrc,
344927dbe93S猫头猫                lrc: lrcUrl,
345927dbe93S猫头猫            };
346927dbe93S猫头猫        }
347927dbe93S猫头猫        // 2.本地缓存
348927dbe93S猫头猫        const localLrc =
3490e4173cdS猫头猫            meta?.[internalSerializeKey]?.local?.localLrc ||
3500e4173cdS猫头猫            cache?.[internalSerializeKey]?.local?.localLrc;
351927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
352927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
353927dbe93S猫头猫            return {
354927dbe93S猫头猫                rawLrc,
355927dbe93S猫头猫                lrc: lrcUrl,
356927dbe93S猫头猫            };
357927dbe93S猫头猫        }
358927dbe93S猫头猫        // 3.优先使用url
359927dbe93S猫头猫        if (lrcUrl) {
360927dbe93S猫头猫            try {
361927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
3622a3194f5S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
363927dbe93S猫头猫                return {
364927dbe93S猫头猫                    rawLrc,
365927dbe93S猫头猫                    lrc: lrcUrl,
366927dbe93S猫头猫                };
367927dbe93S猫头猫            } catch {
368927dbe93S猫头猫                lrcUrl = undefined;
369927dbe93S猫头猫            }
370927dbe93S猫头猫        }
371927dbe93S猫头猫        // 4. 如果地址失效
372927dbe93S猫头猫        if (!lrcUrl) {
373927dbe93S猫头猫            // 插件获得url
374927dbe93S猫头猫            try {
3757a91f04fS猫头猫                let lrcSource;
3767a91f04fS猫头猫                if (from) {
3777a91f04fS猫头猫                    lrcSource = await PluginManager.getByMedia(
3787a91f04fS猫头猫                        musicItem,
3797a91f04fS猫头猫                    )?.instance?.getLyric?.(
380927dbe93S猫头猫                        resetMediaItem(musicItem, undefined, true),
381927dbe93S猫头猫                    );
3827a91f04fS猫头猫                } else {
3837a91f04fS猫头猫                    lrcSource = await this.plugin.instance?.getLyric?.(
3847a91f04fS猫头猫                        resetMediaItem(musicItem, undefined, true),
3857a91f04fS猫头猫                    );
3867a91f04fS猫头猫                }
3877a91f04fS猫头猫
388927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
389927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
390927dbe93S猫头猫            } catch (e: any) {
391927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
392927dbe93S猫头猫            }
393927dbe93S猫头猫        }
394927dbe93S猫头猫        // 5. 最后一次请求
395927dbe93S猫头猫        if (rawLrc || lrcUrl) {
396927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
397927dbe93S猫头猫            if (lrcUrl) {
398927dbe93S猫头猫                try {
3992a3194f5S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
400927dbe93S猫头猫                } catch {}
401927dbe93S猫头猫            }
402927dbe93S猫头猫            if (rawLrc) {
403927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
404927dbe93S猫头猫                // 写入缓存
405927dbe93S猫头猫                Cache.update(musicItem, [
4060e4173cdS猫头猫                    [`${internalSerializeKey}.local.localLrc`, filename],
407927dbe93S猫头猫                ]);
408927dbe93S猫头猫                // 如果有meta
409927dbe93S猫头猫                if (meta) {
410927dbe93S猫头猫                    MediaMeta.update(musicItem, [
4110e4173cdS猫头猫                        [`${internalSerializeKey}.local.localLrc`, filename],
412927dbe93S猫头猫                    ]);
413927dbe93S猫头猫                }
414927dbe93S猫头猫                return {
415927dbe93S猫头猫                    rawLrc,
416927dbe93S猫头猫                    lrc: lrcUrl,
417927dbe93S猫头猫                };
418927dbe93S猫头猫            }
419927dbe93S猫头猫        }
420927dbe93S猫头猫
421927dbe93S猫头猫        return null;
422927dbe93S猫头猫    }
423927dbe93S猫头猫
424927dbe93S猫头猫    /** 获取歌词文本 */
425927dbe93S猫头猫    async getLyricText(
426927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
427927dbe93S猫头猫    ): Promise<string | undefined> {
428927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
429927dbe93S猫头猫    }
430927dbe93S猫头猫
431927dbe93S猫头猫    /** 获取专辑信息 */
432927dbe93S猫头猫    async getAlbumInfo(
433927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
434927dbe93S猫头猫    ): Promise<IAlbum.IAlbumItem | null> {
435927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
436927dbe93S猫头猫            return {...albumItem, musicList: []};
437927dbe93S猫头猫        }
438927dbe93S猫头猫        try {
439927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
440927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
441927dbe93S猫头猫            );
4425276aef9S猫头猫            if (!result) {
4435276aef9S猫头猫                throw new Error();
4445276aef9S猫头猫            }
445927dbe93S猫头猫            result?.musicList?.forEach(_ => {
446927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
447927dbe93S猫头猫            });
4485276aef9S猫头猫
4495276aef9S猫头猫            return {...albumItem, ...result};
4504394410dS猫头猫        } catch (e: any) {
4514394410dS猫头猫            trace('获取专辑信息失败', e?.message);
452927dbe93S猫头猫            return {...albumItem, musicList: []};
453927dbe93S猫头猫        }
454927dbe93S猫头猫    }
455927dbe93S猫头猫
456927dbe93S猫头猫    /** 查询作者信息 */
457efb9da24S猫头猫    async getArtistWorks<T extends IArtist.ArtistMediaType>(
458927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
459927dbe93S猫头猫        page: number,
460927dbe93S猫头猫        type: T,
461927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
462efb9da24S猫头猫        if (!this.plugin.instance.getArtistWorks) {
463927dbe93S猫头猫            return {
464927dbe93S猫头猫                isEnd: true,
465927dbe93S猫头猫                data: [],
466927dbe93S猫头猫            };
467927dbe93S猫头猫        }
468927dbe93S猫头猫        try {
469efb9da24S猫头猫            const result = await this.plugin.instance.getArtistWorks(
470927dbe93S猫头猫                artistItem,
471927dbe93S猫头猫                page,
472927dbe93S猫头猫                type,
473927dbe93S猫头猫            );
474927dbe93S猫头猫            if (!result.data) {
475927dbe93S猫头猫                return {
476927dbe93S猫头猫                    isEnd: true,
477927dbe93S猫头猫                    data: [],
478927dbe93S猫头猫                };
479927dbe93S猫头猫            }
480927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
481927dbe93S猫头猫            return {
482927dbe93S猫头猫                isEnd: result.isEnd ?? true,
483927dbe93S猫头猫                data: result.data,
484927dbe93S猫头猫            };
4854394410dS猫头猫        } catch (e: any) {
4864394410dS猫头猫            trace('查询作者信息失败', e?.message);
487927dbe93S猫头猫            throw e;
488927dbe93S猫头猫        }
489927dbe93S猫头猫    }
49008380090S猫头猫
49108380090S猫头猫    /** 导入歌单 */
49208380090S猫头猫    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
49308380090S猫头猫        try {
49408380090S猫头猫            const result =
49508380090S猫头猫                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
49608380090S猫头猫            result.forEach(_ => resetMediaItem(_, this.plugin.name));
49708380090S猫头猫            return result;
4980e4173cdS猫头猫        } catch (e) {
4990e4173cdS猫头猫            console.log(e);
50008380090S猫头猫            return [];
50108380090S猫头猫        }
50208380090S猫头猫    }
5034d9d3c4cS猫头猫    /** 导入单曲 */
5044d9d3c4cS猫头猫    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
5054d9d3c4cS猫头猫        try {
5064d9d3c4cS猫头猫            const result = await this.plugin.instance?.importMusicItem?.(
5074d9d3c4cS猫头猫                urlLike,
5084d9d3c4cS猫头猫            );
5094d9d3c4cS猫头猫            if (!result) {
5104d9d3c4cS猫头猫                throw new Error();
5114d9d3c4cS猫头猫            }
5124d9d3c4cS猫头猫            resetMediaItem(result, this.plugin.name);
5134d9d3c4cS猫头猫            return result;
5144d9d3c4cS猫头猫        } catch {
5154d9d3c4cS猫头猫            return null;
5164d9d3c4cS猫头猫        }
5174d9d3c4cS猫头猫    }
518927dbe93S猫头猫}
519d5bfeb7eS猫头猫//#endregion
5201a5528a0S猫头猫
521927dbe93S猫头猫let plugins: Array<Plugin> = [];
522927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
52374d0cf81S猫头猫
524d5bfeb7eS猫头猫//#region 本地音乐插件
52574d0cf81S猫头猫/** 本地插件 */
52674d0cf81S猫头猫const localFilePlugin = new Plugin(function () {
5270e4173cdS猫头猫    return {
528d5bfeb7eS猫头猫        platform: localPluginPlatform,
52974d0cf81S猫头猫        _path: '',
53074d0cf81S猫头猫        async getMusicInfo(musicBase) {
53174d0cf81S猫头猫            const localPath = getInternalData<string>(
53274d0cf81S猫头猫                musicBase,
53374d0cf81S猫头猫                InternalDataType.LOCALPATH,
5340e4173cdS猫头猫            );
53574d0cf81S猫头猫            if (localPath) {
53674d0cf81S猫头猫                const coverImg = await Mp3Util.getMediaCoverImg(localPath);
53774d0cf81S猫头猫                return {
53874d0cf81S猫头猫                    artwork: coverImg,
53974d0cf81S猫头猫                };
54074d0cf81S猫头猫            }
54174d0cf81S猫头猫            return null;
54274d0cf81S猫头猫        },
5437993f90eS猫头猫        async getLyric(musicBase) {
5447993f90eS猫头猫            const localPath = getInternalData<string>(
5457993f90eS猫头猫                musicBase,
5467993f90eS猫头猫                InternalDataType.LOCALPATH,
5477993f90eS猫头猫            );
5487993f90eS猫头猫            if (localPath) {
5497993f90eS猫头猫                const rawLrc = await Mp3Util.getLyric(localPath);
5507993f90eS猫头猫                return {
5517993f90eS猫头猫                    rawLrc,
5527993f90eS猫头猫                };
5537993f90eS猫头猫            }
5547993f90eS猫头猫            return null;
5557993f90eS猫头猫        },
55674d0cf81S猫头猫    };
55774d0cf81S猫头猫}, '');
5587993f90eS猫头猫localFilePlugin.hash = localPluginHash;
559927dbe93S猫头猫
560d5bfeb7eS猫头猫//#endregion
561d5bfeb7eS猫头猫
562927dbe93S猫头猫async function setup() {
563927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
564927dbe93S猫头猫    try {
565927dbe93S猫头猫        // 加载插件
566927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
567927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
568927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
5691e263108S猫头猫            trace('初始化插件', _pluginUrl);
5701e263108S猫头猫            if (
5711e263108S猫头猫                _pluginUrl.isFile() &&
5721e263108S猫头猫                (_pluginUrl.name?.endsWith?.('.js') ||
5731e263108S猫头猫                    _pluginUrl.path?.endsWith?.('.js'))
5741e263108S猫头猫            ) {
575927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
576927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
5774060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
5784060c00aS猫头猫                    p => p.hash === plugin.hash,
5794060c00aS猫头猫                );
580927dbe93S猫头猫                if (_pluginIndex !== -1) {
581927dbe93S猫头猫                    // 重复插件,直接忽略
582927dbe93S猫头猫                    return;
583927dbe93S猫头猫                }
584927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
585927dbe93S猫头猫            }
586927dbe93S猫头猫        }
587927dbe93S猫头猫
588927dbe93S猫头猫        plugins = _plugins;
589927dbe93S猫头猫        pluginStateMapper.notify();
590e08d37a3S猫头猫        /** 初始化meta信息 */
591e08d37a3S猫头猫        PluginMeta.setupMeta(plugins.map(_ => _.name));
592927dbe93S猫头猫    } catch (e: any) {
5934060c00aS猫头猫        ToastAndroid.show(
5944060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
5954060c00aS猫头猫            ToastAndroid.LONG,
5964060c00aS猫头猫        );
5971a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
598927dbe93S猫头猫        throw e;
599927dbe93S猫头猫    }
600927dbe93S猫头猫}
601927dbe93S猫头猫
602927dbe93S猫头猫// 安装插件
603927dbe93S猫头猫async function installPlugin(pluginPath: string) {
60422c09412S猫头猫    // if (pluginPath.endsWith('.js')) {
605927dbe93S猫头猫    const funcCode = await readFile(pluginPath, 'utf8');
606927dbe93S猫头猫    const plugin = new Plugin(funcCode, pluginPath);
607927dbe93S猫头猫    const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
608927dbe93S猫头猫    if (_pluginIndex !== -1) {
6094d9d3c4cS猫头猫        throw new Error('插件已安装');
610927dbe93S猫头猫    }
611927dbe93S猫头猫    if (plugin.hash !== '') {
612927dbe93S猫头猫        const fn = nanoid();
613927dbe93S猫头猫        const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
614927dbe93S猫头猫        await copyFile(pluginPath, _pluginPath);
615927dbe93S猫头猫        plugin.path = _pluginPath;
616927dbe93S猫头猫        plugins = plugins.concat(plugin);
617927dbe93S猫头猫        pluginStateMapper.notify();
6184d9d3c4cS猫头猫        return;
619927dbe93S猫头猫    }
6204d9d3c4cS猫头猫    throw new Error('插件无法解析');
62122c09412S猫头猫    // }
62222c09412S猫头猫    // throw new Error('插件不存在');
623927dbe93S猫头猫}
624927dbe93S猫头猫
62558992c6bS猫头猫async function installPluginFromUrl(url: string) {
62658992c6bS猫头猫    try {
62758992c6bS猫头猫        const funcCode = (await axios.get(url)).data;
62858992c6bS猫头猫        if (funcCode) {
62958992c6bS猫头猫            const plugin = new Plugin(funcCode, '');
63058992c6bS猫头猫            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
63158992c6bS猫头猫            if (_pluginIndex !== -1) {
6328b7ddca8S猫头猫                // 静默忽略
6338b7ddca8S猫头猫                return;
63458992c6bS猫头猫            }
63525c1bd29S猫头猫            const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
63625c1bd29S猫头猫            if (oldVersionPlugin) {
63725c1bd29S猫头猫                if (
63825c1bd29S猫头猫                    compare(
63925c1bd29S猫头猫                        oldVersionPlugin.instance.version ?? '',
64025c1bd29S猫头猫                        plugin.instance.version ?? '',
64125c1bd29S猫头猫                        '>',
64225c1bd29S猫头猫                    )
64325c1bd29S猫头猫                ) {
64425c1bd29S猫头猫                    throw new Error('已安装更新版本的插件');
64525c1bd29S猫头猫                }
64625c1bd29S猫头猫            }
64725c1bd29S猫头猫
64858992c6bS猫头猫            if (plugin.hash !== '') {
64958992c6bS猫头猫                const fn = nanoid();
65058992c6bS猫头猫                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
65158992c6bS猫头猫                await writeFile(_pluginPath, funcCode, 'utf8');
65258992c6bS猫头猫                plugin.path = _pluginPath;
65358992c6bS猫头猫                plugins = plugins.concat(plugin);
65425c1bd29S猫头猫                if (oldVersionPlugin) {
65525c1bd29S猫头猫                    plugins = plugins.filter(
65625c1bd29S猫头猫                        _ => _.hash !== oldVersionPlugin.hash,
65725c1bd29S猫头猫                    );
65825c1bd29S猫头猫                    try {
65925c1bd29S猫头猫                        await unlink(oldVersionPlugin.path);
66025c1bd29S猫头猫                    } catch {}
66125c1bd29S猫头猫                }
66258992c6bS猫头猫                pluginStateMapper.notify();
66358992c6bS猫头猫                return;
66458992c6bS猫头猫            }
66574acbfc0S猫头猫            throw new Error('插件无法解析!');
66658992c6bS猫头猫        }
66725c1bd29S猫头猫    } catch (e: any) {
66858992c6bS猫头猫        errorLog('URL安装插件失败', e);
66925c1bd29S猫头猫        throw new Error(e?.message ?? '');
67058992c6bS猫头猫    }
67158992c6bS猫头猫}
67258992c6bS猫头猫
673927dbe93S猫头猫/** 卸载插件 */
674927dbe93S猫头猫async function uninstallPlugin(hash: string) {
675927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
676927dbe93S猫头猫    if (targetIndex !== -1) {
677927dbe93S猫头猫        try {
67824e5e74aS猫头猫            const pluginName = plugins[targetIndex].name;
679927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
680927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
681927dbe93S猫头猫            pluginStateMapper.notify();
68224e5e74aS猫头猫            if (plugins.every(_ => _.name !== pluginName)) {
68324e5e74aS猫头猫                await MediaMeta.removePlugin(pluginName);
68424e5e74aS猫头猫            }
685927dbe93S猫头猫        } catch {}
686927dbe93S猫头猫    }
687927dbe93S猫头猫}
688927dbe93S猫头猫
68908882a77S猫头猫async function uninstallAllPlugins() {
69008882a77S猫头猫    await Promise.all(
69108882a77S猫头猫        plugins.map(async plugin => {
69208882a77S猫头猫            try {
69308882a77S猫头猫                const pluginName = plugin.name;
69408882a77S猫头猫                await unlink(plugin.path);
69508882a77S猫头猫                await MediaMeta.removePlugin(pluginName);
69608882a77S猫头猫            } catch (e) {}
69708882a77S猫头猫        }),
69808882a77S猫头猫    );
69908882a77S猫头猫    plugins = [];
70008882a77S猫头猫    pluginStateMapper.notify();
701e08d37a3S猫头猫
702e08d37a3S猫头猫    /** 清除空余文件,异步做就可以了 */
703e08d37a3S猫头猫    readDir(pathConst.pluginPath)
704e08d37a3S猫头猫        .then(fns => {
705e08d37a3S猫头猫            fns.forEach(fn => {
706e08d37a3S猫头猫                unlink(fn.path).catch(emptyFunction);
707e08d37a3S猫头猫            });
708e08d37a3S猫头猫        })
709e08d37a3S猫头猫        .catch(emptyFunction);
71008882a77S猫头猫}
71108882a77S猫头猫
71225c1bd29S猫头猫async function updatePlugin(plugin: Plugin) {
71325c1bd29S猫头猫    const updateUrl = plugin.instance.srcUrl;
71425c1bd29S猫头猫    if (!updateUrl) {
71525c1bd29S猫头猫        throw new Error('没有更新源');
71625c1bd29S猫头猫    }
71725c1bd29S猫头猫    try {
71825c1bd29S猫头猫        await installPluginFromUrl(updateUrl);
71925c1bd29S猫头猫    } catch (e: any) {
72025c1bd29S猫头猫        if (e.message === '插件已安装') {
72125c1bd29S猫头猫            throw new Error('当前已是最新版本');
72225c1bd29S猫头猫        } else {
72325c1bd29S猫头猫            throw e;
72425c1bd29S猫头猫        }
72525c1bd29S猫头猫    }
72625c1bd29S猫头猫}
72725c1bd29S猫头猫
728927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
7292c595535S猫头猫    return getByName(mediaItem?.platform);
730927dbe93S猫头猫}
731927dbe93S猫头猫
732927dbe93S猫头猫function getByHash(hash: string) {
7337993f90eS猫头猫    return hash === localPluginHash
7347993f90eS猫头猫        ? localFilePlugin
7357993f90eS猫头猫        : plugins.find(_ => _.hash === hash);
736927dbe93S猫头猫}
737927dbe93S猫头猫
738927dbe93S猫头猫function getByName(name: string) {
7397993f90eS猫头猫    return name === localPluginPlatform
7400e4173cdS猫头猫        ? localFilePlugin
7410e4173cdS猫头猫        : plugins.find(_ => _.name === name);
742927dbe93S猫头猫}
743927dbe93S猫头猫
744927dbe93S猫头猫function getValidPlugins() {
745927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
746927dbe93S猫头猫}
747927dbe93S猫头猫
748efb9da24S猫头猫function getSearchablePlugins() {
749efb9da24S猫头猫    return plugins.filter(_ => _.state === 'enabled' && _.instance.search);
750efb9da24S猫头猫}
751efb9da24S猫头猫
752e08d37a3S猫头猫function getSortedSearchablePlugins() {
753e08d37a3S猫头猫    return getSearchablePlugins().sort((a, b) =>
754e08d37a3S猫头猫        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
755e08d37a3S猫头猫            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
756e08d37a3S猫头猫        0
757e08d37a3S猫头猫            ? -1
758e08d37a3S猫头猫            : 1,
759e08d37a3S猫头猫    );
760e08d37a3S猫头猫}
761e08d37a3S猫头猫
762e08d37a3S猫头猫function useSortedPlugins() {
763e08d37a3S猫头猫    const _plugins = pluginStateMapper.useMappedState();
764e08d37a3S猫头猫    const _pluginMetaAll = PluginMeta.usePluginMetaAll();
765e08d37a3S猫头猫
76634588741S猫头猫    const [sortedPlugins, setSortedPlugins] = useState(
76734588741S猫头猫        [..._plugins].sort((a, b) =>
768e08d37a3S猫头猫            (_pluginMetaAll[a.name]?.order ?? Infinity) -
769e08d37a3S猫头猫                (_pluginMetaAll[b.name]?.order ?? Infinity) <
770e08d37a3S猫头猫            0
771e08d37a3S猫头猫                ? -1
772e08d37a3S猫头猫                : 1,
77334588741S猫头猫        ),
774e08d37a3S猫头猫    );
77534588741S猫头猫
77634588741S猫头猫    useEffect(() => {
777d4cd40d8S猫头猫        InteractionManager.runAfterInteractions(() => {
77834588741S猫头猫            setSortedPlugins(
77934588741S猫头猫                [..._plugins].sort((a, b) =>
78034588741S猫头猫                    (_pluginMetaAll[a.name]?.order ?? Infinity) -
78134588741S猫头猫                        (_pluginMetaAll[b.name]?.order ?? Infinity) <
78234588741S猫头猫                    0
78334588741S猫头猫                        ? -1
78434588741S猫头猫                        : 1,
78534588741S猫头猫                ),
78634588741S猫头猫            );
787d4cd40d8S猫头猫        });
78834588741S猫头猫    }, [_plugins, _pluginMetaAll]);
78934588741S猫头猫
79034588741S猫头猫    return sortedPlugins;
791e08d37a3S猫头猫}
792e08d37a3S猫头猫
793927dbe93S猫头猫const PluginManager = {
794927dbe93S猫头猫    setup,
795927dbe93S猫头猫    installPlugin,
79658992c6bS猫头猫    installPluginFromUrl,
79725c1bd29S猫头猫    updatePlugin,
798927dbe93S猫头猫    uninstallPlugin,
799927dbe93S猫头猫    getByMedia,
800927dbe93S猫头猫    getByHash,
801927dbe93S猫头猫    getByName,
802927dbe93S猫头猫    getValidPlugins,
803efb9da24S猫头猫    getSearchablePlugins,
804e08d37a3S猫头猫    getSortedSearchablePlugins,
8055276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
806e08d37a3S猫头猫    useSortedPlugins,
80708882a77S猫头猫    uninstallAllPlugins,
8085276aef9S猫头猫};
809927dbe93S猫头猫
810927dbe93S猫头猫export default PluginManager;
811