xref: /MusicFree/src/core/pluginManager.ts (revision d52aa40ee35db6a95adf7802ea10540bf51594a8)
1import {
2    copyFile,
3    exists,
4    readDir,
5    readFile,
6    unlink,
7    writeFile,
8} from 'react-native-fs';
9import CryptoJs from 'crypto-js';
10import dayjs from 'dayjs';
11import axios from 'axios';
12import bigInt from 'big-integer';
13import qs from 'qs';
14import {InteractionManager, ToastAndroid} from 'react-native';
15import pathConst from '@/constants/pathConst';
16import {compare, satisfies} from 'compare-versions';
17import DeviceInfo from 'react-native-device-info';
18import StateMapper from '@/utils/stateMapper';
19import MediaMeta from './mediaMeta';
20import {nanoid} from 'nanoid';
21import {devLog, errorLog, trace} from '../utils/log';
22import Cache from './cache';
23import {
24    getInternalData,
25    InternalDataType,
26    isSameMediaItem,
27    resetMediaItem,
28} from '@/utils/mediaItem';
29import {
30    CacheControl,
31    emptyFunction,
32    internalSerializeKey,
33    localPluginHash,
34    localPluginPlatform,
35} from '@/constants/commonConst';
36import delay from '@/utils/delay';
37import * as cheerio from 'cheerio';
38import CookieManager from '@react-native-cookies/cookies';
39import he from 'he';
40import Network from './network';
41import LocalMusicSheet from './localMusicSheet';
42import {FileSystem} from 'react-native-file-access';
43import Mp3Util from '@/native/mp3Util';
44import {PluginMeta} from './pluginMeta';
45import {useEffect, useState} from 'react';
46
47axios.defaults.timeout = 1500;
48
49const sha256 = CryptoJs.SHA256;
50
51export enum PluginStateCode {
52    /** 版本不匹配 */
53    VersionNotMatch = 'VERSION NOT MATCH',
54    /** 无法解析 */
55    CannotParse = 'CANNOT PARSE',
56}
57
58//#region 插件类
59export class Plugin {
60    /** 插件名 */
61    public name: string;
62    /** 插件的hash,作为唯一id */
63    public hash: string;
64    /** 插件状态:激活、关闭、错误 */
65    public state: 'enabled' | 'disabled' | 'error';
66    /** 插件支持的搜索类型 */
67    public supportedSearchType?: string;
68    /** 插件状态信息 */
69    public stateCode?: PluginStateCode;
70    /** 插件的实例 */
71    public instance: IPlugin.IPluginInstance;
72    /** 插件路径 */
73    public path: string;
74    /** 插件方法 */
75    public methods: PluginMethods;
76    /** 用户输入 */
77    public userEnv?: Record<string, string>;
78
79    constructor(
80        funcCode: string | (() => IPlugin.IPluginInstance),
81        pluginPath: string,
82    ) {
83        this.state = 'enabled';
84        let _instance: IPlugin.IPluginInstance;
85        try {
86            if (typeof funcCode === 'string') {
87                // eslint-disable-next-line no-new-func
88                _instance = Function(`
89            'use strict';
90            try {
91              return ${funcCode};
92            } catch(e) {
93              return null;
94            }
95          `)()({
96                    CryptoJs,
97                    axios,
98                    dayjs,
99                    cheerio,
100                    bigInt,
101                    qs,
102                    he,
103                    CookieManager: {
104                        flush: CookieManager.flush,
105                        get: CookieManager.get,
106                    },
107                });
108            } else {
109                _instance = funcCode();
110            }
111            this.checkValid(_instance);
112        } catch (e: any) {
113            this.state = 'error';
114            this.stateCode = PluginStateCode.CannotParse;
115            if (e?.stateCode) {
116                this.stateCode = e.stateCode;
117            }
118            errorLog(`${pluginPath}插件无法解析 `, {
119                stateCode: this.stateCode,
120                message: e?.message,
121                stack: e?.stack,
122            });
123            _instance = e?.instance ?? {
124                _path: '',
125                platform: '',
126                appVersion: '',
127                async getMediaSource() {
128                    return null;
129                },
130                async search() {
131                    return {};
132                },
133                async getAlbumInfo() {
134                    return null;
135                },
136            };
137        }
138        this.instance = _instance;
139        this.path = pluginPath;
140        this.name = _instance.platform;
141        if (this.instance.platform === '') {
142            this.hash = '';
143        } else {
144            if (typeof funcCode === 'string') {
145                this.hash = sha256(funcCode).toString();
146            } else {
147                this.hash = sha256(funcCode.toString()).toString();
148            }
149        }
150
151        // 放在最后
152        this.methods = new PluginMethods(this);
153    }
154
155    private checkValid(_instance: IPlugin.IPluginInstance) {
156        /** 版本号校验 */
157        if (
158            _instance.appVersion &&
159            !satisfies(DeviceInfo.getVersion(), _instance.appVersion)
160        ) {
161            throw {
162                instance: _instance,
163                stateCode: PluginStateCode.VersionNotMatch,
164            };
165        }
166        return true;
167    }
168}
169//#endregion
170
171//#region 基于插件类封装的方法,供给APP侧直接调用
172/** 有缓存等信息 */
173class PluginMethods implements IPlugin.IPluginInstanceMethods {
174    private plugin;
175    constructor(plugin: Plugin) {
176        this.plugin = plugin;
177    }
178    /** 搜索 */
179    async search<T extends ICommon.SupportMediaType>(
180        query: string,
181        page: number,
182        type: T,
183    ): Promise<IPlugin.ISearchResult<T>> {
184        if (!this.plugin.instance.search) {
185            return {
186                isEnd: true,
187                data: [],
188            };
189        }
190
191        const result =
192            (await this.plugin.instance.search(query, page, type)) ?? {};
193        if (Array.isArray(result.data)) {
194            result.data.forEach(_ => {
195                resetMediaItem(_, this.plugin.name);
196            });
197            return {
198                isEnd: result.isEnd ?? true,
199                data: result.data,
200            };
201        }
202        return {
203            isEnd: true,
204            data: [],
205        };
206    }
207
208    /** 获取真实源 */
209    async getMediaSource(
210        musicItem: IMusic.IMusicItemBase,
211        quality: IMusic.IQualityKey = 'standard',
212        retryCount = 1,
213        notUpdateCache = false,
214    ): Promise<IPlugin.IMediaSourceResult | null> {
215        // 1. 本地搜索 其实直接读mediameta就好了
216        const localPath =
217            getInternalData<string>(musicItem, InternalDataType.LOCALPATH) ??
218            getInternalData<string>(
219                LocalMusicSheet.isLocalMusic(musicItem),
220                InternalDataType.LOCALPATH,
221            );
222        if (localPath && (await FileSystem.exists(localPath))) {
223            trace('本地播放', localPath);
224            return {
225                url: localPath,
226            };
227        }
228        if (musicItem.platform === localPluginPlatform) {
229            throw new Error('本地音乐不存在');
230        }
231        // 2. 缓存播放
232        const mediaCache = Cache.get(musicItem);
233        const pluginCacheControl =
234            this.plugin.instance.cacheControl ?? 'no-cache';
235        if (
236            mediaCache &&
237            mediaCache?.qualities?.[quality]?.url &&
238            (pluginCacheControl === CacheControl.Cache ||
239                (pluginCacheControl === CacheControl.NoCache &&
240                    Network.isOffline()))
241        ) {
242            trace('播放', '缓存播放');
243            const qualityInfo = mediaCache.qualities[quality];
244            return {
245                url: qualityInfo.url,
246                headers: mediaCache.headers,
247                userAgent:
248                    mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
249            };
250        }
251        // 3. 插件解析
252        if (!this.plugin.instance.getMediaSource) {
253            return {url: musicItem?.qualities?.[quality]?.url ?? musicItem.url};
254        }
255        try {
256            const {url, headers} = (await this.plugin.instance.getMediaSource(
257                musicItem,
258                quality,
259            )) ?? {url: musicItem?.qualities?.[quality]?.url};
260            if (!url) {
261                throw new Error('NOT RETRY');
262            }
263            trace('播放', '插件播放');
264            const result = {
265                url,
266                headers,
267                userAgent: headers?.['user-agent'],
268            } as IPlugin.IMediaSourceResult;
269
270            if (
271                pluginCacheControl !== CacheControl.NoStore &&
272                !notUpdateCache
273            ) {
274                Cache.update(musicItem, [
275                    ['headers', result.headers],
276                    ['userAgent', result.userAgent],
277                    [`qualities.${quality}.url`, url],
278                ]);
279            }
280
281            return result;
282        } catch (e: any) {
283            if (retryCount > 0 && e?.message !== 'NOT RETRY') {
284                await delay(150);
285                return this.getMediaSource(musicItem, quality, --retryCount);
286            }
287            errorLog('获取真实源失败', e?.message);
288            devLog('error', '获取真实源失败', e, e?.message);
289            return null;
290        }
291    }
292
293    /** 获取音乐详情 */
294    async getMusicInfo(
295        musicItem: ICommon.IMediaBase,
296    ): Promise<Partial<IMusic.IMusicItem> | null> {
297        if (!this.plugin.instance.getMusicInfo) {
298            return null;
299        }
300        try {
301            return (
302                this.plugin.instance.getMusicInfo(
303                    resetMediaItem(musicItem, undefined, true),
304                ) ?? null
305            );
306        } catch (e: any) {
307            devLog('error', '获取音乐详情失败', e, e?.message);
308            return null;
309        }
310    }
311
312    /** 获取歌词 */
313    async getLyric(
314        musicItem: IMusic.IMusicItemBase,
315        from?: IMusic.IMusicItemBase,
316    ): Promise<ILyric.ILyricSource | null> {
317        // 1.额外存储的meta信息
318        const meta = MediaMeta.get(musicItem);
319        if (meta && meta.associatedLrc) {
320            // 有关联歌词
321            if (
322                isSameMediaItem(musicItem, from) ||
323                isSameMediaItem(meta.associatedLrc, musicItem)
324            ) {
325                // 形成环路,断开当前的环
326                await MediaMeta.update(musicItem, {
327                    associatedLrc: undefined,
328                });
329                // 无歌词
330                return null;
331            }
332            // 获取关联歌词
333            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
334            const result = await this.getLyric(
335                {...meta.associatedLrc, ...associatedMeta},
336                from ?? musicItem,
337            );
338            if (result) {
339                // 如果有关联歌词,就返回关联歌词,深度优先
340                return result;
341            }
342        }
343        const cache = Cache.get(musicItem);
344        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
345        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
346        // 如果存在文本
347        if (rawLrc) {
348            return {
349                rawLrc,
350                lrc: lrcUrl,
351            };
352        }
353        // 2.本地缓存
354        const localLrc =
355            meta?.[internalSerializeKey]?.local?.localLrc ||
356            cache?.[internalSerializeKey]?.local?.localLrc;
357        if (localLrc && (await exists(localLrc))) {
358            rawLrc = await readFile(localLrc, 'utf8');
359            return {
360                rawLrc,
361                lrc: lrcUrl,
362            };
363        }
364        // 3.优先使用url
365        if (lrcUrl) {
366            try {
367                // 需要超时时间 axios timeout 但是没生效
368                rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
369                return {
370                    rawLrc,
371                    lrc: lrcUrl,
372                };
373            } catch {
374                lrcUrl = undefined;
375            }
376        }
377        // 4. 如果地址失效
378        if (!lrcUrl) {
379            // 插件获得url
380            try {
381                let lrcSource;
382                if (from) {
383                    lrcSource = await PluginManager.getByMedia(
384                        musicItem,
385                    )?.instance?.getLyric?.(
386                        resetMediaItem(musicItem, undefined, true),
387                    );
388                } else {
389                    lrcSource = await this.plugin.instance?.getLyric?.(
390                        resetMediaItem(musicItem, undefined, true),
391                    );
392                }
393
394                rawLrc = lrcSource?.rawLrc;
395                lrcUrl = lrcSource?.lrc;
396            } catch (e: any) {
397                trace('插件获取歌词失败', e?.message, 'error');
398                devLog('error', '插件获取歌词失败', e, e?.message);
399            }
400        }
401        // 5. 最后一次请求
402        if (rawLrc || lrcUrl) {
403            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
404            if (lrcUrl) {
405                try {
406                    rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
407                } catch {}
408            }
409            if (rawLrc) {
410                await writeFile(filename, rawLrc, 'utf8');
411                // 写入缓存
412                Cache.update(musicItem, [
413                    [`${internalSerializeKey}.local.localLrc`, filename],
414                ]);
415                // 如果有meta
416                if (meta) {
417                    MediaMeta.update(musicItem, [
418                        [`${internalSerializeKey}.local.localLrc`, filename],
419                    ]);
420                }
421                return {
422                    rawLrc,
423                    lrc: lrcUrl,
424                };
425            }
426        }
427        // 6. 如果是本地文件
428        const isDownloaded = LocalMusicSheet.isLocalMusic(musicItem);
429        if (musicItem.platform !== localPluginPlatform && isDownloaded) {
430            const res = await localFilePlugin.instance!.getLyric!(isDownloaded);
431            if (res) {
432                return res;
433            }
434        }
435        devLog('warn', '无歌词');
436
437        return null;
438    }
439
440    /** 获取歌词文本 */
441    async getLyricText(
442        musicItem: IMusic.IMusicItem,
443    ): Promise<string | undefined> {
444        return (await this.getLyric(musicItem))?.rawLrc;
445    }
446
447    /** 获取专辑信息 */
448    async getAlbumInfo(
449        albumItem: IAlbum.IAlbumItemBase,
450    ): Promise<IAlbum.IAlbumItem | null> {
451        if (!this.plugin.instance.getAlbumInfo) {
452            return {...albumItem, musicList: []};
453        }
454        try {
455            const result = await this.plugin.instance.getAlbumInfo(
456                resetMediaItem(albumItem, undefined, true),
457            );
458            if (!result) {
459                throw new Error();
460            }
461            result?.musicList?.forEach(_ => {
462                resetMediaItem(_, this.plugin.name);
463            });
464
465            return {...albumItem, ...result};
466        } catch (e: any) {
467            trace('获取专辑信息失败', e?.message);
468            devLog('error', '获取专辑信息失败', e, e?.message);
469
470            return {...albumItem, musicList: []};
471        }
472    }
473
474    /** 查询作者信息 */
475    async getArtistWorks<T extends IArtist.ArtistMediaType>(
476        artistItem: IArtist.IArtistItem,
477        page: number,
478        type: T,
479    ): Promise<IPlugin.ISearchResult<T>> {
480        if (!this.plugin.instance.getArtistWorks) {
481            return {
482                isEnd: true,
483                data: [],
484            };
485        }
486        try {
487            const result = await this.plugin.instance.getArtistWorks(
488                artistItem,
489                page,
490                type,
491            );
492            if (!result.data) {
493                return {
494                    isEnd: true,
495                    data: [],
496                };
497            }
498            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
499            return {
500                isEnd: result.isEnd ?? true,
501                data: result.data,
502            };
503        } catch (e: any) {
504            trace('查询作者信息失败', e?.message);
505            devLog('error', '查询作者信息失败', e, e?.message);
506
507            throw e;
508        }
509    }
510
511    /** 导入歌单 */
512    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
513        try {
514            const result =
515                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
516            result.forEach(_ => resetMediaItem(_, this.plugin.name));
517            return result;
518        } catch (e: any) {
519            console.log(e);
520            devLog('error', '导入歌单失败', e, e?.message);
521
522            return [];
523        }
524    }
525    /** 导入单曲 */
526    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
527        try {
528            const result = await this.plugin.instance?.importMusicItem?.(
529                urlLike,
530            );
531            if (!result) {
532                throw new Error();
533            }
534            resetMediaItem(result, this.plugin.name);
535            return result;
536        } catch (e: any) {
537            devLog('error', '导入单曲失败', e, e?.message);
538
539            return null;
540        }
541    }
542    /** 获取榜单 */
543    async getTopLists(): Promise<IMusic.IMusicTopListGroupItem[]> {
544        try {
545            const result = await this.plugin.instance?.getTopLists?.();
546            if (!result) {
547                throw new Error();
548            }
549            return result;
550        } catch (e: any) {
551            devLog('error', '获取榜单失败', e, e?.message);
552            return [];
553        }
554    }
555    /** 获取榜单详情 */
556    async getTopListDetail(
557        topListItem: IMusic.IMusicTopListItem,
558    ): Promise<ICommon.WithMusicList<IMusic.IMusicTopListItem>> {
559        try {
560            const result = await this.plugin.instance?.getTopListDetail?.(
561                topListItem,
562            );
563            if (!result) {
564                throw new Error();
565            }
566            // resetMediaItem(result, this.plugin.name);
567            return result;
568        } catch (e: any) {
569            devLog('error', '获取榜单详情失败', e, e?.message);
570            return {
571                ...topListItem,
572                musicList: [],
573            };
574        }
575    }
576}
577//#endregion
578
579let plugins: Array<Plugin> = [];
580const pluginStateMapper = new StateMapper(() => plugins);
581
582//#region 本地音乐插件
583/** 本地插件 */
584const localFilePlugin = new Plugin(function () {
585    return {
586        platform: localPluginPlatform,
587        _path: '',
588        async getMusicInfo(musicBase) {
589            const localPath = getInternalData<string>(
590                musicBase,
591                InternalDataType.LOCALPATH,
592            );
593            if (localPath) {
594                const coverImg = await Mp3Util.getMediaCoverImg(localPath);
595                return {
596                    artwork: coverImg,
597                };
598            }
599            return null;
600        },
601        async getLyric(musicBase) {
602            const localPath = getInternalData<string>(
603                musicBase,
604                InternalDataType.LOCALPATH,
605            );
606            let rawLrc: string | null = null;
607            if (localPath) {
608                // 读取内嵌歌词
609                try {
610                    rawLrc = await Mp3Util.getLyric(localPath);
611                } catch (e) {
612                    console.log('e', e);
613                }
614                if (!rawLrc) {
615                    // 读取配置歌词
616                    const lastDot = localPath.lastIndexOf('.');
617                    const lrcPath = localPath.slice(0, lastDot) + '.lrc';
618
619                    try {
620                        if (await exists(lrcPath)) {
621                            rawLrc = await readFile(lrcPath, 'utf8');
622                        }
623                    } catch {}
624                }
625            }
626
627            return rawLrc
628                ? {
629                      rawLrc,
630                  }
631                : null;
632        },
633    };
634}, '');
635localFilePlugin.hash = localPluginHash;
636
637//#endregion
638
639async function setup() {
640    const _plugins: Array<Plugin> = [];
641    try {
642        // 加载插件
643        const pluginsPaths = await readDir(pathConst.pluginPath);
644        for (let i = 0; i < pluginsPaths.length; ++i) {
645            const _pluginUrl = pluginsPaths[i];
646            trace('初始化插件', _pluginUrl);
647            if (
648                _pluginUrl.isFile() &&
649                (_pluginUrl.name?.endsWith?.('.js') ||
650                    _pluginUrl.path?.endsWith?.('.js'))
651            ) {
652                const funcCode = await readFile(_pluginUrl.path, 'utf8');
653                const plugin = new Plugin(funcCode, _pluginUrl.path);
654                const _pluginIndex = _plugins.findIndex(
655                    p => p.hash === plugin.hash,
656                );
657                if (_pluginIndex !== -1) {
658                    // 重复插件,直接忽略
659                    return;
660                }
661                plugin.hash !== '' && _plugins.push(plugin);
662            }
663        }
664
665        plugins = _plugins;
666        pluginStateMapper.notify();
667        /** 初始化meta信息 */
668        PluginMeta.setupMeta(plugins.map(_ => _.name));
669    } catch (e: any) {
670        ToastAndroid.show(
671            `插件初始化失败:${e?.message ?? e}`,
672            ToastAndroid.LONG,
673        );
674        errorLog('插件初始化失败', e?.message);
675        throw e;
676    }
677}
678
679// 安装插件
680async function installPlugin(pluginPath: string) {
681    // if (pluginPath.endsWith('.js')) {
682    const funcCode = await readFile(pluginPath, 'utf8');
683    const plugin = new Plugin(funcCode, pluginPath);
684    const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
685    if (_pluginIndex !== -1) {
686        throw new Error('插件已安装');
687    }
688    if (plugin.hash !== '') {
689        const fn = nanoid();
690        const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
691        await copyFile(pluginPath, _pluginPath);
692        plugin.path = _pluginPath;
693        plugins = plugins.concat(plugin);
694        pluginStateMapper.notify();
695        return;
696    }
697    throw new Error('插件无法解析');
698    // }
699    // throw new Error('插件不存在');
700}
701
702async function installPluginFromUrl(url: string) {
703    try {
704        const funcCode = (await axios.get(url)).data;
705        if (funcCode) {
706            const plugin = new Plugin(funcCode, '');
707            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
708            if (_pluginIndex !== -1) {
709                // 静默忽略
710                return;
711            }
712            const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
713            if (oldVersionPlugin) {
714                if (
715                    compare(
716                        oldVersionPlugin.instance.version ?? '',
717                        plugin.instance.version ?? '',
718                        '>',
719                    )
720                ) {
721                    throw new Error('已安装更新版本的插件');
722                }
723            }
724
725            if (plugin.hash !== '') {
726                const fn = nanoid();
727                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
728                await writeFile(_pluginPath, funcCode, 'utf8');
729                plugin.path = _pluginPath;
730                plugins = plugins.concat(plugin);
731                if (oldVersionPlugin) {
732                    plugins = plugins.filter(
733                        _ => _.hash !== oldVersionPlugin.hash,
734                    );
735                    try {
736                        await unlink(oldVersionPlugin.path);
737                    } catch {}
738                }
739                pluginStateMapper.notify();
740                return;
741            }
742            throw new Error('插件无法解析!');
743        }
744    } catch (e: any) {
745        devLog('error', 'URL安装插件失败', e, e?.message);
746        errorLog('URL安装插件失败', e);
747        throw new Error(e?.message ?? '');
748    }
749}
750
751/** 卸载插件 */
752async function uninstallPlugin(hash: string) {
753    const targetIndex = plugins.findIndex(_ => _.hash === hash);
754    if (targetIndex !== -1) {
755        try {
756            const pluginName = plugins[targetIndex].name;
757            await unlink(plugins[targetIndex].path);
758            plugins = plugins.filter(_ => _.hash !== hash);
759            pluginStateMapper.notify();
760            if (plugins.every(_ => _.name !== pluginName)) {
761                await MediaMeta.removePlugin(pluginName);
762            }
763        } catch {}
764    }
765}
766
767async function uninstallAllPlugins() {
768    await Promise.all(
769        plugins.map(async plugin => {
770            try {
771                const pluginName = plugin.name;
772                await unlink(plugin.path);
773                await MediaMeta.removePlugin(pluginName);
774            } catch (e) {}
775        }),
776    );
777    plugins = [];
778    pluginStateMapper.notify();
779
780    /** 清除空余文件,异步做就可以了 */
781    readDir(pathConst.pluginPath)
782        .then(fns => {
783            fns.forEach(fn => {
784                unlink(fn.path).catch(emptyFunction);
785            });
786        })
787        .catch(emptyFunction);
788}
789
790async function updatePlugin(plugin: Plugin) {
791    const updateUrl = plugin.instance.srcUrl;
792    if (!updateUrl) {
793        throw new Error('没有更新源');
794    }
795    try {
796        await installPluginFromUrl(updateUrl);
797    } catch (e: any) {
798        if (e.message === '插件已安装') {
799            throw new Error('当前已是最新版本');
800        } else {
801            throw e;
802        }
803    }
804}
805
806function getByMedia(mediaItem: ICommon.IMediaBase) {
807    return getByName(mediaItem?.platform);
808}
809
810function getByHash(hash: string) {
811    return hash === localPluginHash
812        ? localFilePlugin
813        : plugins.find(_ => _.hash === hash);
814}
815
816function getByName(name: string) {
817    return name === localPluginPlatform
818        ? localFilePlugin
819        : plugins.find(_ => _.name === name);
820}
821
822function getValidPlugins() {
823    return plugins.filter(_ => _.state === 'enabled');
824}
825
826function getSearchablePlugins() {
827    return plugins.filter(_ => _.state === 'enabled' && _.instance.search);
828}
829
830function getSortedSearchablePlugins() {
831    return getSearchablePlugins().sort((a, b) =>
832        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
833            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
834        0
835            ? -1
836            : 1,
837    );
838}
839
840function useSortedPlugins() {
841    const _plugins = pluginStateMapper.useMappedState();
842    const _pluginMetaAll = PluginMeta.usePluginMetaAll();
843
844    const [sortedPlugins, setSortedPlugins] = useState(
845        [..._plugins].sort((a, b) =>
846            (_pluginMetaAll[a.name]?.order ?? Infinity) -
847                (_pluginMetaAll[b.name]?.order ?? Infinity) <
848            0
849                ? -1
850                : 1,
851        ),
852    );
853
854    useEffect(() => {
855        InteractionManager.runAfterInteractions(() => {
856            setSortedPlugins(
857                [..._plugins].sort((a, b) =>
858                    (_pluginMetaAll[a.name]?.order ?? Infinity) -
859                        (_pluginMetaAll[b.name]?.order ?? Infinity) <
860                    0
861                        ? -1
862                        : 1,
863                ),
864            );
865        });
866    }, [_plugins, _pluginMetaAll]);
867
868    return sortedPlugins;
869}
870
871const PluginManager = {
872    setup,
873    installPlugin,
874    installPluginFromUrl,
875    updatePlugin,
876    uninstallPlugin,
877    getByMedia,
878    getByHash,
879    getByName,
880    getValidPlugins,
881    getSearchablePlugins,
882    getSortedSearchablePlugins,
883    usePlugins: pluginStateMapper.useMappedState,
884    useSortedPlugins,
885    uninstallAllPlugins,
886};
887
888export default PluginManager;
889