xref: /MusicFree/src/core/pluginManager.ts (revision 752ffc5abb93dbe20ee1b9fef4e24fadb07be115)
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';
22927dbe93S猫头猫import {internalSerialzeKey, internalSymbolKey} from '@/constants/commonConst';
23927dbe93S猫头猫import Download from './download';
24927dbe93S猫头猫import delay from '@/utils/delay';
25927dbe93S猫头猫
26927dbe93S猫头猫axios.defaults.timeout = 1500;
27927dbe93S猫头猫
28927dbe93S猫头猫const sha256 = CryptoJs.SHA256;
29927dbe93S猫头猫
30927dbe93S猫头猫enum PluginStateCode {
31927dbe93S猫头猫    /** 版本不匹配 */
32927dbe93S猫头猫    VersionNotMatch = 'VERSION NOT MATCH',
33927dbe93S猫头猫    /** 插件不完整 */
34927dbe93S猫头猫    NotComplete = 'NOT COMPLETE',
35927dbe93S猫头猫    /** 无法解析 */
36927dbe93S猫头猫    CannotParse = 'CANNOT PARSE',
37927dbe93S猫头猫}
38927dbe93S猫头猫
39927dbe93S猫头猫export class Plugin {
40927dbe93S猫头猫    /** 插件名 */
41927dbe93S猫头猫    public name: string;
42927dbe93S猫头猫    /** 插件的hash,作为唯一id */
43927dbe93S猫头猫    public hash: string;
44927dbe93S猫头猫    /** 插件状态:激活、关闭、错误 */
45927dbe93S猫头猫    public state: 'enabled' | 'disabled' | 'error';
46927dbe93S猫头猫    /** 插件支持的搜索类型 */
47927dbe93S猫头猫    public supportedSearchType?: string;
48927dbe93S猫头猫    /** 插件状态信息 */
49927dbe93S猫头猫    public stateCode?: PluginStateCode;
50927dbe93S猫头猫    /** 插件的实例 */
51927dbe93S猫头猫    public instance: IPlugin.IPluginInstance;
52927dbe93S猫头猫    /** 插件路径 */
53927dbe93S猫头猫    public path: string;
54927dbe93S猫头猫    /** 插件方法 */
55927dbe93S猫头猫    public methods: PluginMethods;
56927dbe93S猫头猫
57927dbe93S猫头猫    constructor(funcCode: string, pluginPath: string) {
58927dbe93S猫头猫        this.state = 'enabled';
59927dbe93S猫头猫        let _instance: IPlugin.IPluginInstance;
60927dbe93S猫头猫        try {
614060c00aS猫头猫            // eslint-disable-next-line no-new-func
62927dbe93S猫头猫            _instance = Function(`
63927dbe93S猫头猫      'use strict';
64927dbe93S猫头猫      try {
65927dbe93S猫头猫        return ${funcCode};
66927dbe93S猫头猫      } catch(e) {
67927dbe93S猫头猫        return null;
68927dbe93S猫头猫      }
69927dbe93S猫头猫    `)()({CryptoJs, axios, dayjs});
70927dbe93S猫头猫            this.checkValid(_instance);
71927dbe93S猫头猫        } catch (e: any) {
72927dbe93S猫头猫            this.state = 'error';
73927dbe93S猫头猫            this.stateCode = PluginStateCode.CannotParse;
74927dbe93S猫头猫            if (e?.stateCode) {
75927dbe93S猫头猫                this.stateCode = e.stateCode;
76927dbe93S猫头猫            }
77927dbe93S猫头猫            errorLog(`${pluginPath}插件无法解析 `, {
78927dbe93S猫头猫                stateCode: this.stateCode,
79927dbe93S猫头猫                message: e?.message,
80927dbe93S猫头猫                stack: e?.stack,
81927dbe93S猫头猫            });
82927dbe93S猫头猫            _instance = e?.instance ?? {
83927dbe93S猫头猫                _path: '',
84927dbe93S猫头猫                platform: '',
85927dbe93S猫头猫                appVersion: '',
86927dbe93S猫头猫                async getMusicTrack() {
87927dbe93S猫头猫                    return null;
88927dbe93S猫头猫                },
89927dbe93S猫头猫                async search() {
90927dbe93S猫头猫                    return {};
91927dbe93S猫头猫                },
92927dbe93S猫头猫                async getAlbumInfo() {
93927dbe93S猫头猫                    return null;
94927dbe93S猫头猫                },
95927dbe93S猫头猫            };
96927dbe93S猫头猫        }
97927dbe93S猫头猫        this.instance = _instance;
98927dbe93S猫头猫        this.path = pluginPath;
99927dbe93S猫头猫        this.name = _instance.platform;
100927dbe93S猫头猫        if (this.instance.platform === '') {
101927dbe93S猫头猫            this.hash = '';
102927dbe93S猫头猫        } else {
103927dbe93S猫头猫            this.hash = sha256(funcCode).toString();
104927dbe93S猫头猫        }
105927dbe93S猫头猫
106927dbe93S猫头猫        // 放在最后
107927dbe93S猫头猫        this.methods = new PluginMethods(this);
108927dbe93S猫头猫    }
109927dbe93S猫头猫
110927dbe93S猫头猫    private checkValid(_instance: IPlugin.IPluginInstance) {
111927dbe93S猫头猫        // 总不会一个都没有吧
112927dbe93S猫头猫        const keys: Array<keyof IPlugin.IPluginInstance> = [
113927dbe93S猫头猫            'getAlbumInfo',
114927dbe93S猫头猫            'search',
115927dbe93S猫头猫            'getMusicTrack',
116927dbe93S猫头猫        ];
117927dbe93S猫头猫        if (keys.every(k => !_instance[k])) {
118927dbe93S猫头猫            throw {
119927dbe93S猫头猫                instance: _instance,
120927dbe93S猫头猫                stateCode: PluginStateCode.NotComplete,
121927dbe93S猫头猫            };
122927dbe93S猫头猫        }
123927dbe93S猫头猫        /** 版本号校验 */
124927dbe93S猫头猫        if (
125927dbe93S猫头猫            _instance.appVersion &&
126927dbe93S猫头猫            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
127927dbe93S猫头猫        ) {
128927dbe93S猫头猫            throw {
129927dbe93S猫头猫                instance: _instance,
130927dbe93S猫头猫                stateCode: PluginStateCode.VersionNotMatch,
131927dbe93S猫头猫            };
132927dbe93S猫头猫        }
133927dbe93S猫头猫        return true;
134927dbe93S猫头猫    }
135927dbe93S猫头猫}
136927dbe93S猫头猫
137927dbe93S猫头猫/** 有缓存等信息 */
138927dbe93S猫头猫class PluginMethods implements IPlugin.IPluginInstanceMethods {
139927dbe93S猫头猫    private plugin;
140927dbe93S猫头猫    constructor(plugin: Plugin) {
141927dbe93S猫头猫        this.plugin = plugin;
142927dbe93S猫头猫    }
143927dbe93S猫头猫    /** 搜索 */
144927dbe93S猫头猫    async search<T extends ICommon.SupportMediaType>(
145927dbe93S猫头猫        query: string,
146927dbe93S猫头猫        page: number,
147927dbe93S猫头猫        type: T,
148927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
149927dbe93S猫头猫        if (!this.plugin.instance.search) {
150927dbe93S猫头猫            return {
151927dbe93S猫头猫                isEnd: true,
152927dbe93S猫头猫                data: [],
153927dbe93S猫头猫            };
154927dbe93S猫头猫        }
155927dbe93S猫头猫
1564060c00aS猫头猫        const result =
1574060c00aS猫头猫            (await this.plugin.instance.search(query, page, type)) ?? {};
158927dbe93S猫头猫        if (Array.isArray(result.data)) {
159927dbe93S猫头猫            result.data.forEach(_ => {
160927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
161927dbe93S猫头猫            });
162927dbe93S猫头猫            return {
163927dbe93S猫头猫                isEnd: result.isEnd ?? true,
164927dbe93S猫头猫                data: result.data,
165927dbe93S猫头猫            };
166927dbe93S猫头猫        }
167927dbe93S猫头猫        return {
168927dbe93S猫头猫            isEnd: true,
169927dbe93S猫头猫            data: [],
170927dbe93S猫头猫        };
171927dbe93S猫头猫    }
172927dbe93S猫头猫
173927dbe93S猫头猫    /** 获取真实源 */
174927dbe93S猫头猫    async getMusicTrack(
175927dbe93S猫头猫        musicItem: IMusic.IMusicItemBase,
176927dbe93S猫头猫        retryCount = 1,
177927dbe93S猫头猫    ): Promise<IPlugin.IMusicTrackResult> {
178927dbe93S猫头猫        // 1. 本地搜索 其实直接读mediameta就好了
179927dbe93S猫头猫        const localPath =
180927dbe93S猫头猫            musicItem?.[internalSymbolKey]?.localPath ??
181927dbe93S猫头猫            Download.getDownloaded(musicItem)?.[internalSymbolKey]?.localPath;
182927dbe93S猫头猫        if (localPath && (await exists(localPath))) {
1835276aef9S猫头猫            trace('播放', '本地播放');
184927dbe93S猫头猫            return {
185927dbe93S猫头猫                url: localPath,
186927dbe93S猫头猫            };
187927dbe93S猫头猫        }
188927dbe93S猫头猫        // 2. 缓存播放
189927dbe93S猫头猫        const mediaCache = Cache.get(musicItem);
190927dbe93S猫头猫        if (mediaCache && mediaCache?.url) {
1915276aef9S猫头猫            trace('播放', '缓存播放');
192927dbe93S猫头猫            return {
193927dbe93S猫头猫                url: mediaCache.url,
194927dbe93S猫头猫                headers: mediaCache.headers,
1954060c00aS猫头猫                userAgent:
1964060c00aS猫头猫                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
197927dbe93S猫头猫            };
198927dbe93S猫头猫        }
199927dbe93S猫头猫        // 3. 插件解析
200927dbe93S猫头猫        if (!this.plugin.instance.getMusicTrack) {
201927dbe93S猫头猫            return {url: musicItem.url};
202927dbe93S猫头猫        }
203927dbe93S猫头猫        try {
204*752ffc5aS猫头猫            const {url, headers, cache} =
205927dbe93S猫头猫                (await this.plugin.instance.getMusicTrack(musicItem)) ?? {};
206927dbe93S猫头猫            if (!url) {
207927dbe93S猫头猫                throw new Error();
208927dbe93S猫头猫            }
2095276aef9S猫头猫            trace('播放', '插件播放');
210927dbe93S猫头猫            const result = {
211927dbe93S猫头猫                url,
212927dbe93S猫头猫                headers,
213927dbe93S猫头猫                userAgent: headers?.['user-agent'],
214927dbe93S猫头猫            };
215927dbe93S猫头猫
216*752ffc5aS猫头猫            if (cache !== false) {
217927dbe93S猫头猫                Cache.update(musicItem, result);
218*752ffc5aS猫头猫            }
219927dbe93S猫头猫            return result;
220927dbe93S猫头猫        } catch (e: any) {
221927dbe93S猫头猫            if (retryCount > 0) {
222927dbe93S猫头猫                await delay(150);
223927dbe93S猫头猫                return this.getMusicTrack(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猫头猫            // 获取关联歌词
2654060c00aS猫头猫            const result = await this.getLyric(
2664060c00aS猫头猫                meta.associatedLrc,
2674060c00aS猫头猫                from ?? musicItem,
2684060c00aS猫头猫            );
269927dbe93S猫头猫            if (result) {
270927dbe93S猫头猫                // 如果有关联歌词,就返回关联歌词,深度优先
271927dbe93S猫头猫                return result;
272927dbe93S猫头猫            }
273927dbe93S猫头猫        }
274927dbe93S猫头猫        const cache = Cache.get(musicItem);
275927dbe93S猫头猫        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
276927dbe93S猫头猫        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
277927dbe93S猫头猫        // 如果存在文本
278927dbe93S猫头猫        if (rawLrc) {
279927dbe93S猫头猫            return {
280927dbe93S猫头猫                rawLrc,
281927dbe93S猫头猫                lrc: lrcUrl,
282927dbe93S猫头猫            };
283927dbe93S猫头猫        }
284927dbe93S猫头猫        // 2.本地缓存
285927dbe93S猫头猫        const localLrc =
286927dbe93S猫头猫            meta?.[internalSerialzeKey]?.local?.localLrc ||
287927dbe93S猫头猫            cache?.[internalSerialzeKey]?.local?.localLrc;
288927dbe93S猫头猫        if (localLrc && (await exists(localLrc))) {
289927dbe93S猫头猫            rawLrc = await readFile(localLrc, 'utf8');
290927dbe93S猫头猫            return {
291927dbe93S猫头猫                rawLrc,
292927dbe93S猫头猫                lrc: lrcUrl,
293927dbe93S猫头猫            };
294927dbe93S猫头猫        }
295927dbe93S猫头猫        // 3.优先使用url
296927dbe93S猫头猫        if (lrcUrl) {
297927dbe93S猫头猫            try {
298927dbe93S猫头猫                // 需要超时时间 axios timeout 但是没生效
2992a3194f5S猫头猫                rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
300927dbe93S猫头猫                return {
301927dbe93S猫头猫                    rawLrc,
302927dbe93S猫头猫                    lrc: lrcUrl,
303927dbe93S猫头猫                };
304927dbe93S猫头猫            } catch {
305927dbe93S猫头猫                lrcUrl = undefined;
306927dbe93S猫头猫            }
307927dbe93S猫头猫        }
308927dbe93S猫头猫        // 4. 如果地址失效
309927dbe93S猫头猫        if (!lrcUrl) {
310927dbe93S猫头猫            // 插件获得url
311927dbe93S猫头猫            try {
312927dbe93S猫头猫                const lrcSource = await this.plugin.instance?.getLyric?.(
313927dbe93S猫头猫                    resetMediaItem(musicItem, undefined, true),
314927dbe93S猫头猫                );
315927dbe93S猫头猫                rawLrc = lrcSource?.rawLrc;
316927dbe93S猫头猫                lrcUrl = lrcSource?.lrc;
317927dbe93S猫头猫            } catch (e: any) {
318927dbe93S猫头猫                trace('插件获取歌词失败', e?.message, 'error');
319927dbe93S猫头猫            }
320927dbe93S猫头猫        }
321927dbe93S猫头猫        // 5. 最后一次请求
322927dbe93S猫头猫        if (rawLrc || lrcUrl) {
323927dbe93S猫头猫            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
324927dbe93S猫头猫            if (lrcUrl) {
325927dbe93S猫头猫                try {
3262a3194f5S猫头猫                    rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
327927dbe93S猫头猫                } catch {}
328927dbe93S猫头猫            }
329927dbe93S猫头猫            if (rawLrc) {
330927dbe93S猫头猫                await writeFile(filename, rawLrc, 'utf8');
331927dbe93S猫头猫                // 写入缓存
332927dbe93S猫头猫                Cache.update(musicItem, [
333927dbe93S猫头猫                    [`${internalSerialzeKey}.local.localLrc`, filename],
334927dbe93S猫头猫                ]);
335927dbe93S猫头猫                // 如果有meta
336927dbe93S猫头猫                if (meta) {
337927dbe93S猫头猫                    MediaMeta.update(musicItem, [
338927dbe93S猫头猫                        [`${internalSerialzeKey}.local.localLrc`, filename],
339927dbe93S猫头猫                    ]);
340927dbe93S猫头猫                }
341927dbe93S猫头猫                return {
342927dbe93S猫头猫                    rawLrc,
343927dbe93S猫头猫                    lrc: lrcUrl,
344927dbe93S猫头猫                };
345927dbe93S猫头猫            }
346927dbe93S猫头猫        }
347927dbe93S猫头猫
348927dbe93S猫头猫        return null;
349927dbe93S猫头猫    }
350927dbe93S猫头猫
351927dbe93S猫头猫    /** 获取歌词文本 */
352927dbe93S猫头猫    async getLyricText(
353927dbe93S猫头猫        musicItem: IMusic.IMusicItem,
354927dbe93S猫头猫    ): Promise<string | undefined> {
355927dbe93S猫头猫        return (await this.getLyric(musicItem))?.rawLrc;
356927dbe93S猫头猫    }
357927dbe93S猫头猫
358927dbe93S猫头猫    /** 获取专辑信息 */
359927dbe93S猫头猫    async getAlbumInfo(
360927dbe93S猫头猫        albumItem: IAlbum.IAlbumItemBase,
361927dbe93S猫头猫    ): Promise<IAlbum.IAlbumItem | null> {
362927dbe93S猫头猫        if (!this.plugin.instance.getAlbumInfo) {
363927dbe93S猫头猫            return {...albumItem, musicList: []};
364927dbe93S猫头猫        }
365927dbe93S猫头猫        try {
366927dbe93S猫头猫            const result = await this.plugin.instance.getAlbumInfo(
367927dbe93S猫头猫                resetMediaItem(albumItem, undefined, true),
368927dbe93S猫头猫            );
3695276aef9S猫头猫            if (!result) {
3705276aef9S猫头猫                throw new Error();
3715276aef9S猫头猫            }
372927dbe93S猫头猫            result?.musicList?.forEach(_ => {
373927dbe93S猫头猫                resetMediaItem(_, this.plugin.name);
374927dbe93S猫头猫            });
3755276aef9S猫头猫
3765276aef9S猫头猫            return {...albumItem, ...result};
377927dbe93S猫头猫        } catch {
378927dbe93S猫头猫            return {...albumItem, musicList: []};
379927dbe93S猫头猫        }
380927dbe93S猫头猫    }
381927dbe93S猫头猫
382927dbe93S猫头猫    /** 查询作者信息 */
383927dbe93S猫头猫    async queryArtistWorks<T extends IArtist.ArtistMediaType>(
384927dbe93S猫头猫        artistItem: IArtist.IArtistItem,
385927dbe93S猫头猫        page: number,
386927dbe93S猫头猫        type: T,
387927dbe93S猫头猫    ): Promise<IPlugin.ISearchResult<T>> {
388927dbe93S猫头猫        if (!this.plugin.instance.queryArtistWorks) {
389927dbe93S猫头猫            return {
390927dbe93S猫头猫                isEnd: true,
391927dbe93S猫头猫                data: [],
392927dbe93S猫头猫            };
393927dbe93S猫头猫        }
394927dbe93S猫头猫        try {
395927dbe93S猫头猫            const result = await this.plugin.instance.queryArtistWorks(
396927dbe93S猫头猫                artistItem,
397927dbe93S猫头猫                page,
398927dbe93S猫头猫                type,
399927dbe93S猫头猫            );
400927dbe93S猫头猫            if (!result.data) {
401927dbe93S猫头猫                return {
402927dbe93S猫头猫                    isEnd: true,
403927dbe93S猫头猫                    data: [],
404927dbe93S猫头猫                };
405927dbe93S猫头猫            }
406927dbe93S猫头猫            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
407927dbe93S猫头猫            return {
408927dbe93S猫头猫                isEnd: result.isEnd ?? true,
409927dbe93S猫头猫                data: result.data,
410927dbe93S猫头猫            };
411927dbe93S猫头猫        } catch (e) {
412927dbe93S猫头猫            throw e;
413927dbe93S猫头猫        }
414927dbe93S猫头猫    }
415927dbe93S猫头猫}
4161a5528a0S猫头猫
417927dbe93S猫头猫let plugins: Array<Plugin> = [];
418927dbe93S猫头猫const pluginStateMapper = new StateMapper(() => plugins);
419927dbe93S猫头猫
420927dbe93S猫头猫async function setup() {
421927dbe93S猫头猫    const _plugins: Array<Plugin> = [];
422927dbe93S猫头猫    try {
423927dbe93S猫头猫        // 加载插件
424927dbe93S猫头猫        const pluginsPaths = await readDir(pathConst.pluginPath);
425927dbe93S猫头猫        for (let i = 0; i < pluginsPaths.length; ++i) {
426927dbe93S猫头猫            const _pluginUrl = pluginsPaths[i];
427927dbe93S猫头猫
428927dbe93S猫头猫            if (_pluginUrl.isFile() && _pluginUrl.name.endsWith('.js')) {
429927dbe93S猫头猫                const funcCode = await readFile(_pluginUrl.path, 'utf8');
430927dbe93S猫头猫                const plugin = new Plugin(funcCode, _pluginUrl.path);
4314060c00aS猫头猫                const _pluginIndex = _plugins.findIndex(
4324060c00aS猫头猫                    p => p.hash === plugin.hash,
4334060c00aS猫头猫                );
434927dbe93S猫头猫                if (_pluginIndex !== -1) {
435927dbe93S猫头猫                    // 重复插件,直接忽略
436927dbe93S猫头猫                    return;
437927dbe93S猫头猫                }
438927dbe93S猫头猫                plugin.hash !== '' && _plugins.push(plugin);
439927dbe93S猫头猫            }
440927dbe93S猫头猫        }
441927dbe93S猫头猫
442927dbe93S猫头猫        plugins = _plugins;
443927dbe93S猫头猫        pluginStateMapper.notify();
444927dbe93S猫头猫    } catch (e: any) {
4454060c00aS猫头猫        ToastAndroid.show(
4464060c00aS猫头猫            `插件初始化失败:${e?.message ?? e}`,
4474060c00aS猫头猫            ToastAndroid.LONG,
4484060c00aS猫头猫        );
4491a5528a0S猫头猫        errorLog('插件初始化失败', e?.message);
450927dbe93S猫头猫        throw e;
451927dbe93S猫头猫    }
452927dbe93S猫头猫}
453927dbe93S猫头猫
454927dbe93S猫头猫// 安装插件
455927dbe93S猫头猫async function installPlugin(pluginPath: string) {
456927dbe93S猫头猫    if (pluginPath.endsWith('.js') && (await exists(pluginPath))) {
457927dbe93S猫头猫        const funcCode = await readFile(pluginPath, 'utf8');
458927dbe93S猫头猫        const plugin = new Plugin(funcCode, pluginPath);
459927dbe93S猫头猫        const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
460927dbe93S猫头猫        if (_pluginIndex !== -1) {
461927dbe93S猫头猫            return;
462927dbe93S猫头猫        }
463927dbe93S猫头猫        if (plugin.hash !== '') {
464927dbe93S猫头猫            const fn = nanoid();
465927dbe93S猫头猫            const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
466927dbe93S猫头猫            await copyFile(pluginPath, _pluginPath);
467927dbe93S猫头猫            plugin.path = _pluginPath;
468927dbe93S猫头猫            plugins = plugins.concat(plugin);
469927dbe93S猫头猫            pluginStateMapper.notify();
470927dbe93S猫头猫        }
471927dbe93S猫头猫    }
472927dbe93S猫头猫}
473927dbe93S猫头猫
474927dbe93S猫头猫/** 卸载插件 */
475927dbe93S猫头猫async function uninstallPlugin(hash: string) {
476927dbe93S猫头猫    const targetIndex = plugins.findIndex(_ => _.hash === hash);
477927dbe93S猫头猫    if (targetIndex !== -1) {
478927dbe93S猫头猫        try {
479927dbe93S猫头猫            await unlink(plugins[targetIndex].path);
480927dbe93S猫头猫            plugins = plugins.filter(_ => _.hash !== hash);
481927dbe93S猫头猫            pluginStateMapper.notify();
482927dbe93S猫头猫        } catch {}
483927dbe93S猫头猫    }
484927dbe93S猫头猫}
485927dbe93S猫头猫
486927dbe93S猫头猫function getByMedia(mediaItem: ICommon.IMediaBase) {
487927dbe93S猫头猫    return getByName(mediaItem.platform);
488927dbe93S猫头猫}
489927dbe93S猫头猫
490927dbe93S猫头猫function getByHash(hash: string) {
491927dbe93S猫头猫    return plugins.find(_ => _.hash === hash);
492927dbe93S猫头猫}
493927dbe93S猫头猫
494927dbe93S猫头猫function getByName(name: string) {
495927dbe93S猫头猫    return plugins.find(_ => _.name === name);
496927dbe93S猫头猫}
497927dbe93S猫头猫
498927dbe93S猫头猫function getValidPlugins() {
499927dbe93S猫头猫    return plugins.filter(_ => _.state === 'enabled');
500927dbe93S猫头猫}
501927dbe93S猫头猫
502927dbe93S猫头猫const PluginManager = {
503927dbe93S猫头猫    setup,
504927dbe93S猫头猫    installPlugin,
505927dbe93S猫头猫    uninstallPlugin,
506927dbe93S猫头猫    getByMedia,
507927dbe93S猫头猫    getByHash,
508927dbe93S猫头猫    getByName,
509927dbe93S猫头猫    getValidPlugins,
5105276aef9S猫头猫    usePlugins: pluginStateMapper.useMappedState,
5115276aef9S猫头猫};
512927dbe93S猫头猫
513927dbe93S猫头猫export default PluginManager;
514