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