/
pluginManager.ts
1319 lines (1230 loc) · 40.2 KB
/
pluginManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
copyFile,
exists,
readDir,
readFile,
unlink,
writeFile,
} from 'react-native-fs';
import CryptoJs from 'crypto-js';
import dayjs from 'dayjs';
import axios from 'axios';
import bigInt from 'big-integer';
import qs from 'qs';
import * as webdav from 'webdav';
import {InteractionManager, ToastAndroid} from 'react-native';
import pathConst from '@/constants/pathConst';
import {compare, satisfies} from 'compare-versions';
import DeviceInfo from 'react-native-device-info';
import StateMapper from '@/utils/stateMapper';
import MediaMeta from './mediaExtra';
import {nanoid} from 'nanoid';
import {devLog, errorLog, trace} from '../utils/log';
import {
getInternalData,
InternalDataType,
isSameMediaItem,
resetMediaItem,
} from '@/utils/mediaItem';
import {
CacheControl,
emptyFunction,
internalSerializeKey,
localPluginHash,
localPluginPlatform,
} from '@/constants/commonConst';
import delay from '@/utils/delay';
import * as cheerio from 'cheerio';
import CookieManager from '@react-native-cookies/cookies';
import he from 'he';
import Network from './network';
import LocalMusicSheet from './localMusicSheet';
import {FileSystem} from 'react-native-file-access';
import Mp3Util from '@/native/mp3Util';
import {PluginMeta} from './pluginMeta';
import {useEffect, useState} from 'react';
import {addFileScheme, getFileName} from '@/utils/fileUtils';
import {URL} from 'react-native-url-polyfill';
import Base64 from '@/utils/base64';
import MediaCache from './mediaCache';
import produce from 'immer';
import MediaExtra from './mediaExtra';
import objectPath from 'object-path';
axios.defaults.timeout = 2000;
const sha256 = CryptoJs.SHA256;
export enum PluginStateCode {
/** 版本不匹配 */
VersionNotMatch = 'VERSION NOT MATCH',
/** 无法解析 */
CannotParse = 'CANNOT PARSE',
}
const packages: Record<string, any> = {
cheerio,
'crypto-js': CryptoJs,
axios,
dayjs,
'big-integer': bigInt,
qs,
he,
'@react-native-cookies/cookies': CookieManager,
webdav,
};
const _require = (packageName: string) => {
let pkg = packages[packageName];
pkg.default = pkg;
return pkg;
};
const _consoleBind = function (
method: 'log' | 'error' | 'info' | 'warn',
...args: any
) {
const fn = console[method];
if (fn) {
fn(...args);
devLog(method, ...args);
}
};
const _console = {
log: _consoleBind.bind(null, 'log'),
warn: _consoleBind.bind(null, 'warn'),
info: _consoleBind.bind(null, 'info'),
error: _consoleBind.bind(null, 'error'),
};
function formatAuthUrl(url: string) {
const urlObj = new URL(url);
try {
if (urlObj.username && urlObj.password) {
const auth = `Basic ${Base64.btoa(
`${decodeURIComponent(urlObj.username)}:${decodeURIComponent(
urlObj.password,
)}`,
)}`;
urlObj.username = '';
urlObj.password = '';
return {
url: urlObj.toString(),
auth,
};
}
} catch (e) {
return {
url,
};
}
return {
url,
};
}
//#region 插件类
export class Plugin {
/** 插件名 */
public name: string;
/** 插件的hash,作为唯一id */
public hash: string;
/** 插件状态:激活、关闭、错误 */
public state: 'enabled' | 'disabled' | 'error';
/** 插件状态信息 */
public stateCode?: PluginStateCode;
/** 插件的实例 */
public instance: IPlugin.IPluginInstance;
/** 插件路径 */
public path: string;
/** 插件方法 */
public methods: PluginMethods;
constructor(
funcCode: string | (() => IPlugin.IPluginInstance),
pluginPath: string,
) {
this.state = 'enabled';
let _instance: IPlugin.IPluginInstance;
const _module: any = {exports: {}};
try {
if (typeof funcCode === 'string') {
// 插件的环境变量
const env = {
getUserVariables: () => {
return (
PluginMeta.getPluginMeta(this)?.userVariables ?? {}
);
},
os: 'android',
};
// eslint-disable-next-line no-new-func
_instance = Function(`
'use strict';
return function(require, __musicfree_require, module, exports, console, env, URL) {
${funcCode}
}
`)()(
_require,
_require,
_module,
_module.exports,
_console,
env,
URL,
);
if (_module.exports.default) {
_instance = _module.exports
.default as IPlugin.IPluginInstance;
} else {
_instance = _module.exports as IPlugin.IPluginInstance;
}
} else {
_instance = funcCode();
}
// 插件初始化后的一些操作
if (Array.isArray(_instance.userVariables)) {
_instance.userVariables = _instance.userVariables.filter(
it => it?.key,
);
}
this.checkValid(_instance);
} catch (e: any) {
console.log(e);
this.state = 'error';
this.stateCode = PluginStateCode.CannotParse;
if (e?.stateCode) {
this.stateCode = e.stateCode;
}
errorLog(`${pluginPath}插件无法解析 `, {
stateCode: this.stateCode,
message: e?.message,
stack: e?.stack,
});
_instance = e?.instance ?? {
_path: '',
platform: '',
appVersion: '',
async getMediaSource() {
return null;
},
async search() {
return {};
},
async getAlbumInfo() {
return null;
},
};
}
this.instance = _instance;
this.path = pluginPath;
this.name = _instance.platform;
if (
this.instance.platform === '' ||
this.instance.platform === undefined
) {
this.hash = '';
} else {
if (typeof funcCode === 'string') {
this.hash = sha256(funcCode).toString();
} else {
this.hash = sha256(funcCode.toString()).toString();
}
}
// 放在最后
this.methods = new PluginMethods(this);
}
private checkValid(_instance: IPlugin.IPluginInstance) {
/** 版本号校验 */
if (
_instance.appVersion &&
!satisfies(DeviceInfo.getVersion(), _instance.appVersion)
) {
throw {
instance: _instance,
stateCode: PluginStateCode.VersionNotMatch,
};
}
return true;
}
}
//#endregion
//#region 基于插件类封装的方法,供给APP侧直接调用
/** 有缓存等信息 */
class PluginMethods implements IPlugin.IPluginInstanceMethods {
private plugin;
constructor(plugin: Plugin) {
this.plugin = plugin;
}
/** 搜索 */
async search<T extends ICommon.SupportMediaType>(
query: string,
page: number,
type: T,
): Promise<IPlugin.ISearchResult<T>> {
if (!this.plugin.instance.search) {
return {
isEnd: true,
data: [],
};
}
const result =
(await this.plugin.instance.search(query, page, type)) ?? {};
if (Array.isArray(result.data)) {
result.data.forEach(_ => {
resetMediaItem(_, this.plugin.name);
});
return {
isEnd: result.isEnd ?? true,
data: result.data,
};
}
return {
isEnd: true,
data: [],
};
}
/** 获取真实源 */
async getMediaSource(
musicItem: IMusic.IMusicItemBase,
quality: IMusic.IQualityKey = 'standard',
retryCount = 1,
notUpdateCache = false,
): Promise<IPlugin.IMediaSourceResult | null> {
// 1. 本地搜索 其实直接读mediameta就好了
const mediaExtra = MediaExtra.get(musicItem);
const localPath =
mediaExtra?.localPath ||
getInternalData<string>(musicItem, InternalDataType.LOCALPATH) ||
getInternalData<string>(
LocalMusicSheet.isLocalMusic(musicItem),
InternalDataType.LOCALPATH,
);
if (
localPath &&
(localPath.startsWith('content://') ||
(await FileSystem.exists(localPath)))
) {
trace('本地播放', localPath);
if (mediaExtra && mediaExtra.localPath !== localPath) {
// 修正一下本地数据
MediaExtra.update(musicItem, {
localPath,
});
}
return {
url: addFileScheme(localPath),
};
} else if (mediaExtra?.localPath) {
MediaExtra.update(musicItem, {
localPath: undefined,
});
}
if (musicItem.platform === localPluginPlatform) {
throw new Error('本地音乐不存在');
}
// 2. 缓存播放
const mediaCache = MediaCache.getMediaCache(
musicItem,
) as IMusic.IMusicItem | null;
const pluginCacheControl =
this.plugin.instance.cacheControl ?? 'no-cache';
if (
mediaCache &&
mediaCache?.source?.[quality]?.url &&
(pluginCacheControl === CacheControl.Cache ||
(pluginCacheControl === CacheControl.NoCache &&
Network.isOffline()))
) {
trace('播放', '缓存播放');
const qualityInfo = mediaCache.source[quality];
return {
url: qualityInfo!.url,
headers: mediaCache.headers,
userAgent:
mediaCache.userAgent ?? mediaCache.headers?.['user-agent'],
};
}
// 3. 插件解析
if (!this.plugin.instance.getMediaSource) {
const {url, auth} = formatAuthUrl(
musicItem?.qualities?.[quality]?.url ?? musicItem.url,
);
return {
url: url,
headers: auth
? {
Authorization: auth,
}
: undefined,
};
}
try {
const {url, headers} = (await this.plugin.instance.getMediaSource(
musicItem,
quality,
)) ?? {url: musicItem?.qualities?.[quality]?.url};
if (!url) {
throw new Error('NOT RETRY');
}
trace('播放', '插件播放');
const result = {
url,
headers,
userAgent: headers?.['user-agent'],
} as IPlugin.IMediaSourceResult;
const authFormattedResult = formatAuthUrl(result.url!);
if (authFormattedResult.auth) {
result.url = authFormattedResult.url;
result.headers = {
...(result.headers ?? {}),
Authorization: authFormattedResult.auth,
};
}
if (
pluginCacheControl !== CacheControl.NoStore &&
!notUpdateCache
) {
// 更新缓存
const cacheSource = {
headers: result.headers,
userAgent: result.userAgent,
url,
};
let realMusicItem = {
...musicItem,
...(mediaCache || {}),
};
realMusicItem.source = {
...(realMusicItem.source || {}),
[quality]: cacheSource,
};
MediaCache.setMediaCache(realMusicItem);
}
return result;
} catch (e: any) {
if (retryCount > 0 && e?.message !== 'NOT RETRY') {
await delay(150);
return this.getMediaSource(musicItem, quality, --retryCount);
}
errorLog('获取真实源失败', e?.message);
devLog('error', '获取真实源失败', e, e?.message);
return null;
}
}
/** 获取音乐详情 */
async getMusicInfo(
musicItem: ICommon.IMediaBase,
): Promise<Partial<IMusic.IMusicItem> | null> {
if (!this.plugin.instance.getMusicInfo) {
return null;
}
try {
return (
this.plugin.instance.getMusicInfo(
resetMediaItem(musicItem, undefined, true),
) ?? null
);
} catch (e: any) {
devLog('error', '获取音乐详情失败', e, e?.message);
return null;
}
}
/**
*
* getLyric(musicItem) => {
* lyric: string;
* trans: string;
* }
*
*/
/** 获取歌词 */
async getLyric(
originalMusicItem: IMusic.IMusicItemBase,
): Promise<ILyric.ILyricSource | null> {
// 1.额外存储的meta信息(关联歌词)
const meta = MediaMeta.get(originalMusicItem);
let musicItem: IMusic.IMusicItem;
if (meta && meta.associatedLrc) {
musicItem = meta.associatedLrc as IMusic.IMusicItem;
} else {
musicItem = originalMusicItem as IMusic.IMusicItem;
}
const musicItemCache = MediaCache.getMediaCache(
musicItem,
) as IMusic.IMusicItemCache | null;
/** 原始歌词文本 */
let rawLrc: string | null = musicItem.rawLrc || null;
let translation: string | null = null;
// 2. 缓存歌词 / 对象上本身的歌词
if (musicItemCache?.lyric) {
// 缓存的远程结果
let cacheLyric: ILyric.ILyricSource | null =
musicItemCache.lyric || null;
// 缓存的本地结果
let localLyric: ILyric.ILyricSource | null =
musicItemCache.$localLyric || null;
// 优先用缓存的结果
if (cacheLyric.rawLrc || cacheLyric.translation) {
return {
rawLrc: cacheLyric.rawLrc,
translation: cacheLyric.translation,
};
}
// 本地其实是缓存的路径
if (localLyric) {
let needRefetch = false;
if (localLyric.rawLrc && (await exists(localLyric.rawLrc))) {
rawLrc = await readFile(localLyric.rawLrc, 'utf8');
} else if (localLyric.rawLrc) {
needRefetch = true;
}
if (
localLyric.translation &&
(await exists(localLyric.translation))
) {
translation = await readFile(
localLyric.translation,
'utf8',
);
} else if (localLyric.translation) {
needRefetch = true;
}
if (!needRefetch && (rawLrc || translation)) {
return {
rawLrc: rawLrc || undefined,
translation: translation || undefined,
};
}
}
}
// 3. 无缓存歌词/无自带歌词/无本地歌词
let lrcSource: ILyric.ILyricSource | null;
if (isSameMediaItem(originalMusicItem, musicItem)) {
lrcSource =
(await this.plugin.instance
?.getLyric?.(resetMediaItem(musicItem, undefined, true))
?.catch(() => null)) || null;
} else {
lrcSource =
(await PluginManager.getByMedia(musicItem)
?.instance?.getLyric?.(
resetMediaItem(musicItem, undefined, true),
)
?.catch(() => null)) || null;
}
if (lrcSource) {
rawLrc = lrcSource?.rawLrc || rawLrc;
translation = lrcSource?.translation || null;
const deprecatedLrcUrl = lrcSource?.lrc || musicItem.lrc;
// 本地的文件名
let filename: string | undefined = `${
pathConst.lrcCachePath
}${nanoid()}.lrc`;
let filenameTrans: string | undefined = `${
pathConst.lrcCachePath
}${nanoid()}.lrc`;
// 旧版本兼容
if (!(rawLrc || translation)) {
if (deprecatedLrcUrl) {
rawLrc = (
await axios
.get(deprecatedLrcUrl, {timeout: 3000})
.catch(() => null)
)?.data;
} else if (musicItem.rawLrc) {
rawLrc = musicItem.rawLrc;
}
}
if (rawLrc) {
await writeFile(filename, rawLrc, 'utf8');
} else {
filename = undefined;
}
if (translation) {
await writeFile(filenameTrans, translation, 'utf8');
} else {
filenameTrans = undefined;
}
if (rawLrc || translation) {
MediaCache.setMediaCache(
produce(musicItemCache || musicItem, draft => {
musicItemCache?.$localLyric?.rawLrc;
objectPath.set(draft, '$localLyric.rawLrc', filename);
objectPath.set(
draft,
'$localLyric.translation',
filenameTrans,
);
return draft;
}),
);
return {
rawLrc: rawLrc || undefined,
translation: translation || undefined,
};
}
}
// 6. 如果是本地文件
const isDownloaded = LocalMusicSheet.isLocalMusic(originalMusicItem);
if (
originalMusicItem.platform !== localPluginPlatform &&
isDownloaded
) {
const res = await localFilePlugin.instance!.getLyric!(isDownloaded);
console.log('本地文件歌词');
if (res) {
return res;
}
}
devLog('warn', '无歌词');
return null;
}
/** 获取歌词文本 */
async getLyricText(
musicItem: IMusic.IMusicItem,
): Promise<string | undefined> {
return (await this.getLyric(musicItem))?.rawLrc;
}
/** 获取专辑信息 */
async getAlbumInfo(
albumItem: IAlbum.IAlbumItemBase,
page: number = 1,
): Promise<IPlugin.IAlbumInfoResult | null> {
if (!this.plugin.instance.getAlbumInfo) {
return {
albumItem,
musicList: (albumItem?.musicList ?? []).map(
resetMediaItem,
this.plugin.name,
true,
),
isEnd: true,
};
}
try {
const result = await this.plugin.instance.getAlbumInfo(
resetMediaItem(albumItem, undefined, true),
page,
);
if (!result) {
throw new Error();
}
result?.musicList?.forEach(_ => {
resetMediaItem(_, this.plugin.name);
_.album = albumItem.title;
});
if (page <= 1) {
// 合并信息
return {
albumItem: {...albumItem, ...(result?.albumItem ?? {})},
isEnd: result.isEnd === false ? false : true,
musicList: result.musicList,
};
} else {
return {
isEnd: result.isEnd === false ? false : true,
musicList: result.musicList,
};
}
} catch (e: any) {
trace('获取专辑信息失败', e?.message);
devLog('error', '获取专辑信息失败', e, e?.message);
return null;
}
}
/** 获取歌单信息 */
async getMusicSheetInfo(
sheetItem: IMusic.IMusicSheetItem,
page: number = 1,
): Promise<IPlugin.ISheetInfoResult | null> {
if (!this.plugin.instance.getMusicSheetInfo) {
return {
sheetItem,
musicList: sheetItem?.musicList ?? [],
isEnd: true,
};
}
try {
const result = await this.plugin.instance?.getMusicSheetInfo?.(
resetMediaItem(sheetItem, undefined, true),
page,
);
if (!result) {
throw new Error();
}
result?.musicList?.forEach(_ => {
resetMediaItem(_, this.plugin.name);
});
if (page <= 1) {
// 合并信息
return {
sheetItem: {...sheetItem, ...(result?.sheetItem ?? {})},
isEnd: result.isEnd === false ? false : true,
musicList: result.musicList,
};
} else {
return {
isEnd: result.isEnd === false ? false : true,
musicList: result.musicList,
};
}
} catch (e: any) {
trace('获取歌单信息失败', e, e?.message);
devLog('error', '获取歌单信息失败', e, e?.message);
return null;
}
}
/** 查询作者信息 */
async getArtistWorks<T extends IArtist.ArtistMediaType>(
artistItem: IArtist.IArtistItem,
page: number,
type: T,
): Promise<IPlugin.ISearchResult<T>> {
if (!this.plugin.instance.getArtistWorks) {
return {
isEnd: true,
data: [],
};
}
try {
const result = await this.plugin.instance.getArtistWorks(
artistItem,
page,
type,
);
if (!result.data) {
return {
isEnd: true,
data: [],
};
}
result.data?.forEach(_ => resetMediaItem(_, this.plugin.name));
return {
isEnd: result.isEnd ?? true,
data: result.data,
};
} catch (e: any) {
trace('查询作者信息失败', e?.message);
devLog('error', '查询作者信息失败', e, e?.message);
throw e;
}
}
/** 导入歌单 */
async importMusicSheet(urlLike: string): Promise<IMusic.IMusicItem[]> {
try {
const result =
(await this.plugin.instance?.importMusicSheet?.(urlLike)) ?? [];
result.forEach(_ => resetMediaItem(_, this.plugin.name));
return result;
} catch (e: any) {
console.log(e);
devLog('error', '导入歌单失败', e, e?.message);
return [];
}
}
/** 导入单曲 */
async importMusicItem(urlLike: string): Promise<IMusic.IMusicItem | null> {
try {
const result = await this.plugin.instance?.importMusicItem?.(
urlLike,
);
if (!result) {
throw new Error();
}
resetMediaItem(result, this.plugin.name);
return result;
} catch (e: any) {
devLog('error', '导入单曲失败', e, e?.message);
return null;
}
}
/** 获取榜单 */
async getTopLists(): Promise<IMusic.IMusicSheetGroupItem[]> {
try {
const result = await this.plugin.instance?.getTopLists?.();
if (!result) {
throw new Error();
}
return result;
} catch (e: any) {
devLog('error', '获取榜单失败', e, e?.message);
return [];
}
}
/** 获取榜单详情 */
async getTopListDetail(
topListItem: IMusic.IMusicSheetItemBase,
page: number,
): Promise<IPlugin.ITopListInfoResult> {
try {
const result = await this.plugin.instance?.getTopListDetail?.(
topListItem,
page,
);
if (!result) {
throw new Error();
}
if (result.musicList) {
result.musicList.forEach(_ =>
resetMediaItem(_, this.plugin.name),
);
}
if (result.isEnd !== false) {
result.isEnd = true;
}
return result;
} catch (e: any) {
devLog('error', '获取榜单详情失败', e, e?.message);
return {
isEnd: true,
topListItem: topListItem as IMusic.IMusicSheetItem,
musicList: [],
};
}
}
/** 获取推荐歌单的tag */
async getRecommendSheetTags(): Promise<IPlugin.IGetRecommendSheetTagsResult> {
try {
const result =
await this.plugin.instance?.getRecommendSheetTags?.();
if (!result) {
throw new Error();
}
return result;
} catch (e: any) {
devLog('error', '获取推荐歌单失败', e, e?.message);
return {
data: [],
};
}
}
/** 获取某个tag的推荐歌单 */
async getRecommendSheetsByTag(
tagItem: ICommon.IUnique,
page?: number,
): Promise<ICommon.PaginationResponse<IMusic.IMusicSheetItemBase>> {
try {
const result =
await this.plugin.instance?.getRecommendSheetsByTag?.(
tagItem,
page ?? 1,
);
if (!result) {
throw new Error();
}
if (result.isEnd !== false) {
result.isEnd = true;
}
if (!result.data) {
result.data = [];
}
result.data.forEach(item => resetMediaItem(item, this.plugin.name));
return result;
} catch (e: any) {
devLog('error', '获取推荐歌单详情失败', e, e?.message);
return {
isEnd: true,
data: [],
};
}
}
}
//#endregion
let plugins: Array<Plugin> = [];
const pluginStateMapper = new StateMapper(() => plugins);
//#region 本地音乐插件
/** 本地插件 */
const localFilePlugin = new Plugin(function () {
return {
platform: localPluginPlatform,
_path: '',
async getMusicInfo(musicBase) {
const localPath = getInternalData<string>(
musicBase,
InternalDataType.LOCALPATH,
);
if (localPath) {
const coverImg = await Mp3Util.getMediaCoverImg(localPath);
return {
artwork: coverImg,
};
}
return null;
},
async getLyric(musicBase) {
const localPath = getInternalData<string>(
musicBase,
InternalDataType.LOCALPATH,
);
let rawLrc: string | null = null;
if (localPath) {
// 读取内嵌歌词
try {
rawLrc = await Mp3Util.getLyric(localPath);
} catch (e) {
console.log('读取内嵌歌词失败', e);
}
if (!rawLrc) {
// 读取配置歌词
const lastDot = localPath.lastIndexOf('.');
const lrcPath = localPath.slice(0, lastDot) + '.lrc';
try {
if (await exists(lrcPath)) {
rawLrc = await readFile(lrcPath, 'utf8');
}
} catch {}
}
}
return rawLrc
? {
rawLrc,
}
: null;
},
async importMusicItem(urlLike) {
let meta: any = {};
try {
meta = await Mp3Util.getBasicMeta(urlLike);
} catch {}
const id = await FileSystem.hash(urlLike, 'MD5');
return {
id: id,
platform: '本地',
title: meta?.title ?? getFileName(urlLike),
artist: meta?.artist ?? '未知歌手',
duration: parseInt(meta?.duration ?? '0') / 1000,
album: meta?.album ?? '未知专辑',
artwork: '',
[internalSerializeKey]: {
localPath: urlLike,
},
};
},
async getMediaSource(musicItem, quality) {
if (quality === 'standard') {
return {
url: addFileScheme(musicItem.$?.localPath || musicItem.url),
};
}
return null;
},
};
}, '');
localFilePlugin.hash = localPluginHash;
//#endregion
async function setup() {
const _plugins: Array<Plugin> = [];
try {
// 加载插件
const pluginsPaths = await readDir(pathConst.pluginPath);
for (let i = 0; i < pluginsPaths.length; ++i) {
const _pluginUrl = pluginsPaths[i];
trace('初始化插件', _pluginUrl);
if (
_pluginUrl.isFile() &&
(_pluginUrl.name?.endsWith?.('.js') ||
_pluginUrl.path?.endsWith?.('.js'))
) {
const funcCode = await readFile(_pluginUrl.path, 'utf8');
const plugin = new Plugin(funcCode, _pluginUrl.path);
const _pluginIndex = _plugins.findIndex(
p => p.hash === plugin.hash,
);
if (_pluginIndex !== -1) {
// 重复插件,直接忽略
continue;
}
plugin.hash !== '' && _plugins.push(plugin);
}
}
plugins = _plugins;
/** 初始化meta信息 */
await PluginMeta.setupMeta(plugins.map(_ => _.name));
/** 查看一下是否有禁用的标记 */
const allMeta = PluginMeta.getPluginMetaAll() ?? {};
for (let plugin of plugins) {
if (allMeta[plugin.name]?.enabled === false) {
plugin.state = 'disabled';