xref: /MusicFree/src/core/pluginManager.ts (revision 24e5e74ac2bdea6bcf00df8f7039ddf19ef687ab)
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';
12927dbe93S猫头猫import {ToastAndroid} from 'react-native';
13927dbe93S猫头猫import pathConst from '@/constants/pathConst';
14927dbe93S猫头猫import {satisfies} from 'compare-versions';
15927dbe93S猫头猫import DeviceInfo from 'react-native-device-info';
16927dbe93S猫头猫import StateMapper from '@/utils/stateMapper';
17927dbe93S猫头猫import MediaMeta from './mediaMeta';
18927dbe93S猫头猫import {nanoid} from 'nanoid';
19927dbe93S猫头猫import {errorLog, trace} from '../utils/log';
20927dbe93S猫头猫import Cache from './cache';
21927dbe93S猫头猫import {isSameMediaItem, resetMediaItem} from '@/utils/mediaItem';
22cfa0fc07S猫头猫import {
23cfa0fc07S猫头猫    CacheControl,
24cfa0fc07S猫头猫    internalSerialzeKey,
25cfa0fc07S猫头猫    internalSymbolKey,
26cfa0fc07S猫头猫} from '@/constants/commonConst';
27927dbe93S猫头猫import Download from './download';
28927dbe93S猫头猫import delay from '@/utils/delay';
294d9d3c4cS猫头猫import * as cheerio from 'cheerio';
30ef714860S猫头猫import Network from './network';
31927dbe93S猫头猫
32927dbe93S猫头猫axios.defaults.timeout = 1500;
33927dbe93S猫头猫
34927dbe93S猫头猫const sha256 = CryptoJs.SHA256;
35927dbe93S猫头猫
36cfa0fc07S猫头猫export enum PluginStateCode {
37927dbe93S猫头猫    /** 版本不匹配 */
38927dbe93S猫头猫    VersionNotMatch = 'VERSION NOT MATCH',
39927dbe93S猫头猫    /** 无法解析 */
40927dbe93S猫头猫    CannotParse = 'CANNOT PARSE',
41927dbe93S猫头猫}
42927dbe93S猫头猫
43927dbe93S猫头猫export class Plugin {
44927dbe93S猫头猫    /** 插件名 */
45927dbe93S猫头猫    public name: string;
46927dbe93S猫头猫    /** 插件的hash,作为唯一id */
47927dbe93S猫头猫    public hash: string;
48927dbe93S猫头猫    /** 插件状态:激活、关闭、错误 */
49927dbe93S猫头猫    public state: 'enabled' | 'disabled' | 'error';
50927dbe93S猫头猫    /** 插件支持的搜索类型 */
51927dbe93S猫头猫    public supportedSearchType?: string;
52927dbe93S猫头猫    /** 插件状态信息 */
53927dbe93S猫头猫    public stateCode?: PluginStateCode;
54927dbe93S猫头猫    /** 插件的实例 */
55927dbe93S猫头猫    public instance: IPlugin.IPluginInstance;
56927dbe93S猫头猫    /** 插件路径 */
57927dbe93S猫头猫    public path: string;
58927dbe93S猫头猫    /** 插件方法 */
59927dbe93S猫头猫    public methods: PluginMethods;
60927dbe93S猫头猫
61927dbe93S猫头猫    constructor(funcCode: string, pluginPath: string) {
62927dbe93S猫头猫        this.state = 'enabled';
63927dbe93S猫头猫        let _instance: IPlugin.IPluginInstance;
64927dbe93S猫头猫        try {
654060c00aS猫头猫            // eslint-disable-next-line no-new-func
66927dbe93S猫头猫            _instance = Function(`
67927dbe93S猫头猫      'use strict';
68927dbe93S猫头猫      try {
69927dbe93S猫头猫        return ${funcCode};
70927dbe93S猫头猫      } catch(e) {
71927dbe93S猫头猫        return null;
72927dbe93S猫头猫      }
734d9d3c4cS猫头猫    `)()({CryptoJs, axios, dayjs, cheerio});
74927dbe93S猫头猫            this.checkValid(_instance);
75927dbe93S猫头猫        } catch (e: any) {
76927dbe93S猫头猫            this.state = 'error';
77927dbe93S猫头猫            this.stateCode = PluginStateCode.CannotParse;
78927dbe93S猫头猫            if (e?.stateCode) {
79927dbe93S猫头猫                this.stateCode = e.stateCode;
80927dbe93S猫头猫            }
81927dbe93S猫头猫            errorLog(`${pluginPath}插件无法解析 `, {
82927dbe93S猫头猫                stateCode: this.stateCode,
83927dbe93S猫头猫                message: e?.message,
84927dbe93S猫头猫                stack: e?.stack,
85927dbe93S猫头猫            });
86927dbe93S猫头猫            _instance = e?.instance ?? {
87927dbe93S猫头猫                _path: '',
88927dbe93S猫头猫                platform: '',
89927dbe93S猫头猫                appVersion: '',
9020e6a092S猫头猫                async getMediaSource() {
91927dbe93S猫头猫                    return null;
92927dbe93S猫头猫                },
93927dbe93S猫头猫                async search() {
94927dbe93S猫头猫                    return {};
95927dbe93S猫头猫                },
96927dbe93S猫头猫                async getAlbumInfo() {
97927dbe93S猫头猫                    return null;
98927dbe93S猫头猫                },
99927dbe93S猫头猫            };
100927dbe93S猫头猫        }
101927dbe93S猫头猫        this.instance = _instance;
102927dbe93S猫头猫        this.path = pluginPath;
103927dbe93S猫头猫        this.name = _instance.platform;
104927dbe93S猫头猫        if (this.instance.platform === '') {
105927dbe93S猫头猫            this.hash = '';
106927dbe93S猫头猫        } else {
107927dbe93S猫头猫            this.hash = sha256(funcCode).toString();
108927dbe93S猫头猫        }
109927dbe93S猫头猫
110927dbe93S猫头猫        // 放在最后
111927dbe93S猫头猫        this.methods = new PluginMethods(this);
112927dbe93S猫头猫    }
113927dbe93S猫头猫
114927dbe93S猫头猫    private checkValid(_instance: IPlugin.IPluginInstance) {
115927dbe93S猫头猫        /** 版本号校验 */
116927dbe93S猫头猫        if (
117927dbe93S猫头猫            _instance.appVersion &&
118927dbe93S猫头猫            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
119927dbe93S猫头猫        ) {
120927dbe93S猫头猫            throw {
121927dbe93S猫头猫                instance: _instance,
122927dbe93S猫头猫                stateCode: PluginStateCode.VersionNotMatch,
123927dbe93S猫头猫            };
124927dbe93S猫头猫        }
125927dbe93S猫头猫        return true;
126927dbe93S猫头猫    }
127927dbe93S猫头猫}
128927dbe93S猫头猫
129927dbe93S猫头猫/** 有缓存等信息 */
130927dbe93S猫头猫class PluginMethods implements IPlugin.IPluginInstanceMethods {
131927dbe93S猫头猫    private plugin;
132927dbe93S猫头猫    constructor(plugin: Plugin) {
133927dbe93S猫头猫        this.plugin = plugin;
134927dbe93S猫头猫    }
135927dbe93S猫头猫    /** 搜索 */
136927dbe93S猫头猫    async search<T extends ICommon.SupportMediaType>(
137927dbe93S猫头猫        query: string,
138927dbe93S猫头猫        page: number,
139927dbe93S猫头猫        type: T,
140927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
141927dbe93S猫头猫        if (!this.plugin.instance.search) {
142927dbe93S猫头猫            return {
143927dbe93S猫头猫                isEnd: true,
144927dbe93S猫头猫                data: [],
145927dbe93S猫头猫            };
146927dbe93S猫头猫        }
147927dbe93S猫头猫
1484060c00aS猫头猫        const result =
1494060c00aS猫头猫            (await this.plugin.instance.search(query, page, type)) ?? {};
150927dbe93S猫头猫        if (Array.isArray(result.data)) {
151927dbe93S猫头猫            result.data.forEach(_ => {
152927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
153927dbe93S猫头猫            });
154927dbe93S猫头猫            return {
155927dbe93S猫头猫                isEnd: result.isEnd ?? true,
156927dbe93S猫头猫                data: result.data,
157927dbe93S猫头猫            };
158927dbe93S猫头猫        }
159927dbe93S猫头猫        return {
160927dbe93S猫头猫            isEnd: true,
161927dbe93S猫头猫            data: [],
162927dbe93S猫头猫        };
163927dbe93S猫头猫    }
164927dbe93S猫头猫
165927dbe93S猫头猫    /** 获取真实源 */
16620e6a092S猫头猫    async getMediaSource(
167927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
168927dbe93S猫头猫        retryCount = 1,
16920e6a092S猫头猫    ): Promise<IPlugin.IMediaSourceResult> {
170927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
171927dbe93S猫头猫        const localPath =
172927dbe93S猫头猫            musicItem?.[internalSymbolKey]?.localPath ??
173927dbe93S猫头猫            Download.getDownloaded(musicItem)?.[internalSymbolKey]?.localPath;
174927dbe93S猫头猫        if (localPath && (await exists(localPath))) {
1755276aef9S猫头猫            trace('播放', '本地播放');
176927dbe93S猫头猫            return {
177927dbe93S猫头猫                url: localPath,
178927dbe93S猫头猫            };
179927dbe93S猫头猫        }
180927dbe93S猫头猫        // 2. 缓存播放
181927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
18248f4b873S猫头猫        const pluginCacheControl = this.plugin.instance.cacheControl;
183cfa0fc07S猫头猫        if (
184cfa0fc07S猫头猫            mediaCache &&
185cfa0fc07S猫头猫            mediaCache?.url &&
18648f4b873S猫头猫            (pluginCacheControl === CacheControl.Cache ||
18748f4b873S猫头猫                (pluginCacheControl === CacheControl.NoCache &&
188ef714860S猫头猫                    Network.isOffline()))
189cfa0fc07S猫头猫        ) {
1905276aef9S猫头猫            trace('播放', '缓存播放');
191927dbe93S猫头猫            return {
192927dbe93S猫头猫                url: mediaCache.url,
193927dbe93S猫头猫                headers: mediaCache.headers,
1944060c00aS猫头猫                userAgent:
1954060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
196927dbe93S猫头猫            };
197927dbe93S猫头猫        }
198927dbe93S猫头猫        // 3. 插件解析
19920e6a092S猫头猫        if (!this.plugin.instance.getMediaSource) {
200927dbe93S猫头猫            return {url: musicItem.url};
201927dbe93S猫头猫        }
202927dbe93S猫头猫        try {
20348f4b873S猫头猫            const {url, headers} =
20420e6a092S猫头猫                (await this.plugin.instance.getMediaSource(musicItem)) ?? {};
205927dbe93S猫头猫            if (!url) {
206927dbe93S猫头猫                throw new Error();
207927dbe93S猫头猫            }
2085276aef9S猫头猫            trace('播放', '插件播放');
209927dbe93S猫头猫            const result = {
210927dbe93S猫头猫                url,
211927dbe93S猫头猫                headers,
212927dbe93S猫头猫                userAgent: headers?.['user-agent'],
213cfa0fc07S猫头猫            } as IPlugin.IMediaSourceResult;
214927dbe93S猫头猫
21548f4b873S猫头猫            if (pluginCacheControl !== CacheControl.NoStore) {
216927dbe93S猫头猫                Cache.update(musicItem, result);
217752ffc5aS猫头猫            }
218cfa0fc07S猫头猫
219927dbe93S猫头猫            return result;
220927dbe93S猫头猫        } catch (e: any) {
221927dbe93S猫头猫            if (retryCount > 0) {
222927dbe93S猫头猫                await delay(150);
22320e6a092S猫头猫                return this.getMediaSource(musicItem, --retryCount);
224927dbe93S猫头猫            }
225927dbe93S猫头猫            errorLog('获取真实源失败', e?.message);
226927dbe93S猫头猫            throw e;
227927dbe93S猫头猫        }
228927dbe93S猫头猫    }
229927dbe93S猫头猫
230927dbe93S猫头猫    /** 获取音乐详情 */
231927dbe93S猫头猫    async getMusicInfo(
232927dbe93S猫头猫        musicItem: ICommon.IMediaBase,
233927dbe93S猫头猫    ): Promise<IMusic.IMusicItem | null> {
234927dbe93S猫头猫        if (!this.plugin.instance.getMusicInfo) {
235927dbe93S猫头猫            return musicItem as IMusic.IMusicItem;
236927dbe93S猫头猫        }
237927dbe93S猫头猫        return (
238927dbe93S猫头猫            this.plugin.instance.getMusicInfo(
239927dbe93S猫头猫                resetMediaItem(musicItem, undefined, true),
240927dbe93S猫头猫            ) ?? musicItem
241927dbe93S猫头猫        );
242927dbe93S猫头猫    }
243927dbe93S猫头猫
244927dbe93S猫头猫    /** 获取歌词 */
245927dbe93S猫头猫    async getLyric(
246927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
247927dbe93S猫头猫        from?: IMusic.IMusicItemBase,
248927dbe93S猫头猫    ): Promise<ILyric.ILyricSource | null> {
249927dbe93S猫头猫        // 1.额外存储的meta信息
250927dbe93S猫头猫        const meta = MediaMeta.get(musicItem);
251927dbe93S猫头猫        if (meta && meta.associatedLrc) {
252927dbe93S猫头猫            // 有关联歌词
253927dbe93S猫头猫            if (
254927dbe93S猫头猫                isSameMediaItem(musicItem, from) ||
255927dbe93S猫头猫                isSameMediaItem(meta.associatedLrc, musicItem)
256927dbe93S猫头猫            ) {
257927dbe93S猫头猫                // 形成环路,断开当前的环
258927dbe93S猫头猫                await MediaMeta.update(musicItem, {
259927dbe93S猫头猫                    associatedLrc: undefined,
260927dbe93S猫头猫                });
261927dbe93S猫头猫                // 无歌词
262927dbe93S猫头猫                return null;
263927dbe93S猫头猫            }
264927dbe93S猫头猫            // 获取关联歌词
2657a91f04fS猫头猫            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
2664060c00aS猫头猫            const result = await this.getLyric(
2677a91f04fS猫头猫                {...meta.associatedLrc, ...associatedMeta},
2684060c00aS猫头猫                from ?? musicItem,
2694060c00aS猫头猫            );
270927dbe93S猫头猫            if (result) {
271927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
272927dbe93S猫头猫                return result;
273927dbe93S猫头猫            }
274927dbe93S猫头猫        }
275927dbe93S猫头猫        const cache = Cache.get(musicItem);
276927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
277927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
278927dbe93S猫头猫        // 如果存在文本
279927dbe93S猫头猫        if (rawLrc) {
280927dbe93S猫头猫            return {
281927dbe93S猫头猫                rawLrc,
282927dbe93S猫头猫                lrc: lrcUrl,
283927dbe93S猫头猫            };
284927dbe93S猫头猫        }
285927dbe93S猫头猫        // 2.本地缓存
286927dbe93S猫头猫        const localLrc =
287927dbe93S猫头猫            meta?.[internalSerialzeKey]?.local?.localLrc ||
288927dbe93S猫头猫            cache?.[internalSerialzeKey]?.local?.localLrc;
289927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
290927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
291927dbe93S猫头猫            return {
292927dbe93S猫头猫                rawLrc,
293927dbe93S猫头猫                lrc: lrcUrl,
294927dbe93S猫头猫            };
295927dbe93S猫头猫        }
296927dbe93S猫头猫        // 3.优先使用url
297927dbe93S猫头猫        if (lrcUrl) {
298927dbe93S猫头猫            try {
299927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
3002a3194f5S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
301927dbe93S猫头猫                return {
302927dbe93S猫头猫                    rawLrc,
303927dbe93S猫头猫                    lrc: lrcUrl,
304927dbe93S猫头猫                };
305927dbe93S猫头猫            } catch {
306927dbe93S猫头猫                lrcUrl = undefined;
307927dbe93S猫头猫            }
308927dbe93S猫头猫        }
309927dbe93S猫头猫        // 4. 如果地址失效
310927dbe93S猫头猫        if (!lrcUrl) {
311927dbe93S猫头猫            // 插件获得url
312927dbe93S猫头猫            try {
3137a91f04fS猫头猫                let lrcSource;
3147a91f04fS猫头猫                if (from) {
3157a91f04fS猫头猫                    lrcSource = await PluginManager.getByMedia(
3167a91f04fS猫头猫                        musicItem,
3177a91f04fS猫头猫                    )?.instance?.getLyric?.(
318927dbe93S猫头猫                        resetMediaItem(musicItem, undefined, true),
319927dbe93S猫头猫                    );
3207a91f04fS猫头猫                } else {
3217a91f04fS猫头猫                    lrcSource = await this.plugin.instance?.getLyric?.(
3227a91f04fS猫头猫                        resetMediaItem(musicItem, undefined, true),
3237a91f04fS猫头猫                    );
3247a91f04fS猫头猫                }
3257a91f04fS猫头猫
326927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
327927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
328927dbe93S猫头猫            } catch (e: any) {
329927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
330927dbe93S猫头猫            }
331927dbe93S猫头猫        }
332927dbe93S猫头猫        // 5. 最后一次请求
333927dbe93S猫头猫        if (rawLrc || lrcUrl) {
334927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
335927dbe93S猫头猫            if (lrcUrl) {
336927dbe93S猫头猫                try {
3372a3194f5S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
338927dbe93S猫头猫                } catch {}
339927dbe93S猫头猫            }
340927dbe93S猫头猫            if (rawLrc) {
341927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
342927dbe93S猫头猫                // 写入缓存
343927dbe93S猫头猫                Cache.update(musicItem, [
344927dbe93S猫头猫                    [`${internalSerialzeKey}.local.localLrc`, filename],
345927dbe93S猫头猫                ]);
346927dbe93S猫头猫                // 如果有meta
347927dbe93S猫头猫                if (meta) {
348927dbe93S猫头猫                    MediaMeta.update(musicItem, [
349927dbe93S猫头猫                        [`${internalSerialzeKey}.local.localLrc`, filename],
350927dbe93S猫头猫                    ]);
351927dbe93S猫头猫                }
352927dbe93S猫头猫                return {
353927dbe93S猫头猫                    rawLrc,
354927dbe93S猫头猫                    lrc: lrcUrl,
355927dbe93S猫头猫                };
356927dbe93S猫头猫            }
357927dbe93S猫头猫        }
358927dbe93S猫头猫
359927dbe93S猫头猫        return null;
360927dbe93S猫头猫    }
361927dbe93S猫头猫
362927dbe93S猫头猫    /** 获取歌词文本 */
363927dbe93S猫头猫    async getLyricText(
364927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
365927dbe93S猫头猫    ): Promise<string | undefined> {
366927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
367927dbe93S猫头猫    }
368927dbe93S猫头猫
369927dbe93S猫头猫    /** 获取专辑信息 */
370927dbe93S猫头猫    async getAlbumInfo(
371927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
372927dbe93S猫头猫    ): Promise<IAlbum.IAlbumItem | null> {
373927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
374927dbe93S猫头猫            return {...albumItem, musicList: []};
375927dbe93S猫头猫        }
376927dbe93S猫头猫        try {
377927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
378927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
379927dbe93S猫头猫            );
3805276aef9S猫头猫            if (!result) {
3815276aef9S猫头猫                throw new Error();
3825276aef9S猫头猫            }
383927dbe93S猫头猫            result?.musicList?.forEach(_ => {
384927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
385927dbe93S猫头猫            });
3865276aef9S猫头猫
3875276aef9S猫头猫            return {...albumItem, ...result};
388927dbe93S猫头猫        } catch {
389927dbe93S猫头猫            return {...albumItem, musicList: []};
390927dbe93S猫头猫        }
391927dbe93S猫头猫    }
392927dbe93S猫头猫
393927dbe93S猫头猫    /** 查询作者信息 */
394927dbe93S猫头猫    async queryArtistWorks<T extends IArtist.ArtistMediaType>(
395927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
396927dbe93S猫头猫        page: number,
397927dbe93S猫头猫        type: T,
398927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
399927dbe93S猫头猫        if (!this.plugin.instance.queryArtistWorks) {
400927dbe93S猫头猫            return {
401927dbe93S猫头猫                isEnd: true,
402927dbe93S猫头猫                data: [],
403927dbe93S猫头猫            };
404927dbe93S猫头猫        }
405927dbe93S猫头猫        try {
406927dbe93S猫头猫            const result = await this.plugin.instance.queryArtistWorks(
407927dbe93S猫头猫                artistItem,
408927dbe93S猫头猫                page,
409927dbe93S猫头猫                type,
410927dbe93S猫头猫            );
411927dbe93S猫头猫            if (!result.data) {
412927dbe93S猫头猫                return {
413927dbe93S猫头猫                    isEnd: true,
414927dbe93S猫头猫                    data: [],
415927dbe93S猫头猫                };
416927dbe93S猫头猫            }
417927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
418927dbe93S猫头猫            return {
419927dbe93S猫头猫                isEnd: result.isEnd ?? true,
420927dbe93S猫头猫                data: result.data,
421927dbe93S猫头猫            };
422927dbe93S猫头猫        } catch (e) {
423927dbe93S猫头猫            throw e;
424927dbe93S猫头猫        }
425927dbe93S猫头猫    }
42608380090S猫头猫
42708380090S猫头猫    /** 导入歌单 */
42808380090S猫头猫    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
42908380090S猫头猫        try {
43008380090S猫头猫            const result =
43108380090S猫头猫                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
43208380090S猫头猫            result.forEach(_ => resetMediaItem(_, this.plugin.name));
43308380090S猫头猫            return result;
43408380090S猫头猫        } catch {
43508380090S猫头猫            return [];
43608380090S猫头猫        }
43708380090S猫头猫    }
4384d9d3c4cS猫头猫    /** 导入单曲 */
4394d9d3c4cS猫头猫    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
4404d9d3c4cS猫头猫        try {
4414d9d3c4cS猫头猫            const result = await this.plugin.instance?.importMusicItem?.(
4424d9d3c4cS猫头猫                urlLike,
4434d9d3c4cS猫头猫            );
4444d9d3c4cS猫头猫            if (!result) {
4454d9d3c4cS猫头猫                throw new Error();
4464d9d3c4cS猫头猫            }
4474d9d3c4cS猫头猫            resetMediaItem(result, this.plugin.name);
4484d9d3c4cS猫头猫            return result;
4494d9d3c4cS猫头猫        } catch {
4504d9d3c4cS猫头猫            return null;
4514d9d3c4cS猫头猫        }
4524d9d3c4cS猫头猫    }
453927dbe93S猫头猫}
4541a5528a0S猫头猫
455927dbe93S猫头猫let plugins: Array<Plugin> = [];
456927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
457927dbe93S猫头猫
458927dbe93S猫头猫async function setup() {
459927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
460927dbe93S猫头猫    try {
461927dbe93S猫头猫        // 加载插件
462927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
463927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
464927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
4651e263108S猫头猫            trace('初始化插件', _pluginUrl);
4661e263108S猫头猫            if (
4671e263108S猫头猫                _pluginUrl.isFile() &&
4681e263108S猫头猫                (_pluginUrl.name?.endsWith?.('.js') ||
4691e263108S猫头猫                    _pluginUrl.path?.endsWith?.('.js'))
4701e263108S猫头猫            ) {
471927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
472927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
4734060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
4744060c00aS猫头猫                    p => p.hash === plugin.hash,
4754060c00aS猫头猫                );
476927dbe93S猫头猫                if (_pluginIndex !== -1) {
477927dbe93S猫头猫                    // 重复插件,直接忽略
478927dbe93S猫头猫                    return;
479927dbe93S猫头猫                }
480927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
481927dbe93S猫头猫            }
482927dbe93S猫头猫        }
483927dbe93S猫头猫
484927dbe93S猫头猫        plugins = _plugins;
485927dbe93S猫头猫        pluginStateMapper.notify();
486927dbe93S猫头猫    } catch (e: any) {
4874060c00aS猫头猫        ToastAndroid.show(
4884060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
4894060c00aS猫头猫            ToastAndroid.LONG,
4904060c00aS猫头猫        );
4911a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
492927dbe93S猫头猫        throw e;
493927dbe93S猫头猫    }
494927dbe93S猫头猫}
495927dbe93S猫头猫
496927dbe93S猫头猫// 安装插件
497927dbe93S猫头猫async function installPlugin(pluginPath: string) {
498b50427a2S猫头猫    if (pluginPath.endsWith('.js')) {
499927dbe93S猫头猫        const funcCode = await readFile(pluginPath, 'utf8');
500927dbe93S猫头猫        const plugin = new Plugin(funcCode, pluginPath);
501927dbe93S猫头猫        const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
502927dbe93S猫头猫        if (_pluginIndex !== -1) {
5034d9d3c4cS猫头猫            throw new Error('插件已安装');
504927dbe93S猫头猫        }
505927dbe93S猫头猫        if (plugin.hash !== '') {
506927dbe93S猫头猫            const fn = nanoid();
507927dbe93S猫头猫            const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
508927dbe93S猫头猫            await copyFile(pluginPath, _pluginPath);
509927dbe93S猫头猫            plugin.path = _pluginPath;
510927dbe93S猫头猫            plugins = plugins.concat(plugin);
511927dbe93S猫头猫            pluginStateMapper.notify();
5124d9d3c4cS猫头猫            return;
513927dbe93S猫头猫        }
5144d9d3c4cS猫头猫        throw new Error('插件无法解析');
515927dbe93S猫头猫    }
5164d9d3c4cS猫头猫    throw new Error('插件不存在');
517927dbe93S猫头猫}
518927dbe93S猫头猫
51958992c6bS猫头猫async function installPluginFromUrl(url: string) {
52058992c6bS猫头猫    try {
52158992c6bS猫头猫        const funcCode = (await axios.get(url)).data;
52258992c6bS猫头猫        if (funcCode) {
52358992c6bS猫头猫            const plugin = new Plugin(funcCode, '');
52458992c6bS猫头猫            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
52558992c6bS猫头猫            if (_pluginIndex !== -1) {
52658992c6bS猫头猫                throw new Error('插件已安装');
52758992c6bS猫头猫            }
52858992c6bS猫头猫            if (plugin.hash !== '') {
52958992c6bS猫头猫                const fn = nanoid();
53058992c6bS猫头猫                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
53158992c6bS猫头猫                await writeFile(_pluginPath, funcCode, 'utf8');
53258992c6bS猫头猫                plugin.path = _pluginPath;
53358992c6bS猫头猫                plugins = plugins.concat(plugin);
53458992c6bS猫头猫                pluginStateMapper.notify();
53558992c6bS猫头猫                return;
53658992c6bS猫头猫            }
53758992c6bS猫头猫            throw new Error('插件无法解析');
53858992c6bS猫头猫        }
53958992c6bS猫头猫    } catch (e) {
54058992c6bS猫头猫        errorLog('URL安装插件失败', e);
54158992c6bS猫头猫        throw new Error('插件安装失败');
54258992c6bS猫头猫    }
54358992c6bS猫头猫}
54458992c6bS猫头猫
545927dbe93S猫头猫/** 卸载插件 */
546927dbe93S猫头猫async function uninstallPlugin(hash: string) {
547927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
548927dbe93S猫头猫    if (targetIndex !== -1) {
549927dbe93S猫头猫        try {
550*24e5e74aS猫头猫            const pluginName = plugins[targetIndex].name;
551927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
552927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
553927dbe93S猫头猫            pluginStateMapper.notify();
554*24e5e74aS猫头猫            if (plugins.every(_ => _.name !== pluginName)) {
555*24e5e74aS猫头猫                await MediaMeta.removePlugin(pluginName);
556*24e5e74aS猫头猫            }
557927dbe93S猫头猫        } catch {}
558927dbe93S猫头猫    }
559927dbe93S猫头猫}
560927dbe93S猫头猫
561927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
562927dbe93S猫头猫    return getByName(mediaItem.platform);
563927dbe93S猫头猫}
564927dbe93S猫头猫
565927dbe93S猫头猫function getByHash(hash: string) {
566927dbe93S猫头猫    return plugins.find(_ => _.hash === hash);
567927dbe93S猫头猫}
568927dbe93S猫头猫
569927dbe93S猫头猫function getByName(name: string) {
570927dbe93S猫头猫    return plugins.find(_ => _.name === name);
571927dbe93S猫头猫}
572927dbe93S猫头猫
573927dbe93S猫头猫function getValidPlugins() {
574927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
575927dbe93S猫头猫}
576927dbe93S猫头猫
577927dbe93S猫头猫const PluginManager = {
578927dbe93S猫头猫    setup,
579927dbe93S猫头猫    installPlugin,
58058992c6bS猫头猫    installPluginFromUrl,
581927dbe93S猫头猫    uninstallPlugin,
582927dbe93S猫头猫    getByMedia,
583927dbe93S猫头猫    getByHash,
584927dbe93S猫头猫    getByName,
585927dbe93S猫头猫    getValidPlugins,
5865276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
5875276aef9S猫头猫};
588927dbe93S猫头猫
589927dbe93S猫头猫export default PluginManager;
590