xref: /MusicFree/src/core/pluginManager.ts (revision dc160d50ea0be479d97e47b24a71edee79ca9c1d)
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 {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            return null;
289        }
290    }
291
292    /** 获取音乐详情 */
293    async getMusicInfo(
294        musicItem: ICommon.IMediaBase,
295    ): Promise<Partial<IMusic.IMusicItem> | null> {
296        if (!this.plugin.instance.getMusicInfo) {
297            return null;
298        }
299        try {
300            return (
301                this.plugin.instance.getMusicInfo(
302                    resetMediaItem(musicItem, undefined, true),
303                ) ?? null
304            );
305        } catch (e) {
306            return null;
307        }
308    }
309
310    /** 获取歌词 */
311    async getLyric(
312        musicItem: IMusic.IMusicItemBase,
313        from?: IMusic.IMusicItemBase,
314    ): Promise<ILyric.ILyricSource | null> {
315        // 1.额外存储的meta信息
316        const meta = MediaMeta.get(musicItem);
317        if (meta && meta.associatedLrc) {
318            // 有关联歌词
319            if (
320                isSameMediaItem(musicItem, from) ||
321                isSameMediaItem(meta.associatedLrc, musicItem)
322            ) {
323                // 形成环路,断开当前的环
324                await MediaMeta.update(musicItem, {
325                    associatedLrc: undefined,
326                });
327                // 无歌词
328                return null;
329            }
330            // 获取关联歌词
331            const associatedMeta = MediaMeta.get(meta.associatedLrc) ?? {};
332            const result = await this.getLyric(
333                {...meta.associatedLrc, ...associatedMeta},
334                from ?? musicItem,
335            );
336            if (result) {
337                // 如果有关联歌词,就返回关联歌词,深度优先
338                return result;
339            }
340        }
341        const cache = Cache.get(musicItem);
342        let rawLrc = meta?.rawLrc || musicItem.rawLrc || cache?.rawLrc;
343        let lrcUrl = meta?.lrc || musicItem.lrc || cache?.lrc;
344        // 如果存在文本
345        if (rawLrc) {
346            return {
347                rawLrc,
348                lrc: lrcUrl,
349            };
350        }
351        // 2.本地缓存
352        const localLrc =
353            meta?.[internalSerializeKey]?.local?.localLrc ||
354            cache?.[internalSerializeKey]?.local?.localLrc;
355        if (localLrc && (await exists(localLrc))) {
356            rawLrc = await readFile(localLrc, 'utf8');
357            return {
358                rawLrc,
359                lrc: lrcUrl,
360            };
361        }
362        // 3.优先使用url
363        if (lrcUrl) {
364            try {
365                // 需要超时时间 axios timeout 但是没生效
366                rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
367                return {
368                    rawLrc,
369                    lrc: lrcUrl,
370                };
371            } catch {
372                lrcUrl = undefined;
373            }
374        }
375        // 4. 如果地址失效
376        if (!lrcUrl) {
377            // 插件获得url
378            try {
379                let lrcSource;
380                if (from) {
381                    lrcSource = await PluginManager.getByMedia(
382                        musicItem,
383                    )?.instance?.getLyric?.(
384                        resetMediaItem(musicItem, undefined, true),
385                    );
386                } else {
387                    lrcSource = await this.plugin.instance?.getLyric?.(
388                        resetMediaItem(musicItem, undefined, true),
389                    );
390                }
391
392                rawLrc = lrcSource?.rawLrc;
393                lrcUrl = lrcSource?.lrc;
394            } catch (e: any) {
395                trace('插件获取歌词失败', e?.message, 'error');
396            }
397        }
398        // 5. 最后一次请求
399        if (rawLrc || lrcUrl) {
400            const filename = `${pathConst.lrcCachePath}${nanoid()}.lrc`;
401            if (lrcUrl) {
402                try {
403                    rawLrc = (await axios.get(lrcUrl, {timeout: 1500})).data;
404                } catch {}
405            }
406            if (rawLrc) {
407                await writeFile(filename, rawLrc, 'utf8');
408                // 写入缓存
409                Cache.update(musicItem, [
410                    [`${internalSerializeKey}.local.localLrc`, filename],
411                ]);
412                // 如果有meta
413                if (meta) {
414                    MediaMeta.update(musicItem, [
415                        [`${internalSerializeKey}.local.localLrc`, filename],
416                    ]);
417                }
418                return {
419                    rawLrc,
420                    lrc: lrcUrl,
421                };
422            }
423        }
424
425        return null;
426    }
427
428    /** 获取歌词文本 */
429    async getLyricText(
430        musicItem: IMusic.IMusicItem,
431    ): Promise<string | undefined> {
432        return (await this.getLyric(musicItem))?.rawLrc;
433    }
434
435    /** 获取专辑信息 */
436    async getAlbumInfo(
437        albumItem: IAlbum.IAlbumItemBase,
438    ): Promise<IAlbum.IAlbumItem | null> {
439        if (!this.plugin.instance.getAlbumInfo) {
440            return {...albumItem, musicList: []};
441        }
442        try {
443            const result = await this.plugin.instance.getAlbumInfo(
444                resetMediaItem(albumItem, undefined, true),
445            );
446            if (!result) {
447                throw new Error();
448            }
449            result?.musicList?.forEach(_ => {
450                resetMediaItem(_, this.plugin.name);
451            });
452
453            return {...albumItem, ...result};
454        } catch (e: any) {
455            trace('获取专辑信息失败', e?.message);
456            return {...albumItem, musicList: []};
457        }
458    }
459
460    /** 查询作者信息 */
461    async getArtistWorks<T extends IArtist.ArtistMediaType>(
462        artistItem: IArtist.IArtistItem,
463        page: number,
464        type: T,
465    ): Promise<IPlugin.ISearchResult<T>> {
466        if (!this.plugin.instance.getArtistWorks) {
467            return {
468                isEnd: true,
469                data: [],
470            };
471        }
472        try {
473            const result = await this.plugin.instance.getArtistWorks(
474                artistItem,
475                page,
476                type,
477            );
478            if (!result.data) {
479                return {
480                    isEnd: true,
481                    data: [],
482                };
483            }
484            result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
485            return {
486                isEnd: result.isEnd ?? true,
487                data: result.data,
488            };
489        } catch (e: any) {
490            trace('查询作者信息失败', e?.message);
491            throw e;
492        }
493    }
494
495    /** 导入歌单 */
496    async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
497        try {
498            const result =
499                (await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
500            result.forEach(_ => resetMediaItem(_, this.plugin.name));
501            return result;
502        } catch (e) {
503            console.log(e);
504            return [];
505        }
506    }
507    /** 导入单曲 */
508    async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
509        try {
510            const result = await this.plugin.instance?.importMusicItem?.(
511                urlLike,
512            );
513            if (!result) {
514                throw new Error();
515            }
516            resetMediaItem(result, this.plugin.name);
517            return result;
518        } catch {
519            return null;
520        }
521    }
522}
523//#endregion
524
525let plugins: Array<Plugin> = [];
526const pluginStateMapper = new StateMapper(() => plugins);
527
528//#region 本地音乐插件
529/** 本地插件 */
530const localFilePlugin = new Plugin(function () {
531    return {
532        platform: localPluginPlatform,
533        _path: '',
534        async getMusicInfo(musicBase) {
535            const localPath = getInternalData<string>(
536                musicBase,
537                InternalDataType.LOCALPATH,
538            );
539            if (localPath) {
540                const coverImg = await Mp3Util.getMediaCoverImg(localPath);
541                return {
542                    artwork: coverImg,
543                };
544            }
545            return null;
546        },
547        async getLyric(musicBase) {
548            const localPath = getInternalData<string>(
549                musicBase,
550                InternalDataType.LOCALPATH,
551            );
552            if (localPath) {
553                const rawLrc = await Mp3Util.getLyric(localPath);
554                return {
555                    rawLrc,
556                };
557            }
558            return null;
559        },
560    };
561}, '');
562localFilePlugin.hash = localPluginHash;
563
564//#endregion
565
566async function setup() {
567    const _plugins: Array<Plugin> = [];
568    try {
569        // 加载插件
570        const pluginsPaths = await readDir(pathConst.pluginPath);
571        for (let i = 0; i < pluginsPaths.length; ++i) {
572            const _pluginUrl = pluginsPaths[i];
573            trace('初始化插件', _pluginUrl);
574            if (
575                _pluginUrl.isFile() &&
576                (_pluginUrl.name?.endsWith?.('.js') ||
577                    _pluginUrl.path?.endsWith?.('.js'))
578            ) {
579                const funcCode = await readFile(_pluginUrl.path, 'utf8');
580                const plugin = new Plugin(funcCode, _pluginUrl.path);
581                const _pluginIndex = _plugins.findIndex(
582                    p => p.hash === plugin.hash,
583                );
584                if (_pluginIndex !== -1) {
585                    // 重复插件,直接忽略
586                    return;
587                }
588                plugin.hash !== '' && _plugins.push(plugin);
589            }
590        }
591
592        plugins = _plugins;
593        pluginStateMapper.notify();
594        /** 初始化meta信息 */
595        PluginMeta.setupMeta(plugins.map(_ => _.name));
596    } catch (e: any) {
597        ToastAndroid.show(
598            `插件初始化失败:${e?.message ?? e}`,
599            ToastAndroid.LONG,
600        );
601        errorLog('插件初始化失败', e?.message);
602        throw e;
603    }
604}
605
606// 安装插件
607async function installPlugin(pluginPath: string) {
608    // if (pluginPath.endsWith('.js')) {
609    const funcCode = await readFile(pluginPath, 'utf8');
610    const plugin = new Plugin(funcCode, pluginPath);
611    const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
612    if (_pluginIndex !== -1) {
613        throw new Error('插件已安装');
614    }
615    if (plugin.hash !== '') {
616        const fn = nanoid();
617        const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
618        await copyFile(pluginPath, _pluginPath);
619        plugin.path = _pluginPath;
620        plugins = plugins.concat(plugin);
621        pluginStateMapper.notify();
622        return;
623    }
624    throw new Error('插件无法解析');
625    // }
626    // throw new Error('插件不存在');
627}
628
629async function installPluginFromUrl(url: string) {
630    try {
631        const funcCode = (await axios.get(url)).data;
632        if (funcCode) {
633            const plugin = new Plugin(funcCode, '');
634            const _pluginIndex = plugins.findIndex(p => p.hash === plugin.hash);
635            if (_pluginIndex !== -1) {
636                // 静默忽略
637                return;
638            }
639            const oldVersionPlugin = plugins.find(p => p.name === plugin.name);
640            if (oldVersionPlugin) {
641                if (
642                    compare(
643                        oldVersionPlugin.instance.version ?? '',
644                        plugin.instance.version ?? '',
645                        '>',
646                    )
647                ) {
648                    throw new Error('已安装更新版本的插件');
649                }
650            }
651
652            if (plugin.hash !== '') {
653                const fn = nanoid();
654                const _pluginPath = `${pathConst.pluginPath}${fn}.js`;
655                await writeFile(_pluginPath, funcCode, 'utf8');
656                plugin.path = _pluginPath;
657                plugins = plugins.concat(plugin);
658                if (oldVersionPlugin) {
659                    plugins = plugins.filter(
660                        _ => _.hash !== oldVersionPlugin.hash,
661                    );
662                    try {
663                        await unlink(oldVersionPlugin.path);
664                    } catch {}
665                }
666                pluginStateMapper.notify();
667                return;
668            }
669            throw new Error('插件无法解析!');
670        }
671    } catch (e: any) {
672        errorLog('URL安装插件失败', e);
673        throw new Error(e?.message ?? '');
674    }
675}
676
677/** 卸载插件 */
678async function uninstallPlugin(hash: string) {
679    const targetIndex = plugins.findIndex(_ => _.hash === hash);
680    if (targetIndex !== -1) {
681        try {
682            const pluginName = plugins[targetIndex].name;
683            await unlink(plugins[targetIndex].path);
684            plugins = plugins.filter(_ => _.hash !== hash);
685            pluginStateMapper.notify();
686            if (plugins.every(_ => _.name !== pluginName)) {
687                await MediaMeta.removePlugin(pluginName);
688            }
689        } catch {}
690    }
691}
692
693async function uninstallAllPlugins() {
694    await Promise.all(
695        plugins.map(async plugin => {
696            try {
697                const pluginName = plugin.name;
698                await unlink(plugin.path);
699                await MediaMeta.removePlugin(pluginName);
700            } catch (e) {}
701        }),
702    );
703    plugins = [];
704    pluginStateMapper.notify();
705
706    /** 清除空余文件,异步做就可以了 */
707    readDir(pathConst.pluginPath)
708        .then(fns => {
709            fns.forEach(fn => {
710                unlink(fn.path).catch(emptyFunction);
711            });
712        })
713        .catch(emptyFunction);
714}
715
716async function updatePlugin(plugin: Plugin) {
717    const updateUrl = plugin.instance.srcUrl;
718    if (!updateUrl) {
719        throw new Error('没有更新源');
720    }
721    try {
722        await installPluginFromUrl(updateUrl);
723    } catch (e: any) {
724        if (e.message === '插件已安装') {
725            throw new Error('当前已是最新版本');
726        } else {
727            throw e;
728        }
729    }
730}
731
732function getByMedia(mediaItem: ICommon.IMediaBase) {
733    return getByName(mediaItem?.platform);
734}
735
736function getByHash(hash: string) {
737    return hash === localPluginHash
738        ? localFilePlugin
739        : plugins.find(_ => _.hash === hash);
740}
741
742function getByName(name: string) {
743    return name === localPluginPlatform
744        ? localFilePlugin
745        : plugins.find(_ => _.name === name);
746}
747
748function getValidPlugins() {
749    return plugins.filter(_ => _.state === 'enabled');
750}
751
752function getSearchablePlugins() {
753    return plugins.filter(_ => _.state === 'enabled' && _.instance.search);
754}
755
756function getSortedSearchablePlugins() {
757    return getSearchablePlugins().sort((a, b) =>
758        (PluginMeta.getPluginMeta(a).order ?? Infinity) -
759            (PluginMeta.getPluginMeta(b).order ?? Infinity) <
760        0
761            ? -1
762            : 1,
763    );
764}
765
766function useSortedPlugins() {
767    const _plugins = pluginStateMapper.useMappedState();
768    const _pluginMetaAll = PluginMeta.usePluginMetaAll();
769
770    const [sortedPlugins, setSortedPlugins] = useState(
771        [..._plugins].sort((a, b) =>
772            (_pluginMetaAll[a.name]?.order ?? Infinity) -
773                (_pluginMetaAll[b.name]?.order ?? Infinity) <
774            0
775                ? -1
776                : 1,
777        ),
778    );
779
780    useEffect(() => {
781        InteractionManager.runAfterInteractions(() => {
782            setSortedPlugins(
783                [..._plugins].sort((a, b) =>
784                    (_pluginMetaAll[a.name]?.order ?? Infinity) -
785                        (_pluginMetaAll[b.name]?.order ?? Infinity) <
786                    0
787                        ? -1
788                        : 1,
789                ),
790            );
791        });
792    }, [_plugins, _pluginMetaAll]);
793
794    return sortedPlugins;
795}
796
797const PluginManager = {
798    setup,
799    installPlugin,
800    installPluginFromUrl,
801    updatePlugin,
802    uninstallPlugin,
803    getByMedia,
804    getByHash,
805    getByName,
806    getValidPlugins,
807    getSearchablePlugins,
808    getSortedSearchablePlugins,
809    usePlugins: pluginStateMapper.useMappedState,
810    useSortedPlugins,
811    uninstallAllPlugins,
812};
813
814export default PluginManager;
815