-
Notifications
You must be signed in to change notification settings - Fork 1
/
popupLyricsPlus.js
1840 lines (1661 loc) · 62.6 KB
/
popupLyricsPlus.js
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
// NAME: Popup Lyrics
// AUTHOR: khanhas
// Netease API parser and UI from https://github.com/mantou132/Spotify-Lyrics
// DESCRIPTION: Pop lyrics up
// MODDER: patrick-orz
/// <reference path="../globals.d.ts" />
if (!navigator.serviceWorker) {
// Worker code
// When Spotify client is minimised, requestAnimationFrame does not call our tick function
// setTimeout and setInterval are also throttled at 1 second.
// Offload setInterval to a Worker to consistently call tick function.
let num = null;
onmessage = (event) => {
if (event.data === "popup-lyric-request-update") {
console.warn("popup-lyric-request-update");
num = setInterval(() => postMessage("popup-lyric-update-ui"), 16.66);
} else if (event.data === "popup-lyric-stop-update") {
clearInterval(num);
num = null;
}
};
} else {
PopupLyrics();
}
function PopupLyrics() {
const { Player, CosmosAsync, LocalStorage, ContextMenu } = Spicetify;
if (!CosmosAsync || !LocalStorage || !ContextMenu) {
setTimeout(PopupLyrics, 500);
return;
}
const worker = new Worker("./extensions/popupLyrics.js");
worker.onmessage = (event) => {
if (event.data === "popup-lyric-update-ui") {
tick(userConfigs);
}
};
/* TRANSLATOR */
const kuroshiroPath =
"https://cdn.jsdelivr.net/npm/[email protected]/dist/kuroshiro.min.js";
const kuromojiPath =
"https://cdn.jsdelivr.net/npm/[email protected]/dist/kuroshiro-analyzer-kuromoji.min.js";
const aromanize =
"https://cdn.jsdelivr.net/npm/[email protected]/aromanize.min.js";
const openCCPath =
"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/full.min.js";
// const TinyPinyinPath = "https://creeperyang.github.io/pinyin/browser.js";
const pinyinProPath = "https://unpkg.com/[email protected]/dist/index.js";
const dictPath = "https:/cdn.jsdelivr.net/npm/[email protected]/dict";
class overallTranslator {
constructor(lang) {
this.finished = {
ja: false,
ko: false,
zh: false,
en: false,
py: false,
};
this.applyKuromojiFix();
this.injectExternals(lang);
this.createTranslator(lang);
}
includeExternal(url) {
if (!document.querySelector(`script[src="${url}"]`)) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", url);
document.head.appendChild(script);
}
}
injectExternals(lang) {
switch (lang?.slice(0, 2)) {
case "ja":
this.includeExternal(kuromojiPath);
this.includeExternal(kuroshiroPath);
break;
case "ko":
this.includeExternal(aromanize);
break;
case "zh":
this.includeExternal(openCCPath);
break;
case "py":
// this.includeExternal(TinyPinyinPath);
this.includeExternal(pinyinProPath);
break;
}
}
/**
* Fix an issue with kuromoji when loading dict from external urls
* Adapted from: https://github.com/mobilusoss/textlint-browser-runner/pull/7
*/
applyKuromojiFix() {
if (typeof XMLHttpRequest.prototype.realOpen !== "undefined") return;
XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, bool) {
if (url.indexOf(dictPath.replace("https://", "https:/")) === 0) {
this.realOpen(method, url.replace("https:/", "https://"), bool);
} else {
this.realOpen(method, url, bool);
}
};
}
async createTranslator(lang) {
switch (lang.slice(0, 2)) {
case "ja":
if (this.kuroshiro) return;
if (
typeof Kuroshiro === "undefined" ||
typeof KuromojiAnalyzer === "undefined"
) {
await overallTranslator.#sleep(50);
return this.createTranslator(lang);
}
this.kuroshiro = new Kuroshiro.default();
this.kuroshiro.init(new KuromojiAnalyzer({ dictPath })).then(
function () {
this.finished.ja = true;
}.bind(this)
);
break;
case "ko":
if (this.Aromanize) return;
if (typeof Aromanize === "undefined") {
await overallTranslator.#sleep(50);
return this.createTranslator(lang);
}
this.Aromanize = Aromanize;
this.finished.ko = true;
break;
case "zh":
if (this.OpenCC) return;
if (typeof OpenCC === "undefined") {
await overallTranslator.#sleep(50);
return this.createTranslator(lang);
}
this.OpenCC = OpenCC;
this.finished.zh = true;
break;
case "py":
// if (this.Pinyin) return;
// if (typeof Pinyin === "undefined") {
// await overallTranslator.#sleep(50);
// return this.createTranslator(lang);
// }
// this.Pinyin = Pinyin;
// this.finished.py = true;
// break;
if (this.pinyinPro) return;
if (typeof pinyinPro === "undefined") {
await overallTranslator.#sleep(50);
return this.createTranslator(lang);
}
this.pinyinPro = pinyinPro;
this.finished.py = true;
break;
}
}
async romajifyText(text, target = "romaji", mode = "spaced") {
if (!this.finished.ja) {
await overallTranslator.#sleep(100);
return this.romajifyText(text, target, mode);
}
return this.kuroshiro.convert(text, {
to: target,
mode: mode,
});
}
async convertToRomaja(text) {
if (!this.finished.ko) {
await overallTranslator.#sleep(100);
return this.convertToRomaja(text);
}
return this.Aromanize.hangulToLatin(text, "rr-translit");
}
async convertChinese(text, from, target) {
if (!this.finished.zh) {
await overallTranslator.#sleep(100);
return this.convertChinese(text, from, target);
}
const converter = this.OpenCC.Converter({
from: from,
to: target,
});
return converter(text);
}
async convertPinyin(text, seperator = " ") {
if (!this.finished.py) {
await overallTranslator.#sleep(100);
return this.convertPinyin(text, seperator);
}
var value = text;
// var pinyin = "";
// if (value) {
// var tokens = this.Pinyin.parse(text);
// var lastToken;
// tokens.forEach(function (v, i) {
// if (v.type === 2) {
// pinyin +=
// pinyin && !/\n|\s/.test(lastToken.target)
// ? " " + v.target.toLowerCase()
// : v.target.toLowerCase();
// } else {
// pinyin += (lastToken && lastToken.type === 2 ? " " : "") + v.target;
// }
// lastToken = v;
// });
// }
var pinyinText = "";
if (value) {
var { pinyin } = this.pinyinPro;
// var tokens = this.Pinyin.parse(text);
pinyinText = pinyin(value);
// var lastToken;
// tokens.forEach(function (v, i) {
// if (v.type === 2) {
// pinyin +=
// pinyin && !/\n|\s/.test(lastToken.target)
// ? " " + v.target.toLowerCase()
// : v.target.toLowerCase();
// } else {
// pinyin += (lastToken && lastToken.type === 2 ? " " : "") + v.target;
// }
// lastToken = v;
// });
}
// return pinyin;
return pinyinText;
}
/**
* Async wrapper of `setTimeout`.
*
* @param {number} ms
* @returns {Promise<void>}
*/
static async #sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
// Taken from Lyrics+
const LyricUtils = {
normalize(s, emptySymbol = true) {
const result = s
.replace(/(/g, "(")
.replace(/)/g, ")")
.replace(/【/g, "[")
.replace(/】/g, "]")
.replace(/。/g, ". ")
.replace(/;/g, "; ")
.replace(/:/g, ": ")
.replace(/?/g, "? ")
.replace(/!/g, "! ")
.replace(/、|,/g, ", ")
.replace(/‘|’|′|'/g, "'")
.replace(/“|”/g, '"')
.replace(/〜/g, "~")
.replace(/·|・/g, "•");
if (emptySymbol) {
result.replace(/-/g, " ").replace(/\//g, " ");
}
return result.replace(/\s+/g, " ").trim();
},
removeExtraInfo(s) {
return (
s
.replace(/-\s+(feat|with|prod).*/i, "")
.replace(/(\(|\[)(feat|with|prod)\.?\s+.*(\)|\])$/i, "")
.replace(/\s-\s.*/, "")
.trim() || s
);
},
capitalize(s) {
return s.replace(/^(\w)/, ($1) => $1.toUpperCase());
},
};
const LyricProviders = {
async fetchSpotify(info) {
const baseURL = "https://spclient.wg.spotify.com/color-lyrics/v2/track/";
const id = info.uri.split(":")[2];
const body = await CosmosAsync.get(
`${baseURL + id}?format=json&vocalRemoval=false&market=from_token`
);
const lyricsData = body.lyrics;
if (!lyricsData || lyricsData.syncType !== "LINE_SYNCED") {
return { error: "No lyrics" };
}
const lines = lyricsData.lines;
const lyrics = lines.map((a) => ({
startTime: a.startTimeMs / 1000,
text: a.words,
}));
return { lyrics };
},
async fetchMusixmatch(info) {
const baseURL =
"https://apic-desktop.musixmatch.com/ws/1.1/macro.subtitles.get?format=json&namespace=lyrics_synched&subtitle_format=mxm&app_id=web-desktop-app-v1.0&";
const durr = info.duration / 1000;
const params = {
q_album: info.album,
q_artist: info.artist,
q_artists: info.artist,
q_track: info.title,
track_spotify_id: info.uri,
q_duration: durr,
f_subtitle_length: Math.floor(durr),
usertoken: userConfigs.services.musixmatch.token,
};
const finalURL =
baseURL +
Object.keys(params)
.map((key) => `${key}=${encodeURIComponent(params[key])}`)
.join("&");
try {
let body = await CosmosAsync.get(finalURL, null, {
authority: "apic-desktop.musixmatch.com",
cookie: "x-mxm-token-guid=",
});
body = body.message.body.macro_calls;
if (body["matcher.track.get"].message.header.status_code !== 200) {
const head = body["matcher.track.get"].message.header;
return {
error: `Requested error: ${head.status_code}: ${head.hint} - ${head.mode}`,
};
}
const meta = body["matcher.track.get"].message.body;
const hasSynced = meta.track.has_subtitles;
const isRestricted =
body["track.lyrics.get"].message.header.status_code === 200 &&
body["track.lyrics.get"].message.body.lyrics.restricted;
const isInstrumental = meta.track.instrumental;
if (isRestricted)
return {
error: "Unfortunately we're not authorized to show these lyrics.",
};
if (isInstrumental) return { error: "Instrumental" };
if (hasSynced) {
const subtitle =
body["track.subtitles.get"].message.body.subtitle_list[0].subtitle;
const lyrics = JSON.parse(subtitle.subtitle_body).map((line) => ({
text: line.text || "♪",
startTime: line.time.total,
}));
return { lyrics };
}
return { error: "No lyrics" };
} catch (err) {
return { error: err.message };
}
},
async fetchNetease(info) {
const searchURL =
"https://music.xianqiao.wang/neteaseapiv2/search?limit=10&type=1&keywords=";
const lyricURL = "https://music.xianqiao.wang/neteaseapiv2/lyric?id=";
const requestHeader = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0",
};
const cleanTitle = LyricUtils.removeExtraInfo(
LyricUtils.normalize(info.title)
);
const finalURL =
searchURL + encodeURIComponent(`${cleanTitle} ${info.artist}`);
const searchResults = await CosmosAsync.get(
finalURL,
null,
requestHeader
);
const items = searchResults.result.songs;
if (!items || !items.length) {
return { error: "Cannot find track" };
}
const album = LyricUtils.capitalize(info.album);
const itemId = items.findIndex(
(val) =>
LyricUtils.capitalize(val.album.name) === album ||
Math.abs(info.duration - val.duration) < 1000
);
if (itemId === -1) return { error: "Cannot find track" };
const meta = await CosmosAsync.get(
lyricURL + items[itemId].id,
null,
requestHeader
);
let lyricStr = meta.lrc;
if (!lyricStr || !lyricStr.lyric) {
return { error: "No lyrics" };
}
lyricStr = lyricStr.lyric;
const otherInfoKeys = [
"\\s?作?\\s*词|\\s?作?\\s*曲|\\s?编\\s*曲?|\\s?监\\s*制?",
".*编写|.*和音|.*和声|.*合声|.*提琴|.*录|.*工程|.*工作室|.*设计|.*剪辑|.*制作|.*发行|.*出品|.*后期|.*混音|.*缩混",
"原唱|翻唱|题字|文案|海报|古筝|二胡|钢琴|吉他|贝斯|笛子|鼓|弦乐",
"lrc|publish|vocal|guitar|program|produce|write|mix",
];
const otherInfoRegexp = new RegExp(
`^(${otherInfoKeys.join("|")}).*(:|:)`,
"i"
);
const lines = lyricStr.split(/\r?\n/).map((line) => line.trim());
let noLyrics = false;
const lyrics = lines
.flatMap((line) => {
// ["[ar:Beyond]"]
// ["[03:10]"]
// ["[03:10]", "永远高唱我歌"]
// ["永远高唱我歌"]
// ["[03:10]", "[03:10]", "永远高唱我歌"]
const matchResult = line.match(/(\[.*?\])|([^\[\]]+)/g) || [line];
if (!matchResult.length || matchResult.length === 1) {
return;
}
const textIndex = matchResult.findIndex(
(slice) => !slice.endsWith("]")
);
let text = "";
if (textIndex > -1) {
text = matchResult.splice(textIndex, 1)[0];
text = LyricUtils.capitalize(LyricUtils.normalize(text, false));
}
if (text === "纯音乐, 请欣赏") noLyrics = true;
return matchResult.map((slice) => {
const result = {};
const matchResult = slice.match(/[^\[\]]+/g);
const [key, value] = matchResult[0].split(":") || [];
const [min, sec] = [
Number.parseFloat(key),
Number.parseFloat(value),
];
if (
!Number.isNaN(min) &&
!Number.isNaN(sec) &&
!otherInfoRegexp.test(text)
) {
result.startTime = min * 60 + sec;
result.text = text || "♪";
return result;
}
return;
});
})
.sort((a, b) => {
if (a.startTime === null) {
return 0;
}
if (b.startTime === null) {
return 1;
}
return a.startTime - b.startTime;
})
.filter(Boolean);
if (noLyrics) {
return { error: "No lyrics" };
}
if (!lyrics.length) {
return { error: "No synced lyrics" };
}
return { lyrics };
},
// Fetch from NeteaseMusicAPI and store chinese lyrics
async fetchNeteaseCN(info) {
// URL of deployed Netease API, used for fetching
const searchURL =
"https://netease-cloud-music-api-patrick-orz.vercel.app/cloudsearch?type=1&keywords=";
const lyricURL =
"https://netease-cloud-music-api-patrick-orz.vercel.app/lyric?id=";
const requestHeader = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0",
};
const cleanTitle = LyricUtils.removeExtraInfo(
LyricUtils.normalize(info.title)
);
const finalURL =
searchURL + encodeURIComponent(`${cleanTitle} ${info.artist}`);
const searchResults = await CosmosAsync.get(
finalURL,
null,
requestHeader
);
const items = searchResults.result.songs;
if (!items || !items.length) {
return { error: "Cannot find track" };
}
const album = LyricUtils.capitalize(info.album);
const itemId = items.findIndex(
(val) =>
LyricUtils.capitalize(val.name) === album ||
Math.abs(info.duration - val.dt) < 1000
);
if (itemId === -1) return { error: "Cannot find track" };
const meta = await CosmosAsync.get(
lyricURL + items[itemId].id,
null,
requestHeader
);
// Store netease lyrics
let ogLyricStr = meta.lrc; // Untranslated lyrics
let tLyricStr = meta.tlyric; // Translated lyrics
if (!ogLyricStr || !ogLyricStr.lyric) {
return { error: "No lyrics" };
}
ogLyricStr = ogLyricStr.lyric;
tLyricStr = tLyricStr.lyric;
let lines;
const otherInfoKeys = [
"\\s?作?\\s*词|\\s?作?\\s*曲|\\s?编\\s*曲?|\\s?监\\s*制?",
".*编写|.*和音|.*和声|.*合声|.*提琴|.*录|.*工程|.*工作室|.*设计|.*剪辑|.*制作|.*发行|.*出品|.*后期|.*混音|.*缩混",
"原唱|翻唱|题字|文案|海报|古筝|二胡|钢琴|吉他|贝斯|笛子|鼓|弦乐",
"lrc|publish|vocal|guitar|program|produce|write|mix",
];
const otherInfoRegexp = new RegExp(
`^(${otherInfoKeys.join("|")}).*(:|:)`,
"i"
);
// Parse OG
lines = ogLyricStr.split(/\r?\n/).map((line) => line.trim());
let noOgLyrics = false;
const ogLyrics = lines
.flatMap((line) => {
// ["[ar:Beyond]"]
// ["[03:10]"]
// ["[03:10]", "永远高唱我歌"]
// ["永远高唱我歌"]
// ["[03:10]", "[03:10]", "永远高唱我歌"]
const matchResult = line.match(/(\[.*?\])|([^\[\]]+)/g) || [line];
if (!matchResult.length || matchResult.length === 1) {
return;
}
const textIndex = matchResult.findIndex(
(slice) => !slice.endsWith("]")
);
let text = "";
if (textIndex > -1) {
text = matchResult.splice(textIndex, 1)[0];
text = LyricUtils.capitalize(LyricUtils.normalize(text, false));
}
if (text === "纯音乐, 请欣赏") noOgLyrics = true;
return matchResult.map((slice) => {
const result = {};
const matchResult = slice.match(/[^\[\]]+/g);
const [key, value] = matchResult[0].split(":") || [];
const [min, sec] = [parseFloat(key), parseFloat(value)];
if (
!Number.isNaN(min) &&
!Number.isNaN(sec) &&
!otherInfoRegexp.test(text)
) {
result.startTime = min * 60 + sec;
result.text = text || "♪";
return result;
}
return;
});
})
.sort((a, b) => {
if (a.startTime === null) {
return 0;
}
if (b.startTime === null) {
return 1;
}
return a.startTime - b.startTime;
})
.filter(Boolean);
console.log(ogLyrics);
// Parse Translated
lines = tLyricStr.split(/\r?\n/).map((line) => line.trim());
let noTLyrics = false;
const tLyrics = lines
.flatMap((line) => {
const matchResult = line.match(/(\[.*?\])|([^\[\]]+)/g) || [line];
if (!matchResult.length || matchResult.length === 1) {
return;
}
const textIndex = matchResult.findIndex(
(slice) => !slice.endsWith("]")
);
let text = "";
if (textIndex > -1) {
text = matchResult.splice(textIndex, 1)[0];
text = LyricUtils.capitalize(LyricUtils.normalize(text, false));
}
if (text === "纯音乐, 请欣赏") noTLyrics = true;
return matchResult.map((slice) => {
const result = {};
const matchResult = slice.match(/[^\[\]]+/g);
const [key, value] = matchResult[0].split(":") || [];
const [min, sec] = [parseFloat(key), parseFloat(value)];
if (
!Number.isNaN(min) &&
!Number.isNaN(sec) &&
!otherInfoRegexp.test(text)
) {
result.startTime = min * 60 + sec;
result.text = text || "♪";
return result;
}
return;
});
})
.sort((a, b) => {
if (a.startTime === null) {
return 0;
}
if (b.startTime === null) {
return 1;
}
return a.startTime - b.startTime;
})
.filter(Boolean);
// Check & Output
if (noOgLyrics) {
return { error: "No lyrics" };
}
if (!ogLyrics.length) {
return { error: "No synced lyrics" };
}
let lyrics;
if (userConfigs.translation2rd == 2)
lyrics = noTLyrics || !tLyrics.length ? ogLyrics : tLyrics;
else lyrics = ogLyrics;
return { lyrics };
},
async fetchLrclib(info) {
const baseURL = "https://lrclib.net/api/get";
const durr = info.duration / 1000;
const params = {
track_name: info.title,
artist_name: info.artist,
album_name: info.album,
duration: durr,
};
const finalURL = `${baseURL}?${Object.keys(params)
.map((key) => `${key}=${encodeURIComponent(params[key])}`)
.join("&")}`;
const body = await fetch(finalURL, {
headers: {
"x-user-agent": `spicetify v${Spicetify.Config.version} (https://github.com/spicetify/cli)`,
},
});
if (body.status !== 200) {
return { error: "No lyrics" };
}
const meta = await body.json();
if (meta?.instrumental) {
return { error: "Instrumental" };
}
if (!meta?.syncedLyrics) {
return { error: "No lyrics" };
}
// Preprocess lyrics by removing [tags] and empty lines
const lines = meta?.syncedLyrics
.replaceAll(/\[[a-zA-Z]+:.+\]/g, "")
.trim()
.split("\n");
const syncedTimestamp = /\[([0-9:.]+)\]/;
const isSynced = lines[0].match(syncedTimestamp);
const lyrics = lines.map((line) => {
const time = line.match(syncedTimestamp)?.[1];
const lyricContent = line.replace(syncedTimestamp, "").trim();
const lyric = lyricContent.replaceAll(/\<([0-9:.]+)\>/g, "").trim();
const [min, sec] = time.replace(/\[\]\<\>/, "").split(":");
if (line.trim() !== "" && isSynced && time) {
return { text: lyric || "♪", startTime: Number(min) * 60 + Number(sec) };
}
return;
});
return { lyrics };
},
};
const userConfigs = {
smooth: boolLocalStorage("popup-lyrics:smooth"),
centerAlign: boolLocalStorage("popup-lyrics:center-align"),
showCover: boolLocalStorage("popup-lyrics:show-cover"),
translation2rd: Number(LocalStorage.get("popup-lyrics:translation-2rd")),
fontSize: Number(LocalStorage.get("popup-lyrics:font-size")),
blurSize: Number(LocalStorage.get("popup-lyrics:blur-size")),
fontFamily:
LocalStorage.get("popup-lyrics:font-family") || "spotify-circular",
ratio: LocalStorage.get("popup-lyrics:ratio") || "11",
delay: Number(LocalStorage.get("popup-lyrics:delay")),
services: {
neteaseCN: {
on: boolLocalStorage("popup-lyrics:services:netease:on"),
call: LyricProviders.fetchNeteaseCN,
desc: "NeteaseAPI OG & Chinese lyrics fetch through self-deployed API",
},
netease: {
on: boolLocalStorage("popup-lyrics:services:netease:on"),
call: LyricProviders.fetchNetease,
desc: "Crowdsourced lyrics provider ran by Chinese developers and users.",
},
musixmatch: {
on: boolLocalStorage("popup-lyrics:services:musixmatch:on"),
call: LyricProviders.fetchMusixmatch,
desc: `Fully compatible with Spotify. Requires a token that can be retrieved from the official Musixmatch app. Follow instructions on <a href="https://spicetify.app/docs/faq#sometimes-popup-lyrics-andor-lyrics-plus-seem-to-not-work">Spicetify Docs</a>.`,
token:
LocalStorage.get("popup-lyrics:services:musixmatch:token") ||
"2005218b74f939209bda92cb633c7380612e14cb7fe92dcd6a780f",
},
spotify: {
on: boolLocalStorage("popup-lyrics:services:spotify:on"),
call: LyricProviders.fetchSpotify,
desc: "Lyrics sourced from official Spotify API."
},
lrclib: {
on: boolLocalStorage("popup-lyrics:services:lrclib:on"),
call: LyricProviders.fetchLrclib,
desc: "Lyrics sourced from lrclib.net. Supports both synced and unsynced lyrics. LRCLIB is a free and open-source lyrics provider.",
desc: "Lyrics sourced from official Spotify API.",
},
},
servicesOrder: [],
};
userConfigs.fontSize = userConfigs.fontSize
? Number(userConfigs.fontSize)
: 46;
try {
const rawServicesOrder = LocalStorage.get("popup-lyrics:services-order");
userConfigs.servicesOrder = JSON.parse(rawServicesOrder);
if (!Array.isArray(userConfigs.servicesOrder)) throw "";
userConfigs.servicesOrder = userConfigs.servicesOrder.filter(
(s) => userConfigs.services[s]
); // Remove obsoleted services
const allServices = Object.keys(userConfigs.services);
if (userConfigs.servicesOrder.length !== allServices.length) {
for (const s of allServices) {
if (!userConfigs.servicesOrder.includes(s)) {
userConfigs.servicesOrder.push(s);
}
}
LocalStorage.set(
"popup-lyrics:services-order",
JSON.stringify(userConfigs.servicesOrder)
);
}
} catch {
userConfigs.servicesOrder = Object.keys(userConfigs.services);
LocalStorage.set(
"popup-lyrics:services-order",
JSON.stringify(userConfigs.servicesOrder)
);
}
const lyricVideo = document.createElement("video");
lyricVideo.muted = true;
lyricVideo.width = 600;
switch (userConfigs.ratio) {
case "43":
lyricVideo.height = Math.round((lyricVideo.width * 3) / 4);
break;
case "169":
lyricVideo.height = Math.round((lyricVideo.width * 9) / 16);
break;
default:
lyricVideo.height = lyricVideo.width;
break;
}
let lyricVideoIsOpen = false;
lyricVideo.onenterpictureinpicture = () => {
lyricVideo.play();
lyricVideoIsOpen = true;
tick(userConfigs);
updateTrack();
};
lyricVideo.onleavepictureinpicture = () => {
lyricVideoIsOpen = false;
};
const lyricCanvas = document.createElement("canvas");
lyricCanvas.width = lyricVideo.width;
lyricCanvas.height = lyricVideo.height;
const lyricCtx = lyricCanvas.getContext("2d");
lyricVideo.srcObject = lyricCanvas.captureStream();
lyricCtx.fillRect(0, 0, 1, 1);
lyricVideo.play();
const button = new Spicetify.Topbar.Button(
"Popup Lyrics Plus",
"lyrics",
() => {
if (!lyricVideoIsOpen) {
lyricVideo.requestPictureInPicture();
} else {
document.exitPictureInPicture();
}
}
);
button.element.oncontextmenu = openConfig;
const coverCanvas = document.createElement("canvas");
coverCanvas.width = lyricVideo.width;
coverCanvas.height = lyricVideo.width;
const coverCtx = coverCanvas.getContext("2d");
const largeImage = new Image();
largeImage.onload = () => {
coverCtx.drawImage(
largeImage,
0,
0,
coverCtx.canvas.width,
coverCtx.canvas.width
);
};
userConfigs.backgroundImage = coverCanvas;
let sharedData = {};
Player.addEventListener("songchange", updateTrack);
async function updateTrack() {
if (!lyricVideoIsOpen) {
return;
}
const meta = Player.data.item.metadata;
if (
!Spicetify.URI.isTrack(Player.data.item.uri) &&
!Spicetify.URI.isLocalTrack(Player.data.item.uri)
) {
return;
}
largeImage.src = meta.image_url;
const info = {
duration: Number(meta.duration),
album: meta.album_title,
artist: meta.artist_name,
title: meta.title,
uri: Player.data.item.uri,
};
for (const name of userConfigs.servicesOrder) {
const service = userConfigs.services[name];
if (!service.on) continue;
sharedData = { lyrics: [] };
try {
const data = await service.call(info);
console.log(data);
let dataStr;
// Translate into Eng/Romaji
if (userConfigs.translation2rd == 3) {
//Romaji
dataStr = await intoRomaji(
data.lyrics.map((lyric) => lyric.text).join("\n")
);
// Reformat
for (let i = 0; i < data.lyrics.length; i++) {
// Transfer into format that PopupLyrics accept
// Remove ONE spaces before or after special symbols
// '"…\-!?()[\]:;\/&*+%$#@~^,.。
dataStr[i] = dataStr[i].replace(
/\s*[\'"…\-!?()[\]:;\/&*+%$#@~^,.。]\s*/g,
function (match) {
return match.substring(1, match.length - 1);
}
);
//Replace consecutive spaces with one space
dataStr[i] = dataStr[i].replace(/\s+/g, " ");
data.lyrics[i].text = dataStr[i];
}
} else if (userConfigs.translation2rd == 1) {
//English
dataStr = await intoEnglish(data.lyrics.map((lyric) => lyric.text));
// Reformat
for (let i = 0; i < data.lyrics.length; i++) {
data.lyrics[i].text = dataStr[i];
}
} else if (userConfigs.translation2rd == 4) {
//Pinyin
dataStr = await intoPinyin(
data.lyrics.map((lyric) => lyric.text).join("\n")
);
for (let i = 0; i < data.lyrics.length; i++) {
data.lyrics[i].text = dataStr[i];
}
} else if (userConfigs.translation2rd == 5) {
//Romaja
dataStr = await intoRomaja(
data.lyrics.map((lyric) => lyric.text).join("\n")
);
for (let i = 0; i < data.lyrics.length; i++) {
data.lyrics[i].text = dataStr[i];
}
}
sharedData = data;
if (!sharedData.error) {
return;
}
} catch (err) {
sharedData = { error: "No lyrics" };
}
}
}
async function intoRomaji(str) {
try {
const romajifyTranslator = new overallTranslator("ja");
let tempStr = await romajifyTranslator.romajifyText(str);
// Change translated results into list for reformatting
tempStr = tempStr.split("\n");
return tempStr;
} catch (e) {
return "OK";
}
}