-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·1752 lines (1537 loc) · 62.3 KB
/
Copy pathserver.js
File metadata and controls
executable file
·1752 lines (1537 loc) · 62.3 KB
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 { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import Fastify from "fastify";
import fastifyStatic from "@fastify/static";
import fs from "node:fs";
import { Readable } from "node:stream";
import { Blob } from "node:buffer";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const publicPath = join(__dirname, "public");
try {
if (typeof process.loadEnvFile === "function") process.loadEnvFile(join(__dirname, ".env"));
} catch {
try {
const raw = fs.readFileSync(join(__dirname, ".env"), "utf8");
for (const line of raw.split(/\r?\n/)) {
const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/i);
if (match && !process.env[match[1]]) process.env[match[1]] = match[2].replace(/^["']|["']$/g, "");
}
} catch {}
}
const binaryName = process.platform === "win32" ? "yt-dlp.exe" : "yt-dlp";
const binaryPath = join(__dirname, binaryName);
const GEMINI_KEY = process.env.GEMINI_API_KEY || "";
const GEMINI_MODEL = process.env.GEMINI_MODEL || "gemini-3.5-flash-lite";
const GEMINI_FALLBACK = "gemini-3.1-flash-lite";
const GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/models";
const GEMINI_TIMEOUT_MS = 20000;
const GEMINI_MAX_RPM = 12;
const geminiCalls = [];
function geminiRateAvailable() {
const cutoff = Date.now() - 60000;
while (geminiCalls.length && geminiCalls[0] < cutoff) geminiCalls.shift();
return geminiCalls.length < GEMINI_MAX_RPM;
}
async function callGeminiModel(model, { system, prompt, schema, temperature = 0.9 }) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), GEMINI_TIMEOUT_MS);
try {
const resp = await fetch(`${GEMINI_BASE}/${model}:generateContent?key=${GEMINI_KEY}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
signal: controller.signal,
body: JSON.stringify({
systemInstruction: { parts: [{ text: system }] },
contents: [{ role: "user", parts: [{ text: prompt }] }],
generationConfig: {
responseMimeType: "application/json",
responseSchema: schema,
temperature,
},
}),
});
if (!resp.ok) {
const detail = await resp.text();
const error = new Error(`gemini-${resp.status}`);
error.status = resp.status;
error.detail = detail.slice(0, 300);
throw error;
}
const json = await resp.json();
const text = json?.candidates?.[0]?.content?.parts?.map((p) => p.text).join("") || "";
if (!text) return null;
return JSON.parse(text);
} finally {
clearTimeout(timer);
}
}
async function callGemini(options) {
if (!GEMINI_KEY) return null;
if (!geminiRateAvailable()) {
const error = new Error("gemini-rate-limited");
error.status = 429;
throw error;
}
geminiCalls.push(Date.now());
try {
return await callGeminiModel(GEMINI_MODEL, options);
} catch (e) {
if (e.status === 404 || e.status === 429 || (e.status >= 500 && e.status < 600)) {
console.warn("[Gemini] primary failed, trying fallback:", e.message);
return await callGeminiModel(GEMINI_FALLBACK, options);
}
throw e;
}
}
const TRACK_LIST_SCHEMA = {
type: "OBJECT",
properties: {
title: { type: "STRING" },
description: { type: "STRING" },
tracks: {
type: "ARRAY",
items: {
type: "OBJECT",
properties: {
artist: { type: "STRING" },
title: { type: "STRING" },
},
required: ["artist", "title"],
},
},
},
required: ["title", "tracks"],
};
const MIXES_SCHEMA = {
type: "OBJECT",
properties: {
mixes: {
type: "ARRAY",
items: {
type: "OBJECT",
properties: {
artist: { type: "STRING" },
title: { type: "STRING" },
mixType: { type: "STRING" },
description: { type: "STRING" },
tracks: {
type: "ARRAY",
items: {
type: "OBJECT",
properties: {
artist: { type: "STRING" },
title: { type: "STRING" },
},
required: ["artist", "title"],
},
},
},
required: ["artist", "title", "mixType", "tracks"],
},
},
},
required: ["mixes"],
};
const TRANSLATE_SCHEMA = {
type: "OBJECT",
properties: {
sourceLanguage: { type: "STRING" },
sameLanguage: { type: "BOOLEAN" },
lines: { type: "ARRAY", items: { type: "STRING" } },
},
required: ["sourceLanguage", "sameLanguage", "lines"],
};
const CURATOR_SYSTEM = [
"You are an expert music curator building listening queues for a music player.",
"Rules you must always follow:",
"1. Only suggest real, commercially released songs that exist on streaming services.",
"2. Never invent song titles, never suggest podcasts, interviews, tutorials or non music audio.",
"3. Use the exact primary artist name and the exact official track title, with no extra words such as Official Video, Remix, Live or Lyrics.",
"4. Build a queue that flows: keep energy, tempo and mood coherent from one track to the next, and vary the artists so no artist dominates.",
"5. Mix familiar picks with a few well chosen deeper cuts that genuinely match the taste shown.",
"6. Never repeat a track that is listed as already played or excluded.",
].join(" ");
function normalizeMatchText(value) {
return String(value || "")
.toLowerCase()
.replace(/\(.*?\)|\[.*?\]/g, " ")
.replace(/[^a-z0-9\s]/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function textsRelated(a, b) {
const left = normalizeMatchText(a);
const right = normalizeMatchText(b);
if (!left || !right) return false;
if (left === right) return true;
if (left.includes(right) || right.includes(left)) return true;
const leftWords = new Set(left.split(" "));
const rightWords = right.split(" ");
const shared = rightWords.filter((w) => leftWords.has(w)).length;
return shared / Math.max(1, rightWords.length) >= 0.7;
}
async function resolveSuggestedTrack(candidate) {
const artist = String(candidate?.artist || "").trim();
const title = String(candidate?.title || "").trim();
if (!artist || !title) return null;
try {
const url = `https://itunes.apple.com/search?term=${encodeURIComponent(
`${artist} ${title}`
)}&media=music&entity=song&limit=6`;
const resp = await fetch(url);
if (resp.ok) {
const json = await resp.json();
const rows = Array.isArray(json?.results) ? json.results : [];
for (const row of rows) {
if (textsRelated(row.trackName, title) && textsRelated(row.artistName, artist)) {
return { ...row, source: "catalog", aiSuggested: true };
}
}
}
} catch {}
try {
const res = await ytSearch(`${artist} ${title} audio`);
const videos = Array.isArray(res?.videos) ? res.videos.slice(0, 6) : [];
for (const video of videos) {
const classified = classifyYouTubeResult(video);
if (classified.kind === "reject") continue;
if (!textsRelated(video.title, title)) continue;
return {
trackName: title,
artistName: artist,
artworkUrl100: video.thumbnail,
artworkUrl60: video.thumbnail,
trackId: video.videoId,
videoId: video.videoId,
collectionName: "YouTube",
source: "youtube",
trackTimeMillis: (Number(video.seconds) || 0) * 1000,
trackExplicitness: /\bexplicit\b/i.test(String(video.title || "")) ? "explicit" : "notExplicit",
aiSuggested: true,
};
}
} catch {}
return null;
}
async function resolveSuggestions(candidates, excludeKeys) {
const seen = new Set(excludeKeys || []);
const limit = 5;
const resolved = [];
for (let i = 0; i < candidates.length; i += limit) {
const slice = candidates.slice(i, i + limit);
const batch = await Promise.all(slice.map((c) => resolveSuggestedTrack(c).catch(() => null)));
for (const track of batch) {
if (!track) continue;
const key = normalizeMatchText(`${track.artistName} ${track.trackName}`);
if (seen.has(key)) continue;
seen.add(key);
resolved.push(track);
}
}
return resolved;
}
function describeTrackList(list, label) {
const items = (Array.isArray(list) ? list : [])
.slice(0, 25)
.map((t) => `${t.artist || t.artistName || ""} - ${t.title || t.trackName || ""}`.trim())
.filter((line) => line.length > 2);
if (!items.length) return "";
return `${label}:\n${items.join("\n")}`;
}
const fastify = Fastify();
const LRCLIB_BASE = "https://lrclib.net/api";
const LRCLIB_UA = "THPMusic/1.0 (+https://thehtmlproject.com)";
const LRCLIB_TIMEOUT_MS = 7000;
const LYRICS_TTL_MS = 6 * 60 * 60 * 1000;
const LYRICS_MISS_TTL_MS = 10 * 60 * 1000;
const LYRICS_CACHE_LIMIT = 400;
if (typeof global.File === "undefined") {
global.File = class File extends Blob {
constructor(parts, name, options = {}) {
super(parts, options);
this.name = String(name || "");
this.lastModified = options.lastModified ?? Date.now();
}
get [Symbol.toStringTag]() {
return "File";
}
};
}
const { default: fetch } = await import("node-fetch");
const { default: ytSearch } = await import("yt-search");
const { default: YTDlpWrap } = await import("yt-dlp-wrap");
let ytDlpWrap;
(async () => {
try {
if (!fs.existsSync(binaryPath)) {
console.log("[Engine] Downloading binary...");
await YTDlpWrap.default.downloadFromGithub(binaryPath);
if (process.platform !== "win32") fs.chmodSync(binaryPath, "755");
}
ytDlpWrap = new YTDlpWrap.default(binaryPath);
console.log("[Engine] Ready.");
} catch (e) {
console.error("[Engine] Error:", e);
}
})();
const NON_MUSIC_PATTERN =
/\b(reaction|reacts?|review|tutorial|lesson|how\s+to|interview|podcast|vlog|trailer|gameplay|walkthrough|unboxing|documentary|behind\s+the\s+scenes|making\s+of|explained|analysis|breakdown|top\s+\d+|compilation|dj\s+set|radio\s+show|episode|news|asmr|guitar\s+tab|announcement|teaser|shorts|flashmob|flash\s+mob|movie\s+scene|film\s+scene|muppet|got\s+talent|the\s+voice|x\s+factor|american\s+idol|talent\s+show|audition|wedding|proposal|commercial|advert|sketch|comedy|meme|prank|first\s+time\s+hearing|blind\s+rank|tier\s+list|full\s+album|greatest\s+hits|mix\s+\d+\s*hour|nonstop|megamix)\b/i;
const COMMUNITY_PATTERN =
/\b(remix|cover|sped\s*up|speed\s*up|slowed|reverb|nightcore|8d\s*audio|bass\s*boosted|mashup|karaoke|instrumental|acapella|a\s*cappella|vocals?\s*only|ai\s+cover|bootleg|refix|extended\s+mix|tribute|piano\s+version|guitar\s+version|violin|orchestral|choir|marching\s+band|loop|1\s*hour|10\s*hours|fan\s*made|unofficial)\b/i;
const OFFICIAL_PATTERN =
/\b(official\s+(music\s+)?video|official\s+audio|official\s+visualizer|official\s+lyric|lyric\s+video|visualizer|audio\s+oficial|video\s+oficial)\b/i;
const REMASTER_HINT = /\b(remaster(ed)?|anniversary|deluxe)\b/i;
function classifyYouTubeResult(video, hints) {
const title = String(video?.title || "");
const author = String(video?.author?.name || "");
const seconds = Number(video?.seconds) || 0;
if (seconds > 0 && (seconds < 60 || seconds > 900)) return { kind: "reject", reason: "duration" };
if (NON_MUSIC_PATTERN.test(title)) return { kind: "reject", reason: "non-music" };
const isTopic = /-\s*topic\s*$/i.test(author);
const isVevo = /vevo$/i.test(author);
const isOfficialChannel = isTopic || isVevo;
if (isOfficialChannel) return { kind: "song", reason: "official-channel" };
if (COMMUNITY_PATTERN.test(title)) {
return { kind: "community", reason: "derivative" };
}
if (hints) {
const normalizedAuthor = normalizeMatchText(author);
const normalizedTitle = normalizeMatchText(title);
if (normalizedAuthor) {
for (const artist of hints.artists || []) {
if (!artist) continue;
if (normalizedAuthor === artist || normalizedAuthor.includes(artist) || artist.includes(normalizedAuthor)) {
return { kind: "song", reason: "catalog-artist" };
}
}
}
if (normalizedAuthor && hints.query && hints.query.includes(normalizedAuthor)) {
return { kind: "song", reason: "query-artist" };
}
}
if (OFFICIAL_PATTERN.test(title)) return { kind: "community", reason: "unverified-official-label" };
if (REMASTER_HINT.test(title)) return { kind: "community", reason: "unverified-remaster" };
if (/.+\s[-\u2013\u2014]\s.+/.test(title)) return { kind: "community", reason: "artist-title" };
return { kind: "community", reason: "unverified" };
}
function mapYouTubeVideo(video, kind) {
return {
trackName: video.title,
artistName: video.author?.name || "",
artworkUrl100: video.thumbnail,
artworkUrl60: video.thumbnail,
trackId: video.videoId,
videoId: video.videoId,
collectionName: "YouTube",
source: "youtube",
community: kind === "community",
trackTimeMillis: (Number(video.seconds) || 0) * 1000,
trackExplicitness: /\bexplicit\b/i.test(String(video.title || "")) ? "explicit" : "notExplicit",
};
}
fastify.get("/music/meta", async (req, reply) => {
const { q } = req.query;
if (!q) return reply.status(400).send({ error: "Missing query" });
const includeCommunity = String(req.query.community || "0") === "1";
try {
const [itunesSongs, itunesArtists, ytRes] = await Promise.allSettled([
fetch(
`https://itunes.apple.com/search?term=${encodeURIComponent(q)}&media=music&entity=song&limit=20`
).then((r) => r.json()),
fetch(
`https://itunes.apple.com/search?term=${encodeURIComponent(q)}&media=music&entity=musicArtist&limit=8`
).then((r) => r.json()),
ytSearch(q),
]);
const songs = [];
const artists = [];
const playlists = [];
let rejected = 0;
if (itunesSongs.status === "fulfilled" && Array.isArray(itunesSongs.value?.results)) {
for (const row of itunesSongs.value.results) {
songs.push({ ...row, source: "catalog", community: false });
}
}
if (itunesArtists.status === "fulfilled" && Array.isArray(itunesArtists.value?.results)) {
for (const row of itunesArtists.value.results) {
if (!row.artistName) continue;
artists.push({
artistName: row.artistName,
artistId: row.artistId,
primaryGenreName: row.primaryGenreName || "",
source: "catalog",
});
}
}
const hints = {
artists: new Set(
[...songs.map((s) => s.artistName), ...artists.map((a) => a.artistName)]
.map(normalizeMatchText)
.filter((v) => v.length > 2)
),
titles: new Set(songs.map((s) => normalizeMatchText(s.trackName)).filter((v) => v.length > 3)),
query: normalizeMatchText(q),
};
if (ytRes.status === "fulfilled") {
const videos = Array.isArray(ytRes.value?.videos) ? ytRes.value.videos.slice(0, 20) : [];
for (const video of videos) {
const classified = classifyYouTubeResult(video, hints);
if (classified.kind === "reject") {
rejected++;
continue;
}
if (classified.kind === "community" && !includeCommunity) continue;
songs.push(mapYouTubeVideo(video, classified.kind));
}
const lists = Array.isArray(ytRes.value?.playlists) ? ytRes.value.playlists.slice(0, 10) : [];
for (const list of lists) {
const listId = list.listId || list.playlistId;
if (!listId) continue;
playlists.push({
listId,
title: list.title || "Playlist",
author: list.author?.name || "YouTube",
thumbnail: list.thumbnail || "",
videoCount: Number(list.videoCount) || null,
source: "community",
});
}
}
const ranked = songs
.map((song, index) => {
const title = String(song.trackName || "");
const artistName = String(song.artistName || "");
let rank = 0;
if (DERIVATIVE_PATTERN.test(title)) rank += 4;
if (DERIVATIVE_ARTIST.test(artistName)) rank += 5;
if (LIVE_HINT.test(title)) rank += 2;
if (song.community) rank += 1;
if (hints.query && normalizeMatchText(artistName) && hints.query.includes(normalizeMatchText(artistName))) rank -= 2;
return { song, rank, index };
})
.sort((a, b) => a.rank - b.rank || a.index - b.index)
.map((entry) => entry.song);
return reply.send({
resultCount: ranked.length,
results: ranked,
songs: ranked,
artists,
playlists,
rejected,
});
} catch (e) {
console.error(e);
return reply.status(500).send({ error: "Meta failed" });
}
});
const playlistCache = new Map();
const PLAYLIST_TTL_MS = 30 * 60 * 1000;
fastify.get("/music/playlist", async (req, reply) => {
const { listId } = req.query || {};
if (!listId || !/^[A-Za-z0-9_-]{10,64}$/.test(String(listId))) {
return reply.status(400).send({ error: "Invalid listId" });
}
if (!ytDlpWrap) return reply.status(503).send({ error: "Engine not ready" });
const cached = playlistCache.get(listId);
if (cached && cached.expiresAt > Date.now()) return reply.send(cached.value);
try {
const out = await execYtDlpForText([
`https://www.youtube.com/playlist?list=${listId}`,
"--flat-playlist",
"--dump-single-json",
"--playlist-end",
"100",
"--no-warnings",
]);
const data = JSON.parse(String(out));
const entries = Array.isArray(data?.entries) ? data.entries : [];
const tracks = entries
.filter((entry) => entry?.id)
.map((entry) => {
const thumb = Array.isArray(entry.thumbnails) && entry.thumbnails.length
? entry.thumbnails[entry.thumbnails.length - 1].url
: `https://i.ytimg.com/vi/${entry.id}/hqdefault.jpg`;
return {
trackName: entry.title || "Unknown",
artistName: entry.uploader || entry.channel || data.uploader || "",
artworkUrl100: thumb,
artworkUrl60: thumb,
trackId: entry.id,
videoId: entry.id,
collectionName: data.title || "Playlist",
source: "youtube",
community: true,
trackTimeMillis: (Number(entry.duration) || 0) * 1000,
};
})
.filter((track) => {
const seconds = track.trackTimeMillis / 1000;
if (seconds > 0 && (seconds < 45 || seconds > 900)) return false;
return !NON_MUSIC_PATTERN.test(track.trackName);
});
const value = { title: data?.title || "Playlist", resultCount: tracks.length, results: tracks };
if (playlistCache.size > 40) {
const oldest = playlistCache.keys().next().value;
if (oldest !== undefined) playlistCache.delete(oldest);
}
playlistCache.set(listId, { value, expiresAt: Date.now() + PLAYLIST_TTL_MS });
return reply.send(value);
} catch (e) {
console.error("[Playlist]", e.message || e);
return reply.status(502).send({ error: "Playlist failed" });
}
});
const DERIVATIVE_PATTERN =
/\b(acapella|a\s*cappella|vocals?\s*only|instrumental|karaoke|backing\s*track|cover|remix|mashup|nightcore|sped\s*up|speed\s*up|slowed|reverb|8d\s*audio|bass\s*boosted|reversed|remake|rendition|tribute|fingerstyle|finger\s*style|piano\s+version|guitar\s+version|violin|cello|flute|saxophone|orchestral|string\s+quartet|marching\s+band|music\s+box|lullaby|8\s*bit|chiptune|midi|meditation|sleep\s+version|study\s+version|ai\s+cover|parody|in\s+the\s+style\s+of|made\s+famous\s+by|originally\s+performed)\b/i;
const DERIVATIVE_ARTIST =
/\b(string\s+quartet|quartet\s+tribute|tribute\s+(band|players|orchestra)|piano\s+tribute|lullaby|rockabye|kidz\s+bop|karaoke|the\s+karaoke|instrumental\s+(band|players)|8\s*bit|chiptune|music\s+box|meditation|relaxing|study\s+music|cover\s+band|made\s+famous|sleep\s+baby|baby\s+lullaby|guitar\s+tribute|vitamin\s+string)\b/i;
const LIVE_HINT =
/\b(live|concert|tour|festival|session|unplugged|gala|awards?|tiny\s+desk|npr|fallon|colbert|kimmel|snl|glastonbury|coachella|lollapalooza|live\s+lounge|acoustic|performance|residency|halftime|super\s*bowl)\b/i;
const ARTIST_CHANNEL_SUFFIX = /^(vevo|official|music|band|tv|records|channel|hd|topic)$/i;
function authorIsArtist(author, artist) {
const normalizedAuthor = normalizeMatchText(author);
const normalizedArtist = normalizeMatchText(artist);
if (!normalizedAuthor || normalizedArtist.length < 3) return "none";
if (normalizedAuthor === normalizedArtist) return "exact";
if (normalizedAuthor.startsWith(normalizedArtist)) {
const rest = normalizedAuthor.slice(normalizedArtist.length).trim();
if (!rest) return "exact";
if (rest.split(" ").every((word) => ARTIST_CHANNEL_SUFFIX.test(word))) return "exact";
}
if (normalizedAuthor.includes(normalizedArtist) || normalizedArtist.includes(normalizedAuthor)) return "loose";
return "none";
}
function scoreVideoCandidate(video, targetSeconds, query, artist) {
const title = String(video.title || "");
const author = String(video.author?.name || "");
const seconds = Number(video.seconds) || 0;
const lowerQuery = String(query || "").toLowerCase();
let score = 0;
if (targetSeconds && seconds) {
const delta = seconds - targetSeconds;
const diff = Math.abs(delta);
if (diff <= 1) score += 70;
else if (diff <= 3) score += 52;
else if (diff <= 6) score += 28;
else if (diff <= 12) score += 4;
else score -= Math.min(60, diff * 1.5);
if (delta > 8) score -= Math.min(45, (delta - 8) * 2);
}
const isTopic = /-\s*topic\s*$/i.test(author);
const isVevo = /vevo$/i.test(author);
const authorMatch = authorIsArtist(author, artist);
if (isTopic) score += 50;
else if (isVevo) score += 34;
else if (authorMatch === "exact") score += 32;
else if (authorMatch === "loose") score += 8;
if (/official\s*audio|full\s*audio|\baudio\b/i.test(title)) score += 20;
if (/official\s*visualizer|visualizer/i.test(title)) score += 8;
if (/lyric\s*video|\(lyrics\)/i.test(title)) score += 6;
if (/official\s*(music\s*)?video/i.test(title)) score -= 6;
if (REMASTER_HINT.test(title)) score += 3;
if (DERIVATIVE_PATTERN.test(title) && !DERIVATIVE_PATTERN.test(lowerQuery)) score -= 85;
if (LIVE_HINT.test(title) && !LIVE_HINT.test(lowerQuery)) score -= 30;
if (NON_MUSIC_PATTERN.test(title)) score -= 90;
if (seconds > 0 && seconds < 45) score -= 40;
if (seconds > 900) score -= 30;
const views = Number(video.views) || 0;
if (views > 0) score += Math.min(10, Math.log10(views));
return score;
}
fastify.get("/music/search", async (req, reply) => {
const q = req.query.q;
if (!q) return reply.status(400).send({ error: "Query required" });
const targetSeconds = Number(req.query.duration) > 0 ? Number(req.query.duration) : null;
const artist = String(req.query.artist || "");
try {
const result = await ytSearch(q);
const videos = Array.isArray(result?.videos) ? result.videos.slice(0, 15) : [];
if (!videos.length) return reply.status(404).send({ error: "No results" });
const wantsDerivative = DERIVATIVE_PATTERN.test(q);
const clean = wantsDerivative
? videos
: videos.filter((v) => {
const title = String(v.title || "");
if (NON_MUSIC_PATTERN.test(title)) return false;
if (DERIVATIVE_PATTERN.test(title)) return false;
return true;
});
const pool = clean.length ? clean : videos;
let best = pool[0];
let bestScore = -Infinity;
for (const video of pool) {
const score = scoreVideoCandidate(video, targetSeconds, q, artist);
if (score > bestScore) {
bestScore = score;
best = video;
}
}
return reply.send({
videoId: best.videoId,
duration: Number(best.seconds) || null,
title: best.title || "",
author: best.author?.name || "",
score: Math.round(bestScore),
});
} catch (e) {
return reply.status(500).send({ error: "Search failed" });
}
});
fastify.get("/music/lyrics", async (req, reply) => {
const { artist = "", title = "", duration = "" } = req.query || {};
if (!artist && !title) return reply.status(400).send({ error: "Missing artist or title" });
const durationSec = Number(duration) > 0 ? Number(duration) : null;
const cacheKey = lyricsCacheKey(artist, title, durationSec);
const cached = readLyricsCache(cacheKey);
if (cached) {
if (!cached.value) return reply.status(404).send({ error: "No lyrics" });
return reply.send(cached.value);
}
try {
const found = await resolveLyrics(artist, title, durationSec);
if (!found) {
writeLyricsCache(cacheKey, null, LYRICS_MISS_TTL_MS);
return reply.status(404).send({ error: "No lyrics" });
}
writeLyricsCache(cacheKey, found, LYRICS_TTL_MS);
return reply.send(found);
} catch (e) {
console.error("[Lyrics]", e.message || e);
return reply.status(500).send({ error: "Lyrics failed" });
}
});
fastify.get("/music/radio", async (req, reply) => {
const { q } = req.query || {};
if (!q) return reply.status(400).send({ error: "Missing query" });
const includeCommunity = String(req.query.community || "0") === "1";
try {
const [ytRes, itunesRes] = await Promise.allSettled([
ytSearch(q),
fetch(
`https://itunes.apple.com/search?term=${encodeURIComponent(q)}&media=music&entity=song&limit=20`
).then((r) => r.json()),
]);
const results = [];
if (itunesRes.status === "fulfilled" && Array.isArray(itunesRes.value?.results)) {
for (const row of itunesRes.value.results) {
const title = String(row.trackName || "");
const artist = String(row.artistName || "");
if (DERIVATIVE_PATTERN.test(title) || DERIVATIVE_ARTIST.test(artist)) continue;
results.push({ ...row, source: "catalog", community: false, collectionName: row.collectionName || "Radio" });
}
}
if (ytRes.status === "fulfilled") {
const videos = Array.isArray(ytRes.value?.videos) ? ytRes.value.videos.slice(0, 20) : [];
const hints = {
artists: new Set(results.map((r) => normalizeMatchText(r.artistName)).filter((v) => v.length > 2)),
titles: new Set(results.map((r) => normalizeMatchText(r.trackName)).filter((v) => v.length > 3)),
query: normalizeMatchText(q),
};
for (const video of videos) {
const classified = classifyYouTubeResult(video, hints);
if (classified.kind === "reject") continue;
if (classified.kind === "community" && !includeCommunity) continue;
const title = String(video.title || "");
if (DERIVATIVE_PATTERN.test(title)) continue;
if (LIVE_HINT.test(title) && !LIVE_HINT.test(q)) continue;
results.push({ ...mapYouTubeVideo(video, classified.kind), collectionName: "Radio" });
}
}
const seen = new Set();
const unique = [];
for (const row of results) {
const key = `${normalizeMatchText(row.artistName)}|${normalizeMatchText(row.trackName)}`;
if (!key.trim() || seen.has(key)) continue;
seen.add(key);
unique.push(row);
}
return reply.send({ resultCount: unique.length, results: unique });
} catch (e) {
console.error("[Radio]", e.message || e);
return reply.status(500).send({ error: "Radio failed" });
}
});
const directUrlCache = new Map();
const DIRECT_URL_TTL_MS = 30 * 60 * 1000;
const pendingDirectUrl = new Map();
async function execYtDlpForText(args) {
if (ytDlpWrap && typeof ytDlpWrap.execPromise === "function") {
return await ytDlpWrap.execPromise(args);
}
return await new Promise((resolve, reject) => {
try {
const child = ytDlpWrap.exec(args);
let out = "";
let err = "";
if (child.stdout) child.stdout.on("data", (d) => (out += d.toString()));
if (child.stderr) child.stderr.on("data", (d) => (err += d.toString()));
child.on("error", reject);
child.on("close", (code) => {
if (code === 0) resolve(out);
else reject(new Error(err || `yt-dlp exited with code ${code}`));
});
} catch (e) {
reject(e);
}
});
}
async function resolveDirectAudioUrl(id) {
const now = Date.now();
const cached = directUrlCache.get(id);
if (cached && cached.expiresAt > now) return cached.url;
const inFlight = pendingDirectUrl.get(id);
if (inFlight) return await inFlight;
const task = resolveDirectAudioUrlUncached(id);
pendingDirectUrl.set(id, task);
try {
return await task;
} finally {
pendingDirectUrl.delete(id);
}
}
const INVIDIOUS_URL = String(process.env.INVIDIOUS_URL || "").trim().replace(/\/+$/, "");
const INVIDIOUS_ITAGS = [140, 251];
const INVIDIOUS_PROBE_TIMEOUT_MS = 8000;
const INVIDIOUS_BREAKER_THRESHOLD = 3;
const INVIDIOUS_BREAKER_COOLDOWN_MS = 5 * 60 * 1000;
const invidiousBreaker = { failures: 0, openUntil: 0 };
function invidiousAvailable() {
if (!INVIDIOUS_URL) return false;
if (invidiousBreaker.openUntil > Date.now()) return false;
return true;
}
function noteInvidiousResult(ok) {
if (ok) {
invidiousBreaker.failures = 0;
invidiousBreaker.openUntil = 0;
return;
}
invidiousBreaker.failures += 1;
if (invidiousBreaker.failures >= INVIDIOUS_BREAKER_THRESHOLD) {
invidiousBreaker.openUntil = Date.now() + INVIDIOUS_BREAKER_COOLDOWN_MS;
invidiousBreaker.failures = 0;
console.warn("[Invidious] breaker open, pausing for 5 minutes");
}
}
function invidiousStreamUrls(id, itag) {
const base = `${INVIDIOUS_URL}/latest_version?id=${encodeURIComponent(id)}&itag=${itag}`;
return [`${base}&local=true`, base];
}
async function resolveViaInvidious(id) {
if (!invidiousAvailable()) return null;
for (const itag of INVIDIOUS_ITAGS) {
for (const url of invidiousStreamUrls(id, itag)) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), INVIDIOUS_PROBE_TIMEOUT_MS);
try {
const resp = await fetch(url, {
headers: { Range: "bytes=0-1024", Accept: "*/*" },
redirect: "follow",
signal: controller.signal,
});
const type = resp.headers.get("content-type") || "";
if ((resp.status === 206 || resp.status === 200) && type.startsWith("audio")) {
if (resp.body && typeof resp.body.cancel === "function") resp.body.cancel().catch(() => {});
noteInvidiousResult(true);
return url;
}
} catch {
continue;
} finally {
clearTimeout(timer);
}
}
}
noteInvidiousResult(false);
return null;
}
const EXTRACT_STRATEGIES = [
[],
["--extractor-args", "youtube:player_client=default,android_vr"],
["--extractor-args", "youtube:player_client=web_safari,tv"],
["--extractor-args", "youtube:player_client=ios"],
];
async function resolveViaYtDlp(id) {
const baseArgs = [
`https://www.youtube.com/watch?v=${id}`,
"-f",
"bestaudio[ext=m4a]/bestaudio[ext=mp4]/bestaudio/best[acodec!=none]",
"--no-playlist",
"--no-warnings",
"-g",
];
let lastError = null;
for (const strategy of EXTRACT_STRATEGIES) {
try {
const out = await execYtDlpForText([...baseArgs, ...strategy]);
const url = String(out)
.trim()
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.startsWith("http"))
.pop();
if (url) {
directUrlCache.set(id, { url, expiresAt: Date.now() + DIRECT_URL_TTL_MS });
if (strategy.length) console.log(`[Extract] ${id} recovered via ${strategy[1]}`);
return url;
}
lastError = new Error("no-direct-url");
} catch (e) {
lastError = e;
}
}
throw lastError || new Error("no-direct-url");
}
async function resolveDirectAudioUrlUncached(id) {
if (invidiousAvailable()) {
const fastUrl = await resolveViaInvidious(id);
if (fastUrl) {
console.log(`[Extract] ${id} via Invidious`);
directUrlCache.set(id, { url: fastUrl, expiresAt: Date.now() + DIRECT_URL_TTL_MS });
return fastUrl;
}
console.warn(`[Extract] ${id} Invidious unavailable, using yt-dlp`);
}
let lastError = null;
try {
return await resolveViaYtDlp(id);
} catch (e) {
lastError = e;
}
const invidiousUrl = await resolveViaInvidious(id);
if (invidiousUrl) {
console.log(`[Extract] ${id} recovered via Invidious`);
directUrlCache.set(id, { url: invidiousUrl, expiresAt: Date.now() + DIRECT_URL_TTL_MS });
return invidiousUrl;
}
console.error(`[Extract] all strategies failed for ${id}:`, lastError?.message || lastError);
throw lastError || new Error("no-direct-url");
}
const lyricsCache = new Map();
const LYRIC_NOISE_WORDS =
"official|officiel|video|videoclip|audio|lyric|lyrics|letra|visualizer|visualiser|hd|hq|4k|1080p|remaster|remastered|explicit|clean|mv|m\\/v|music\\s*video|full\\s*song|with\\s*lyrics|color\\s*coded|sub\\s*espa\\u00f1ol|legendado";
const LYRIC_NOISE_PARENS = new RegExp(
`\\((?:[^()]*(?:${LYRIC_NOISE_WORDS})[^()]*)\\)|\\[(?:[^\\[\\]]*(?:${LYRIC_NOISE_WORDS})[^\\[\\]]*)\\]`,
"gi"
);
const LYRIC_NOISE_TRAILING = new RegExp(
`\\s*[-|\\u2013\\u2014]\\s*(?:${LYRIC_NOISE_WORDS})[^-|\\u2013\\u2014]*$`,
"gi"
);
const LYRIC_FEATURE = /\s*[([]?\s*(?:feat\.?|ft\.?|featuring|with)\s+[^)\]]*[)\]]?\s*$/gi;
function cleanLyricTitle(raw) {
let value = String(raw || "");
value = value.replace(LYRIC_NOISE_PARENS, " ");
value = value.replace(LYRIC_NOISE_TRAILING, " ");
value = value.replace(LYRIC_FEATURE, " ");
value = value.replace(/[“”"]/g, "");
value = value.replace(/\s{2,}/g, " ").trim();
value = value.replace(/[\s\-\u2013\u2014|]+$/g, "").trim();
return value;
}
function cleanLyricArtist(raw) {
let value = String(raw || "");
value = value.replace(/\s*-\s*Topic\s*$/i, "");
value = value.replace(/VEVO$/i, "");
value = value.replace(/\s*(?:official|music|records|channel|tv)\s*$/i, "");
value = value.replace(LYRIC_NOISE_PARENS, " ");
value = value.replace(/\s{2,}/g, " ").trim();
return value;
}
function splitArtistTitle(value) {
const match = String(value || "").match(/^\s*(.+?)\s+[-\u2013\u2014]\s+(.+?)\s*$/);
if (!match) return null;
return { artist: match[1].trim(), title: match[2].trim() };
}
function buildLyricCandidates(rawArtist, rawTitle) {
const candidates = [];
const push = (artist, title) => {
const a = String(artist || "").trim();
const t = String(title || "").trim();
if (!t) return;
const dupe = candidates.some(
(c) => c.artist.toLowerCase() === a.toLowerCase() && c.title.toLowerCase() === t.toLowerCase()
);
if (dupe) return;
candidates.push({ artist: a, title: t });
};
const cleanArtist = cleanLyricArtist(rawArtist);
const cleanTitle = cleanLyricTitle(rawTitle);
const combined = splitArtistTitle(cleanTitle);
if (combined) {
push(cleanLyricArtist(combined.artist), cleanLyricTitle(combined.title));
push(cleanArtist, cleanLyricTitle(combined.title));
}
push(cleanArtist, cleanTitle);
push(String(rawArtist || "").trim(), String(rawTitle || "").trim());
if (combined) push("", cleanLyricTitle(combined.title));
push("", cleanTitle);
return candidates.slice(0, 6);
}
async function lrcLibRequest(path, params) {
const url = `${LRCLIB_BASE}${path}?${params.toString()}`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), LRCLIB_TIMEOUT_MS);