xref: /MusicFree/src/core/pluginManager.ts (revision cfa0fc0757dad620cd0b0533a949d86b17086d32)
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';
22*cfa0fc07S猫头猫import {
23*cfa0fc07S猫头猫    CacheControl,
24*cfa0fc07S猫头猫    internalSerialzeKey,
25*cfa0fc07S猫头猫    internalSymbolKey,
26*cfa0fc07S猫头猫} from '@/constants/commonConst';
27927dbe93S猫头猫import Download from './download';
28927dbe93S猫头猫import delay from '@/utils/delay';
294d9d3c4cS猫头猫import * as cheerio from 'cheerio';
30927dbe93S猫头猫
31927dbe93S猫头猫axios.defaults.timeout = 1500;
32927dbe93S猫头猫
33927dbe93S猫头猫const sha256 = CryptoJs.SHA256;
34927dbe93S猫头猫
35*cfa0fc07S猫头猫export enum PluginStateCode {
36927dbe93S猫头猫    /** 版本不匹配 */
37927dbe93S猫头猫    VersionNotMatch = 'VERSION NOT MATCH',
38927dbe93S猫头猫    /** 无法解析 */
39927dbe93S猫头猫    CannotParse = 'CANNOT PARSE',
40927dbe93S猫头猫}
41927dbe93S猫头猫
42927dbe93S猫头猫export class Plugin {
43927dbe93S猫头猫    /** 插件名 */
44927dbe93S猫头猫    public name: string;
45927dbe93S猫头猫    /** 插件的hash,作为唯一id */
46927dbe93S猫头猫    public hash: string;
47927dbe93S猫头猫    /** 插件状态:激活、关闭、错误 */
48927dbe93S猫头猫    public state: 'enabled' | 'disabled' | 'error';
49927dbe93S猫头猫    /** 插件支持的搜索类型 */
50927dbe93S猫头猫    public supportedSearchType?: string;
51927dbe93S猫头猫    /** 插件状态信息 */
52927dbe93S猫头猫    public stateCode?: PluginStateCode;
53927dbe93S猫头猫    /** 插件的实例 */
54927dbe93S猫头猫    public instance: IPlugin.IPluginInstance;
55927dbe93S猫头猫    /** 插件路径 */
56927dbe93S猫头猫    public path: string;
57927dbe93S猫头猫    /** 插件方法 */
58927dbe93S猫头猫    public methods: PluginMethods;
59927dbe93S猫头猫
60927dbe93S猫头猫    constructor(funcCode: string, pluginPath: string) {
61927dbe93S猫头猫        this.state = 'enabled';
62927dbe93S猫头猫        let _instance: IPlugin.IPluginInstance;
63927dbe93S猫头猫        try {
644060c00aS猫头猫            // eslint-disable-next-line no-new-func
65927dbe93S猫头猫            _instance = Function(`
66927dbe93S猫头猫      'use strict';
67927dbe93S猫头猫      try {
68927dbe93S猫头猫        return ${funcCode};
69927dbe93S猫头猫      } catch(e) {
70927dbe93S猫头猫        return null;
71927dbe93S猫头猫      }
724d9d3c4cS猫头猫    `)()({CryptoJs, axios, dayjs, cheerio});
73927dbe93S猫头猫            this.checkValid(_instance);
74927dbe93S猫头猫        } catch (e: any) {
75927dbe93S猫头猫            this.state = 'error';
76927dbe93S猫头猫            this.stateCode = PluginStateCode.CannotParse;
77927dbe93S猫头猫            if (e?.stateCode) {
78927dbe93S猫头猫                this.stateCode = e.stateCode;
79927dbe93S猫头猫            }
80927dbe93S猫头猫            errorLog(`${pluginPath}插件无法解析 `, {
81927dbe93S猫头猫                stateCode: this.stateCode,
82927dbe93S猫头猫                message: e?.message,
83927dbe93S猫头猫                stack: e?.stack,
84927dbe93S猫头猫            });
85927dbe93S猫头猫            _instance = e?.instance ?? {
86927dbe93S猫头猫                _path: '',
87927dbe93S猫头猫                platform: '',
88927dbe93S猫头猫                appVersion: '',
8920e6a092S猫头猫                async getMediaSource() {
90927dbe93S猫头猫                    return null;
91927dbe93S猫头猫                },
92927dbe93S猫头猫                async search() {
93927dbe93S猫头猫                    return {};
94927dbe93S猫头猫                },
95927dbe93S猫头猫                async getAlbumInfo() {
96927dbe93S猫头猫                    return null;
97927dbe93S猫头猫                },
98927dbe93S猫头猫            };
99927dbe93S猫头猫        }
100927dbe93S猫头猫        this.instance = _instance;
101927dbe93S猫头猫        this.path = pluginPath;
102927dbe93S猫头猫        this.name = _instance.platform;
103927dbe93S猫头猫        if (this.instance.platform === '') {
104927dbe93S猫头猫            this.hash = '';
105927dbe93S猫头猫        } else {
106927dbe93S猫头猫            this.hash = sha256(funcCode).toString();
107927dbe93S猫头猫        }
108927dbe93S猫头猫
109927dbe93S猫头猫        // 放在最后
110927dbe93S猫头猫        this.methods = new PluginMethods(this);
111927dbe93S猫头猫    }
112927dbe93S猫头猫
113927dbe93S猫头猫    private checkValid(_instance: IPlugin.IPluginInstance) {
114927dbe93S猫头猫        /** 版本号校验 */
115927dbe93S猫头猫        if (
116927dbe93S猫头猫            _instance.appVersion &&
117927dbe93S猫头猫            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
118927dbe93S猫头猫        ) {
119927dbe93S猫头猫            throw {
120927dbe93S猫头猫                instance: _instance,
121927dbe93S猫头猫                stateCode: PluginStateCode.VersionNotMatch,
122927dbe93S猫头猫            };
123927dbe93S猫头猫        }
124927dbe93S猫头猫        return true;
125927dbe93S猫头猫    }
126927dbe93S猫头猫}
127927dbe93S猫头猫
128927dbe93S猫头猫/** 有缓存等信息 */
129927dbe93S猫头猫class PluginMethods implements IPlugin.IPluginInstanceMethods {
130927dbe93S猫头猫    private plugin;
131927dbe93S猫头猫    constructor(plugin: Plugin) {
132927dbe93S猫头猫        this.plugin = plugin;
133927dbe93S猫头猫    }
134927dbe93S猫头猫    /** 搜索 */
135927dbe93S猫头猫    async search<T extends ICommon.SupportMediaType>(
136927dbe93S猫头猫        query: string,
137927dbe93S猫头猫        page: number,
138927dbe93S猫头猫        type: T,
139927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
140927dbe93S猫头猫        if (!this.plugin.instance.search) {
141927dbe93S猫头猫            return {
142927dbe93S猫头猫                isEnd: true,
143927dbe93S猫头猫                data: [],
144927dbe93S猫头猫            };
145927dbe93S猫头猫        }
146927dbe93S猫头猫
1474060c00aS猫头猫        const result =
1484060c00aS猫头猫            (await this.plugin.instance.search(query, page, type)) ?? {};
149927dbe93S猫头猫        if (Array.isArray(result.data)) {
150927dbe93S猫头猫            result.data.forEach(_ => {
151927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
152927dbe93S猫头猫            });
153927dbe93S猫头猫            return {
154927dbe93S猫头猫                isEnd: result.isEnd ?? true,
155927dbe93S猫头猫                data: result.data,
156927dbe93S猫头猫            };
157927dbe93S猫头猫        }
158927dbe93S猫头猫        return {
159927dbe93S猫头猫            isEnd: true,
160927dbe93S猫头猫            data: [],
161927dbe93S猫头猫        };
162927dbe93S猫头猫    }
163927dbe93S猫头猫
164927dbe93S猫头猫    /** 获取真实源 */
16520e6a092S猫头猫    async getMediaSource(
166927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
167927dbe93S猫头猫        retryCount = 1,
16820e6a092S猫头猫    ): Promise<IPlugin.IMediaSourceResult> {
169927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
170927dbe93S猫头猫        const localPath =
171927dbe93S猫头猫            musicItem?.[internalSymbolKey]?.localPath ??
172927dbe93S猫头猫            Download.getDownloaded(musicItem)?.[internalSymbolKey]?.localPath;
173927dbe93S猫头猫        if (localPath && (await exists(localPath))) {
1745276aef9S猫头猫            trace('播放', '本地播放');
175927dbe93S猫头猫            return {
176927dbe93S猫头猫                url: localPath,
177927dbe93S猫头猫            };
178927dbe93S猫头猫        }
179927dbe93S猫头猫        // 2. 缓存播放
180*cfa0fc07S猫头猫        // todo: 无网络情况下强制使用缓存播放 no-cache: 无网络情况下使用cache
181927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
182*cfa0fc07S猫头猫        if (
183*cfa0fc07S猫头猫            mediaCache &&
184*cfa0fc07S猫头猫            mediaCache?.url &&
185*cfa0fc07S猫头猫            mediaCache.cache === CacheControl.Cache
186*cfa0fc07S猫头猫        ) {
1875276aef9S猫头猫            trace('播放', '缓存播放');
188927dbe93S猫头猫            return {
189927dbe93S猫头猫                url: mediaCache.url,
190927dbe93S猫头猫                headers: mediaCache.headers,
1914060c00aS猫头猫                userAgent:
1924060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
193927dbe93S猫头猫            };
194927dbe93S猫头猫        }
195927dbe93S猫头猫        // 3. 插件解析
19620e6a092S猫头猫        if (!this.plugin.instance.getMediaSource) {
197927dbe93S猫头猫            return {url: musicItem.url};
198927dbe93S猫头猫        }
199927dbe93S猫头猫        try {
200*cfa0fc07S猫头猫            const {url, headers, cacheControl} =
20120e6a092S猫头猫                (await this.plugin.instance.getMediaSource(musicItem)) ?? {};
202927dbe93S猫头猫            if (!url) {
203927dbe93S猫头猫                throw new Error();
204927dbe93S猫头猫            }
2055276aef9S猫头猫            trace('播放', '插件播放');
206927dbe93S猫头猫            const result = {
207927dbe93S猫头猫                url,
208927dbe93S猫头猫                headers,
209927dbe93S猫头猫                userAgent: headers?.['user-agent'],
210*cfa0fc07S猫头猫                cacheControl: cacheControl ?? CacheControl.Cache,
211*cfa0fc07S猫头猫            } as IPlugin.IMediaSourceResult;
212927dbe93S猫头猫
213*cfa0fc07S猫头猫            if (cacheControl !== CacheControl.NoStore) {
214927dbe93S猫头猫                Cache.update(musicItem, result);
215752ffc5aS猫头猫            }
216*cfa0fc07S猫头猫
217927dbe93S猫头猫            return result;
218927dbe93S猫头猫        } catch (e: any) {
219927dbe93S猫头猫            if (retryCount > 0) {
220927dbe93S猫头猫                await delay(150);
22120e6a092S猫头猫                return this.getMediaSource(musicItem, --retryCount);
222927dbe93S猫头猫            }
223927dbe93S猫头猫            errorLog('获取真实源失败', e?.message);
224927dbe93S猫头猫            throw e;
225927dbe93S猫头猫        }
226927dbe93S猫头猫    }
227927dbe93S猫头猫
228927dbe93S猫头猫    /** 获取音乐详情 */
229927dbe93S猫头猫    async getMusicInfo(
230927dbe93S猫头猫        musicItem: ICommon.IMediaBase,
231927dbe93S猫头猫    ): Promise<IMusic.IMusicItem | null> {
232927dbe93S猫头猫        if (!this.plugin.instance.getMusicInfo) {
233927dbe93S猫头猫            return musicItem as IMusic.IMusicItem;
234927dbe93S猫头猫        }
235927dbe93S猫头猫        return (
236927dbe93S猫头猫            this.plugin.instance.getMusicInfo(
237927dbe93S猫头猫                resetMediaItem(musicItem, undefined, true),
238927dbe93S猫头猫            ) ?? musicItem
239927dbe93S猫头猫        );
240927dbe93S猫头猫    }
241927dbe93S猫头猫
242927dbe93S猫头猫    /** 获取歌词 */
243927dbe93S猫头猫    async getLyric(
244927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
245927dbe93S猫头猫        from?: IMusic.IMusicItemBase,
246927dbe93S猫头猫    ): Promise<ILyric.ILyricSource | null> {
247927dbe93S猫头猫        // 1.额外存储的meta信息
248927dbe93S猫头猫        const meta = MediaMeta.get(musicItem);
249927dbe93S猫头猫        if (meta && meta.associatedLrc) {
250927dbe93S猫头猫            // 有关联歌词
251927dbe93S猫头猫            if (
252927dbe93S猫头猫                isSameMediaItem(musicItem, from) ||
253927dbe93S猫头猫                isSameMediaItem(meta.associatedLrc, musicItem)
254927dbe93S猫头猫            ) {
255927dbe93S猫头猫                // 形成环路,断开当前的环
256927dbe93S猫头猫                await MediaMeta.update(musicItem, {
257927dbe93S猫头猫                    associatedLrc: undefined,
258927dbe93S猫头猫                });
259927dbe93S猫头猫                // 无歌词
260927dbe93S猫头猫                return null;
261927dbe93S猫头猫            }
262927dbe93S猫头猫            // 获取关联歌词
2634060c00aS猫头猫            const result = await this.getLyric(
2644060c00aS猫头猫                meta.associatedLrc,
2654060c00aS猫头猫                from ?? musicItem,
2664060c00aS猫头猫            );
267927dbe93S猫头猫            if (result) {
268927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
269927dbe93S猫头猫                return result;
270927dbe93S猫头猫            }
271927dbe93S猫头猫        }
272927dbe93S猫头猫        const cache = Cache.get(musicItem);
273927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
274927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
275927dbe93S猫头猫        // 如果存在文本
276927dbe93S猫头猫        if (rawLrc) {
277927dbe93S猫头猫            return {
278927dbe93S猫头猫                rawLrc,
279927dbe93S猫头猫                lrc: lrcUrl,
280927dbe93S猫头猫            };
281927dbe93S猫头猫        }
282927dbe93S猫头猫        // 2.本地缓存
283927dbe93S猫头猫        const localLrc =
284927dbe93S猫头猫            meta?.[internalSerialzeKey]?.local?.localLrc ||
285927dbe93S猫头猫            cache?.[internalSerialzeKey]?.local?.localLrc;
286927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
287927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
288927dbe93S猫头猫            return {
289927dbe93S猫头猫                rawLrc,
290927dbe93S猫头猫                lrc: lrcUrl,
291927dbe93S猫头猫            };
292927dbe93S猫头猫        }
293927dbe93S猫头猫        // 3.优先使用url
294927dbe93S猫头猫        if (lrcUrl) {
295927dbe93S猫头猫            try {
296927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
2972a3194f5S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
298927dbe93S猫头猫                return {
299927dbe93S猫头猫                    rawLrc,
300927dbe93S猫头猫                    lrc: lrcUrl,
301927dbe93S猫头猫                };
302927dbe93S猫头猫            } catch {
303927dbe93S猫头猫                lrcUrl = undefined;
304927dbe93S猫头猫            }
305927dbe93S猫头猫        }
306927dbe93S猫头猫        // 4. 如果地址失效
307927dbe93S猫头猫        if (!lrcUrl) {
308927dbe93S猫头猫            // 插件获得url
309927dbe93S猫头猫            try {
310927dbe93S猫头猫                const lrcSource = await this.plugin.instance?.getLyric?.(
311927dbe93S猫头猫                    resetMediaItem(musicItem, undefined, true),
312927dbe93S猫头猫                );
313927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
314927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
315927dbe93S猫头猫            } catch (e: any) {
316927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
317927dbe93S猫头猫            }
318927dbe93S猫头猫        }
319927dbe93S猫头猫        // 5. 最后一次请求
320927dbe93S猫头猫        if (rawLrc || lrcUrl) {
321927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
322927dbe93S猫头猫            if (lrcUrl) {
323927dbe93S猫头猫                try {
3242a3194f5S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
325927dbe93S猫头猫                } catch {}
326927dbe93S猫头猫            }
327927dbe93S猫头猫            if (rawLrc) {
328927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
329927dbe93S猫头猫                // 写入缓存
330927dbe93S猫头猫                Cache.update(musicItem, [
331927dbe93S猫头猫                    [`${internalSerialzeKey}.local.localLrc`, filename],
332927dbe93S猫头猫                ]);
333927dbe93S猫头猫                // 如果有meta
334927dbe93S猫头猫                if (meta) {
335927dbe93S猫头猫                    MediaMeta.update(musicItem, [
336927dbe93S猫头猫                        [`${internalSerialzeKey}.local.localLrc`, filename],
337927dbe93S猫头猫                    ]);
338927dbe93S猫头猫                }
339927dbe93S猫头猫                return {
340927dbe93S猫头猫                    rawLrc,
341927dbe93S猫头猫                    lrc: lrcUrl,
342927dbe93S猫头猫                };
343927dbe93S猫头猫            }
344927dbe93S猫头猫        }
345927dbe93S猫头猫
346927dbe93S猫头猫        return null;
347927dbe93S猫头猫    }
348927dbe93S猫头猫
349927dbe93S猫头猫    /** 获取歌词文本 */
350927dbe93S猫头猫    async getLyricText(
351927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
352927dbe93S猫头猫    ): Promise<string | undefined> {
353927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
354927dbe93S猫头猫    }
355927dbe93S猫头猫
356927dbe93S猫头猫    /** 获取专辑信息 */
357927dbe93S猫头猫    async getAlbumInfo(
358927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
359927dbe93S猫头猫    ): Promise<IAlbum.IAlbumItem | null> {
360927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
361927dbe93S猫头猫            return {...albumItem, musicList: []};
362927dbe93S猫头猫        }
363927dbe93S猫头猫        try {
364927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
365927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
366927dbe93S猫头猫            );
3675276aef9S猫头猫            if (!result) {
3685276aef9S猫头猫                throw new Error();
3695276aef9S猫头猫            }
370927dbe93S猫头猫            result?.musicList?.forEach(_ => {
371927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
372927dbe93S猫头猫            });
3735276aef9S猫头猫
3745276aef9S猫头猫            return {...albumItem, ...result};
375927dbe93S猫头猫        } catch {
376927dbe93S猫头猫            return {...albumItem, musicList: []};
377927dbe93S猫头猫        }
378927dbe93S猫头猫    }
379927dbe93S猫头猫
380927dbe93S猫头猫    /** 查询作者信息 */
381927dbe93S猫头猫    async queryArtistWorks<T extends IArtist.ArtistMediaType>(
382927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
383927dbe93S猫头猫        page: number,
384927dbe93S猫头猫        type: T,
385927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
386927dbe93S猫头猫        if (!this.plugin.instance.queryArtistWorks) {
387927dbe93S猫头猫            return {
388927dbe93S猫头猫                isEnd: true,
389927dbe93S猫头猫                data: [],
390927dbe93S猫头猫            };
391927dbe93S猫头猫        }
392927dbe93S猫头猫        try {
393927dbe93S猫头猫            const result = await this.plugin.instance.queryArtistWorks(
394927dbe93S猫头猫                artistItem,
395927dbe93S猫头猫                page,
396927dbe93S猫头猫                type,
397927dbe93S猫头猫            );
398927dbe93S猫头猫            if (!result.data) {
399927dbe93S猫头猫                return {
400927dbe93S猫头猫                    isEnd: true,
401927dbe93S猫头猫                    data: [],
402927dbe93S猫头猫                };
403927dbe93S猫头猫            }
404927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
405927dbe93S猫头猫            return {
406927dbe93S猫头猫                isEnd: result.isEnd ?? true,
407927dbe93S猫头猫                data: result.data,
408927dbe93S猫头猫            };
409927dbe93S猫头猫        } catch (e) {
410927dbe93S猫头猫            throw e;
411927dbe93S猫头猫        }
412927dbe93S猫头猫    }
41308380090S猫头猫
41408380090S猫头猫    /** 导入歌单 */
41508380090S猫头猫    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
41608380090S猫头猫        try {
41708380090S猫头猫            const result =
41808380090S猫头猫                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
41908380090S猫头猫            result.forEach(_ => resetMediaItem(_, this.plugin.name));
42008380090S猫头猫            return result;
42108380090S猫头猫        } catch {
42208380090S猫头猫            return [];
42308380090S猫头猫        }
42408380090S猫头猫    }
4254d9d3c4cS猫头猫    /** 导入单曲 */
4264d9d3c4cS猫头猫    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
4274d9d3c4cS猫头猫        try {
4284d9d3c4cS猫头猫            const result = await this.plugin.instance?.importMusicItem?.(
4294d9d3c4cS猫头猫                urlLike,
4304d9d3c4cS猫头猫            );
4314d9d3c4cS猫头猫            if (!result) {
4324d9d3c4cS猫头猫                throw new Error();
4334d9d3c4cS猫头猫            }
4344d9d3c4cS猫头猫            resetMediaItem(result, this.plugin.name);
4354d9d3c4cS猫头猫            return result;
4364d9d3c4cS猫头猫        } catch {
4374d9d3c4cS猫头猫            return null;
4384d9d3c4cS猫头猫        }
4394d9d3c4cS猫头猫    }
440927dbe93S猫头猫}
4411a5528a0S猫头猫
442927dbe93S猫头猫let plugins: Array<Plugin> = [];
443927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
444927dbe93S猫头猫
445927dbe93S猫头猫async function setup() {
446927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
447927dbe93S猫头猫    try {
448927dbe93S猫头猫        // 加载插件
449927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
450927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
451927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
452927dbe93S猫头猫
453927dbe93S猫头猫            if (_pluginUrl.isFile() && _pluginUrl.name.endsWith('.js')) {
454927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
455927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
4564060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
4574060c00aS猫头猫                    p => p.hash === plugin.hash,
4584060c00aS猫头猫                );
459927dbe93S猫头猫                if (_pluginIndex !== -1) {
460927dbe93S猫头猫                    // 重复插件,直接忽略
461927dbe93S猫头猫                    return;
462927dbe93S猫头猫                }
463927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
464927dbe93S猫头猫            }
465927dbe93S猫头猫        }
466927dbe93S猫头猫
467927dbe93S猫头猫        plugins = _plugins;
468927dbe93S猫头猫        pluginStateMapper.notify();
469927dbe93S猫头猫    } catch (e: any) {
4704060c00aS猫头猫        ToastAndroid.show(
4714060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
4724060c00aS猫头猫            ToastAndroid.LONG,
4734060c00aS猫头猫        );
4741a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
475927dbe93S猫头猫        throw e;
476927dbe93S猫头猫    }
477927dbe93S猫头猫}
478927dbe93S猫头猫
479927dbe93S猫头猫// 安装插件
480927dbe93S猫头猫async function installPlugin(pluginPath: string) {
481*cfa0fc07S猫头猫    // let checkPath = decodeURIComponent(pluginPath);
482*cfa0fc07S猫头猫    // trace(checkPath, await exists(checkPath));
483*cfa0fc07S猫头猫    // trace(pluginPath, await exists(pluginPath));
484*cfa0fc07S猫头猫    // trace(pluginPath.substring(7), await exists(pluginPath.substring(7)));
485*cfa0fc07S猫头猫    // trace(checkPath.substring(7), await exists(checkPath.substring(7)));
486b50427a2S猫头猫    if (pluginPath.endsWith('.js')) {
487927dbe93S猫头猫        const funcCode = await readFile(pluginPath, 'utf8');
488927dbe93S猫头猫        const plugin = new Plugin(funcCode, pluginPath);
489927dbe93S猫头猫        const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
490927dbe93S猫头猫        if (_pluginIndex !== -1) {
4914d9d3c4cS猫头猫            throw new Error('插件已安装');
492927dbe93S猫头猫        }
493927dbe93S猫头猫        if (plugin.hash !== '') {
494927dbe93S猫头猫            const fn = nanoid();
495927dbe93S猫头猫            const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
496927dbe93S猫头猫            await copyFile(pluginPath, _pluginPath);
497927dbe93S猫头猫            plugin.path = _pluginPath;
498927dbe93S猫头猫            plugins = plugins.concat(plugin);
499927dbe93S猫头猫            pluginStateMapper.notify();
5004d9d3c4cS猫头猫            return;
501927dbe93S猫头猫        }
5024d9d3c4cS猫头猫        throw new Error('插件无法解析');
503927dbe93S猫头猫    }
5044d9d3c4cS猫头猫    throw new Error('插件不存在');
505927dbe93S猫头猫}
506927dbe93S猫头猫
507927dbe93S猫头猫/** 卸载插件 */
508927dbe93S猫头猫async function uninstallPlugin(hash: string) {
509927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
510927dbe93S猫头猫    if (targetIndex !== -1) {
511927dbe93S猫头猫        try {
512927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
513927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
514927dbe93S猫头猫            pluginStateMapper.notify();
515927dbe93S猫头猫        } catch {}
516927dbe93S猫头猫    }
517927dbe93S猫头猫}
518927dbe93S猫头猫
519927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
520927dbe93S猫头猫    return getByName(mediaItem.platform);
521927dbe93S猫头猫}
522927dbe93S猫头猫
523927dbe93S猫头猫function getByHash(hash: string) {
524927dbe93S猫头猫    return plugins.find(_ => _.hash === hash);
525927dbe93S猫头猫}
526927dbe93S猫头猫
527927dbe93S猫头猫function getByName(name: string) {
528927dbe93S猫头猫    return plugins.find(_ => _.name === name);
529927dbe93S猫头猫}
530927dbe93S猫头猫
531927dbe93S猫头猫function getValidPlugins() {
532927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
533927dbe93S猫头猫}
534927dbe93S猫头猫
535927dbe93S猫头猫const PluginManager = {
536927dbe93S猫头猫    setup,
537927dbe93S猫头猫    installPlugin,
538927dbe93S猫头猫    uninstallPlugin,
539927dbe93S猫头猫    getByMedia,
540927dbe93S猫头猫    getByHash,
541927dbe93S猫头猫    getByName,
542927dbe93S猫头猫    getValidPlugins,
5435276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
5445276aef9S猫头猫};
545927dbe93S猫头猫
546927dbe93S猫头猫export default PluginManager;
547