-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
1960 lines (1681 loc) Β· 69.7 KB
/
server.mjs
File metadata and controls
1960 lines (1681 loc) Β· 69.7 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
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Aura Music Server
// YouTube Music backend using youtubei.js + yt-dlp
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import 'dotenv/config.js';
import express from "express";
import { Innertube } from "youtubei.js";
import path from "path";
import { fileURLToPath } from "url";
import { createHash } from "crypto";
import { createProxyMiddleware } from "http-proxy-middleware";
import rateLimit from "express-rate-limit";
import timeout from "connect-timeout";
import { createCache } from "./backend/cache/cache.mjs";
import { createAuthToken, extractBearerToken, verifyAuthToken } from "./backend/auth/token.mjs";
import {
createOrUpdateEmailUser,
createUser,
getUserById,
getUserLibrary,
loginUser,
updateUserLibrary,
updateUserPassword,
} from "./backend/auth/userStore.mjs";
import { sendEmailOtp, verifyEmailOtpCode } from "./backend/auth/emailOtp.mjs";
import { recordTrackIssue } from "./backend/feedback/issueStore.mjs";
import { resolveStreamUrl, resolveStreamWithMeta } from "./backend/resolver/streamResolver.mjs";
import { downloadToCache, getCachedFilePath, getCacheStatus } from "./backend/cache/audioCache.mjs";
import { ytdlpQueue } from "./backend/queue/ytdlpQueue.mjs";
import { buildYtdlpArgs, getYtdlpProxy } from "./backend/providers/ytdlpProvider.mjs";
import { spawnWithTimeout } from "./backend/lib/spawnWithTimeout.mjs";
import { logger } from "./backend/lib/logger.mjs";
import { metrics } from "./backend/lib/metrics.mjs";
import { scheduleYtdlpAutoUpdate } from "./backend/lib/ytdlpAutoUpdate.mjs";
import { getRecommendations, trackUserAction } from "./backend/reco/recommendations.mjs";
import { recordTrackPlay } from "./backend/reco/trackPlayLogger.mjs";
import { calculateUserDNA, getUserDNA, findSonicTwins, invalidateUserDNA } from "./backend/reco/musicDna.mjs";
import { initializeMusicDNASchema } from "./backend/db/musicDnaSchema.mjs";
import { pool } from "./backend/db/postgres.mjs";
import { normalizeLibraryPayload } from "./shared/userLibrary.js";
const PORT = process.env.PORT || 3001;
const app = express();
// If this server is behind a reverse proxy (Nginx/Cloudflare/Traefik), Express must
// trust the proxy in order to correctly interpret `X-Forwarded-For` and avoid
// express-rate-limit's proxy safety checks.
//
// - Set `TRUST_PROXY=1` (single proxy hop) or `TRUST_PROXY=true` (any number)
// - If unset, we default to 1 in production for typical deployments.
const TRUST_PROXY_RAW = (process.env.TRUST_PROXY ?? '').toString().trim();
if (TRUST_PROXY_RAW) {
const v = TRUST_PROXY_RAW.toLowerCase();
if (v === 'true') app.set('trust proxy', true);
else if (v === 'false') app.set('trust proxy', false);
else if (!Number.isNaN(Number(v))) app.set('trust proxy', Number(v));
else app.set('trust proxy', TRUST_PROXY_RAW);
} else if ((process.env.NODE_ENV || '').toLowerCase() === 'production') {
app.set('trust proxy', 1);
}
// JSON body parsing (used by /api/* endpoints)
app.use(express.json({ limit: "512kb" }));
// basic health endpoint (deployment / load balancers)
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
// request timeout (prevents long-hanging requests)
const requestTimeout = process.env.REQUEST_TIMEOUT || "10s";
const timeoutMiddleware = timeout(requestTimeout);
const BACKEND_STREAMING_ENABLED = String(process.env.BACKEND_STREAMING_ENABLED || '').trim().toLowerCase() === 'true';
const shouldSkipRequestTimeout = (req) =>
req.path.startsWith("/api/yt/stream/") ||
(BACKEND_STREAMING_ENABLED && (
req.path.startsWith("/api/yt/pipe/") ||
req.path.startsWith("/api/yt/download/") ||
req.path.startsWith("/api/yt/cache/")
));
app.use((req, res, next) => {
if (shouldSkipRequestTimeout(req)) {
req.setTimeout?.(0);
res.setTimeout?.(0);
return next();
}
return timeoutMiddleware(req, res, next);
});
app.use((req, res, next) => {
if (req.timedout) {
if (!res.headersSent) res.status(503).json({ error: "Request timeout" });
return;
}
next();
});
const YT_DLP_BIN = process.env.YT_DLP_BIN || "yt-dlp";
const YT_SOURCE_ADDRESS = process.env.YT_SOURCE_ADDRESS;
const YT_EXTRACTOR_ARGS = process.env.YT_EXTRACTOR_ARGS || "";
const YT_DLP_JS_RUNTIMES = process.env.YT_DLP_JS_RUNTIMES || "node";
const YT_DLP_PROXY = getYtdlpProxy();
const YT_PLAYER_SKIP = process.env.YT_PLAYER_SKIP || "webpage,configs";
const HTTP_UA = process.env.HTTP_UA || "NullMusicPlayer/1.0 (+https://github.com)";
const SPOTIFY_CLIENT_ID = String(process.env.SPOTIFY_CLIENT_ID || "").trim();
const SPOTIFY_CLIENT_SECRET = String(process.env.SPOTIFY_CLIENT_SECRET || "").trim();
const SPOTIFY_TOKEN_ENDPOINT = String(process.env.SPOTIFY_TOKEN_ENDPOINT || "https://accounts.spotify.com/api/token").trim();
const SPOTIFY_API_BASE = String(process.env.SPOTIFY_API_BASE || "https://api.spotify.com/v1").replace(/\/+$/, "");
const LASTFM_API_KEY = String(process.env.LASTFM_API_KEY || "").trim();
const LASTFM_API_SECRET = String(process.env.LASTFM_API_SECRET || "").trim();
const LASTFM_SESSION_KEY = String(process.env.LASTFM_SESSION_KEY || "").trim();
const LASTFM_API_BASE = String(process.env.LASTFM_API_BASE || "https://ws.audioscrobbler.com/2.0/").trim();
let spotifyTokenCache = {
accessToken: "",
expiresAt: 0,
};
const RECO_API_KEY = process.env.RECO_API_KEY || "";
function requireRecoApiKey(req, res, next) {
if (!RECO_API_KEY) return next();
const headerKey = req.get("x-api-key") || req.get("x-api-key".toUpperCase());
const auth = req.get("authorization") || "";
const bearerKey = auth.toLowerCase().startsWith("bearer ") ? auth.slice(7).trim() : "";
const queryKey = req.query?.apiKey ? String(req.query.apiKey) : "";
const provided = headerKey || bearerKey || queryKey;
if (!provided || provided !== RECO_API_KEY) {
return res.status(401).json({ ok: false, error: "Unauthorized" });
}
return next();
}
logger.info("config", "yt-dlp runtime configuration", {
bin: YT_DLP_BIN,
jsRuntimes: YT_DLP_JS_RUNTIMES,
backendStreamingEnabled: BACKEND_STREAMING_ENABLED,
hasProxy: Boolean(YT_DLP_PROXY),
playerSkip: YT_PLAYER_SKIP,
extractorArgs: YT_EXTRACTOR_ARGS || "",
});
// resolve dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const cachePromise = createCache();
// βββββββββββββββββββββββββββββββββββββββββββββ
// Note: youtubei.js handles URL deciphering natively on Node.js
// βββββββββββββββββββββββββββββββββββββββββββββ
let yt = null;
async function getYT() {
if (!yt) {
logger.info("yt", "Creating Innertube session...");
yt = await Innertube.create({
lang: "en",
location: "IN",
retrieve_player: true,
generate_session_locally: true,
});
logger.info("yt", "YouTube session ready");
}
return yt;
}
// βββββββββββββββββββββββββββββββββββββββββββββ
// basic cors
// βββββββββββββββββββββββββββββββββββββββββββββ
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization, X-API-Key, x-api-key"
);
res.header("Access-Control-Max-Age", "86400");
if (req.method === "OPTIONS") {
return res.sendStatus(204);
}
next();
});
async function requireAuth(req, res, next) {
try {
const token = extractBearerToken(req.get("authorization") || "");
const auth = await verifyAuthToken(token);
if (!auth?.userId) {
return res.status(401).json({ ok: false, error: "Please sign in again." });
}
const user = await getUserById(auth.userId);
if (!user?.id) {
return res.status(401).json({ ok: false, error: "Please sign in again." });
}
req.auth = {
...auth,
user,
};
return next();
} catch (error) {
logger.warn("auth", "Authentication failed", { error: error?.message });
return res.status(401).json({ ok: false, error: "Please sign in again." });
}
}
function getErrorStatus(error, fallback = 500) {
return Number(error?.status) || fallback;
}
function getErrorMessage(error, fallback = "Something went wrong.") {
const status = getErrorStatus(error, 500);
if (status >= 500) return fallback;
return error?.message || fallback;
}
async function buildSessionPayload(session) {
const token = await createAuthToken(session.user);
return {
ok: true,
token,
user: session.user,
library: session.library,
};
}
// βββββββββββββββββββββββββββββββββββββββββββββ
// saavn proxy (placed BEFORE rate limiter so fallback requests aren't throttled)
// βββββββββββββββββββββββββββββββββββββββββββββ
app.use(
"/api/saavn",
createProxyMiddleware({
target: "https://saavn.sumit.co",
changeOrigin: true,
// Express strips the mount path (`/api/saavn`) before proxying,
// so we must prepend `/api` for the upstream Saavn API.
pathRewrite: (path) => `/api${path}`
})
);
// βββββββββββββββββββββββββββββββββββββββββββββ
// rate limiting (basic protection)
// βββββββββββββββββββββββββββββββββββββββββββββ
// Production default: 60 req/min per IP (override via env)
const windowMs = Math.max(1, Number(process.env.RATE_LIMIT_WINDOW_MS || 60 * 1000));
const maxReq = Math.max(1, Number(process.env.RATE_LIMIT_MAX || 60));
app.use(
"/api/",
rateLimit({
windowMs,
max: maxReq,
standardHeaders: true,
legacyHeaders: false,
// If `trust proxy` isn't enabled, a reverse proxy may still add X-Forwarded-For.
// Disable the strict header validation in that case to prevent a hard crash.
validate: {
xForwardedForHeader: !!app.get('trust proxy'),
},
})
);
// request logging (cheap)
app.use((req, res, next) => {
const start = Date.now();
res.on("finish", () => {
const ms = Date.now() - start;
logger.info("http", `${req.method} ${req.originalUrl} ${res.statusCode} ${ms}ms`);
});
next();
});
// βββββββββββββββββββββββββββββββββββββββββββββ
// search songs
// βββββββββββββββββββββββββββββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββββββββββββ
// user tracking + recommendations
// βββββββββββββββββββββββββββββββββββββββββββββ
app.post("/api/auth/signup", async (req, res) => {
try {
const { email, password, name } = req.body || {};
const created = await createUser({ email, password, name });
return res.status(201).json(await buildSessionPayload(created));
} catch (error) {
logger.warn("auth", "Signup failed", { error: error?.message });
return res.status(getErrorStatus(error, 500)).json({
ok: false,
error: getErrorMessage(error, "Unable to create account right now."),
});
}
});
app.post("/api/auth/login", async (req, res) => {
try {
const { email, password } = req.body || {};
const session = await loginUser({ email, password });
return res.json(await buildSessionPayload(session));
} catch (error) {
logger.warn("auth", "Login failed", { error: error?.message });
return res.status(getErrorStatus(error, 500)).json({
ok: false,
error: getErrorMessage(error, "Unable to sign in right now."),
});
}
});
app.post("/api/auth/email/send-otp", async (req, res) => {
try {
const { email, name } = req.body || {};
const result = await sendEmailOtp(email, { name });
return res.json({ ok: true, email: result.email, status: result.status });
} catch (error) {
logger.warn("auth", "Email OTP send failed", { error: error?.message });
return res.status(getErrorStatus(error, 500)).json({
ok: false,
error: getErrorMessage(error, "Email OTP is unavailable right now."),
});
}
});
app.post("/api/auth/email/verify-otp", async (req, res) => {
try {
const { email, code, name } = req.body || {};
const verification = await verifyEmailOtpCode(email, code);
const session = await createOrUpdateEmailUser({
email: verification.email,
name: name || verification.name,
});
return res.json(await buildSessionPayload(session));
} catch (error) {
logger.warn("auth", "Email OTP verify failed", { error: error?.message });
return res.status(getErrorStatus(error, 500)).json({
ok: false,
error: getErrorMessage(error, "Email OTP verification failed."),
});
}
});
app.get("/api/auth/me", requireAuth, async (req, res) => {
return res.json({
ok: true,
user: req.auth.user,
});
});
app.post("/api/auth/change-password", requireAuth, async (req, res) => {
try {
const { currentPassword, newPassword } = req.body || {};
const user = await updateUserPassword({
userId: req.auth.user.id,
currentPassword,
newPassword,
});
return res.json({ ok: true, user });
} catch (error) {
logger.warn("auth", "Password change failed", { error: error?.message, userId: req.auth?.user?.id });
return res.status(getErrorStatus(error, 500)).json({
ok: false,
error: getErrorMessage(error, "Password update failed."),
});
}
});
app.get("/api/library", requireAuth, async (req, res) => {
try {
const library = await getUserLibrary(req.auth.user.id);
return res.json({ ok: true, library });
} catch (error) {
logger.warn("library", "Failed to load user library", { error: error?.message, userId: req.auth?.user?.id });
return res.status(getErrorStatus(error, 500)).json({
ok: false,
error: getErrorMessage(error, "Unable to load your library right now."),
});
}
});
app.put("/api/library", requireAuth, async (req, res) => {
try {
const library = normalizeLibraryPayload(req.body || {});
const saved = await updateUserLibrary(req.auth.user.id, library);
return res.json({ ok: true, library: saved });
} catch (error) {
logger.warn("library", "Failed to update user library", { error: error?.message, userId: req.auth?.user?.id });
return res.status(getErrorStatus(error, 500)).json({
ok: false,
error: getErrorMessage(error, "Unable to save your library right now."),
});
}
});
app.post("/api/feedback/track-issue", async (req, res) => {
try {
const token = extractBearerToken(req.get("authorization") || "");
const auth = token ? await verifyAuthToken(token) : null;
const issue = await recordTrackIssue({
...(req.body || {}),
userId: auth?.userId || req.body?.userId || "",
userEmail: auth?.email || "",
source: "app",
});
return res.status(201).json({ ok: true, issueId: issue.id });
} catch (error) {
logger.warn("feedback", "Track issue report failed", { error: error?.message });
return res.status(getErrorStatus(error, 500)).json({
ok: false,
error: getErrorMessage(error, "Could not send the issue report right now."),
});
}
});
app.post("/api/track", requireRecoApiKey, async (req, res) => {
try {
const { userId, songId, artist, action, song } = req.body || {};
if (!userId || !action) {
return res.status(400).json({ error: "userId and action required" });
}
// Minimal song payload (prefer explicit 'song' from client).
const normalizedSong = song && typeof song === 'object'
? song
: {
id: songId,
artist,
};
await trackUserAction({ userId, song: normalizedSong, action });
res.json({ ok: true });
} catch (err) {
logger.warn("reco", "track endpoint failed", { error: err?.message });
res.status(500).json({ error: "Internal error" });
}
});
app.post("/api/track/play", requireAuth, async (req, res) => {
try {
const userId = req.auth?.user?.id;
if (!userId) {
return res.status(401).json({ ok: false, error: "Unauthorized" });
}
const payloadTrack = req.body?.track && typeof req.body.track === "object" ? req.body.track : null;
const trackId = String(payloadTrack?.id || "").trim();
if (!trackId) {
return res.status(400).json({ ok: false, error: "track.id is required" });
}
const completionRaw = Number(req.body?.completionRatio);
const completionRatio = Number.isFinite(completionRaw)
? Math.max(0, Math.min(1, completionRaw))
: 0;
const features = req.body?.features && typeof req.body.features === "object"
? req.body.features
: (payloadTrack?.features && typeof payloadTrack.features === "object" ? payloadTrack.features : null);
await recordTrackPlay(
userId,
{
id: trackId,
title: String(payloadTrack?.title || "").trim() || "Unknown",
artist: String(payloadTrack?.artist || "").trim() || "Unknown",
features,
},
completionRatio,
features
);
// Ensure next DNA/Twins fetch reflects newly recorded behavior.
await invalidateUserDNA(userId);
return res.json({ ok: true });
} catch (error) {
logger.warn("reco", "track play log failed", {
error: error?.message,
userId: req.auth?.user?.id,
});
return res.status(500).json({
ok: false,
error: "Could not record track play right now.",
});
}
});
app.get("/api/recommendations", requireRecoApiKey, async (req, res) => {
const { userId } = req.query || {};
if (!userId) return res.status(400).json({ error: "userId required" });
try {
const innertube = await getYT();
const cache = await cachePromise;
const data = await getRecommendations({
userId: String(userId),
innertube,
cache,
});
res.json({ ok: true, ...data });
} catch (err) {
logger.warn("reco", "recommendations failed", { userId, error: err?.message });
res.status(500).json({ ok: false, error: "Recommendations unavailable" });
}
});
app.get("/api/yt/search", async (req, res) => {
const { query, limit = 20 } = req.query;
if (!query) return res.json({ results: [] });
try {
const innertube = await getYT();
const searchResults = await innertube.music.search(query, {
type: "song",
});
const songs = searchResults.songs?.contents || [];
const results = songs.slice(0, parseInt(limit)).map((song) => ({
id: song.id,
title: pickText(song.title, song.name) || "Unknown Title",
artist: pickArtistName(song).join(", ") || "Unknown Artist",
artists: pickArtists(song),
album: pickText(song.album?.name, song.album?.text, song.album),
duration: parseDuration(song.duration?.text || song.duration),
durationText: song.duration?.text || "",
thumbnail: pickThumbnailUrl(song),
thumbnails: [
...(Array.isArray(song.thumbnails) ? song.thumbnails : []),
...(Array.isArray(song.thumbnail) ? song.thumbnail : []),
],
}));
res.json({ results });
} catch (err) {
console.error("Search error:", err.message);
res.status(500).json({ results: [] });
}
});
// βββββββββββββββββββββββββββββββββββββββββββββ
// stream endpoint with cache
// βββββββββββββββββββββββββββββββββββββββββββββ
app.get("/api/yt/stream/:videoId", async (req, res) => {
const { videoId } = req.params;
if (!videoId) return res.status(400).json({ error: "videoId required" });
try {
const innertube = await getYT();
const requestedTitle = String(req.query?.title || '').trim();
const requestedArtist = String(req.query?.artist || '').trim();
const findAlternateVideoIds = async ({ seedTitle = '', seedArtist = '', excludeId = '' }) => {
const base = `${seedTitle} ${seedArtist}`.trim();
if (!base) return [];
const queries = [
base,
seedTitle ? `${seedTitle} official audio` : '',
seedArtist ? `${seedArtist} popular songs` : '',
].filter(Boolean);
const ids = new Set();
for (const query of queries) {
try {
const searchResults = await innertube.music.search(query, { type: "song" });
const songs = searchResults?.songs?.contents || [];
for (const item of songs.slice(0, 8)) {
const id = String(item?.id || '').trim();
if (!id || id === excludeId || id.length !== 11) continue;
ids.add(id);
if (ids.size >= 8) return [...ids];
}
} catch {
// ignore one failed query and continue
}
}
return [...ids];
};
let title, author, duration, thumbnail;
try {
const info = await innertube.music.getInfo(videoId);
title = info.basic_info?.title;
author = info.basic_info?.author;
duration = info.basic_info?.duration;
thumbnail = info.basic_info?.thumbnail?.[0]?.url;
} catch {
try {
const info = await innertube.getInfo(videoId);
title = info?.basic_info?.title;
author = info?.basic_info?.author;
duration = info?.basic_info?.duration;
thumbnail = info?.basic_info?.thumbnail?.[0]?.url;
} catch {
// Metadata is optional for stream URL resolution.
}
}
const cache = await cachePromise;
let resolved = null;
let resolvedVideoId = videoId;
try {
resolved = await resolveStreamWithMeta({
innertube,
ytdlpBin: YT_DLP_BIN,
cache,
videoId,
title: requestedTitle || title,
artist: requestedArtist || author,
});
} catch {
resolved = null;
}
if (!resolved?.url) {
const alternates = await findAlternateVideoIds({
seedTitle: requestedTitle || title || '',
seedArtist: requestedArtist || author || '',
excludeId: videoId,
});
for (const altVideoId of alternates) {
try {
const altResolved = await resolveStreamWithMeta({
innertube,
ytdlpBin: YT_DLP_BIN,
cache,
videoId: altVideoId,
title: requestedTitle || title,
artist: requestedArtist || author,
});
if (altResolved?.url) {
resolved = {
...altResolved,
source: `${altResolved.source || 'unknown'}-alt`,
};
resolvedVideoId = altVideoId;
break;
}
} catch {
// continue trying alternates
}
}
}
if (!resolved?.url) {
return res.status(502).json({ error: "Stream unavailable" });
}
const responseData = {
videoId: resolvedVideoId,
title,
author,
duration,
thumbnail,
streamUrl: resolved.url,
cacheState: "remote",
cached: false,
cacheSizeBytes: 0,
streamSource: resolved.source || "unknown",
};
res.json(responseData);
} catch (err) {
logger.error("stream", "Stream error", { videoId, error: err?.message });
res.status(502).json({
videoId,
error: "Stream unavailable",
});
}
});
// βββββββββββββββββββββββββββββββββββββββββββββ
// local disk cache static server
// βββββββββββββββββββββββββββββββββββββββββββββ
app.get("/api/yt/cache/:videoId", (req, res) => {
if (!BACKEND_STREAMING_ENABLED) {
return res.status(410).json({
error: "Backend audio cache serving is disabled. Resolve and stream directly from client sources.",
});
}
const { videoId } = req.params;
const cachedPath = getCachedFilePath(videoId);
if (cachedPath) {
res.setHeader("Accept-Ranges", "bytes");
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
res.sendFile(cachedPath);
} else {
res.status(404).send("Not found in cache");
}
});
app.get("/api/yt/cache-status/:videoId", (req, res) => {
if (!BACKEND_STREAMING_ENABLED) {
return res.json({
videoId: req.params.videoId,
cached: false,
warming: false,
path: null,
disabled: true,
});
}
const { videoId } = req.params;
const status = getCacheStatus(videoId);
res.json({
videoId,
...status,
});
});
app.get("/api/yt/download/:videoId", async (req, res) => {
if (!BACKEND_STREAMING_ENABLED) {
return res.status(410).json({
error: "YouTube download endpoint is disabled. Only direct legal source downloads are allowed on client.",
});
}
const { videoId } = req.params;
if (!videoId) return res.status(400).json({ error: "videoId required" });
let title = `track-${videoId}`;
let author = "Aura Music";
try {
const innertube = await getYT();
const info = await innertube.music.getInfo(videoId);
title = info.basic_info?.title || title;
author = info.basic_info?.author || author;
} catch {
// Metadata is optional for downloads.
}
const cacheStatus = getCacheStatus(videoId);
const cachedPath = cacheStatus.path;
const filenameExt = cacheStatus.ext || '.m4a';
const filename = `${sanitizeFilename(`${author} - ${title}`) || `aura-${videoId}`}${filenameExt}`;
if (cachedPath) {
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
return res.sendFile(cachedPath);
}
try {
const innertube = await getYT();
const cache = await cachePromise;
const streamUrl = await resolveStreamUrl({
innertube,
ytdlpBin: YT_DLP_BIN,
cache,
videoId,
title,
artist: author,
});
downloadToCache(videoId, YT_DLP_BIN);
const upstream = await fetch(streamUrl, {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
},
});
if (!upstream.ok && upstream.status !== 206) {
throw new Error(`Download upstream failed with ${upstream.status}`);
}
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
return pipeUpstream(upstream, res);
} catch (err) {
logger.warn("download", "Direct download stream failed; falling back to yt-dlp pipe", { videoId, error: err?.message });
try {
return await pipeYtdlpToResponse({
req,
res,
videoId,
contentDisposition: `attachment; filename="${filename}"`,
});
} catch (pipeErr) {
logger.error("download", "Download failed", { videoId, error: pipeErr?.message || err?.message });
return res.status(500).json({ error: "Download unavailable" });
}
}
});
// βββββββββββββββββββββββββββββββββββββββββββββ
// suggestions
// βββββββββββββββββββββββββββββββββββββββββββββ
app.get("/api/yt/suggestions", async (req, res) => {
const { query } = req.query;
if (!query) return res.json({ suggestions: [] });
try {
const innertube = await getYT();
const raw = await innertube.music.getSearchSuggestions(query);
const suggestions = [];
for (const section of raw || []) {
for (const item of section.contents || []) {
if (item.type === "SearchSuggestion") {
suggestions.push({
type: "query",
text: item.suggestion?.text || "",
title: item.suggestion?.text || "",
});
} else if (item.type === "MusicResponsiveListItem") {
const title = pickText(item.name, item.title, item.flex_columns?.[0]?.title);
if (!title) continue;
let type = "query";
if (item.item_type === "artist") type = "artist";
else if (item.item_type === "album") type = "album";
else if (item.item_type === "song") type = "song";
const subText = pickText(item.flex_columns?.[1]?.title);
if (type === "query") {
if (/song/i.test(subText)) type = "song";
if (/album/i.test(subText)) type = "album";
if (/artist/i.test(subText)) type = "artist";
if (/video/i.test(subText)) type = "song";
}
const desc = subText || pickText(item.subtitle) || "";
const thumbnail = pickThumbnailUrl(item) || "";
suggestions.push({
type,
text: title,
title,
description: desc,
image: thumbnail,
});
}
}
}
res.json({ suggestions: suggestions.slice(0, 10) });
} catch {
res.json({ suggestions: [] });
}
});
// βββββββββββββββββββββββββββββββββββββββββββββ
// trending songs
// βββββββββββββββββββββββββββββββββββββββββββββ
app.get("/api/yt/trending", async (req, res) => {
try {
const innertube = await getYT();
const home = await innertube.music.getHomeFeed();
const songs = [];
for (const section of home.sections || []) {
for (const item of section.contents || []) {
// Video IDs are exactly 11 characters. PLaylist IDs are longer (PL... or VLPL...)
if (item.id && item.id.length === 11 && item.title) {
songs.push({
id: item.id,
title: pickText(item.title, item.name) || "Unknown Title",
artist: pickArtistName(item).join(", "),
thumbnail: pickThumbnailUrl(item),
});
}
}
}
res.json({ results: songs.slice(0, 20) });
} catch {
res.json({ results: [] });
}
});
// βββββββββββββββββββββββββββββββββββββββββββββ
// lyrics api
// βββββββββββββββββββββββββββββββββββββββββββββ
app.get("/api/yt/lyrics", async (req, res) => {
const { artist, title } = req.query;
if (!artist || !title) return res.json({ lyrics: "" });
try {
const r = await fetch(
`https://api.lyrics.ovh/v1/${artist}/${title}`
);
const data = await r.json();
res.json(data);
} catch {
res.json({ lyrics: "" });
}
});
app.get("/api/lyrics", async (req, res) => {
const { artist, title, album, duration } = req.query;
if (!artist || !title) {
return res.json({ ok: true, plainLyrics: "", syncedLyrics: "", source: "none" });
}
const params = new URLSearchParams({
artist_name: String(artist),
track_name: String(title),
});
if (album) params.set("album_name", String(album));
if (duration && Number.isFinite(Number(duration))) {
params.set("duration", String(Math.round(Number(duration))));
}
try {
const lrclibResp = await fetch(`https://lrclib.net/api/get?${params.toString()}`, {
headers: {
"User-Agent": HTTP_UA,
"Accept": "application/json",
},
});
if (lrclibResp.ok) {
const data = await lrclibResp.json();
if ((!data?.syncedLyrics || !String(data.syncedLyrics).trim()) && data?.plainLyrics) {
// Try searching for an alternate match that has synced lines.
const searchResp = await fetch(`https://lrclib.net/api/search?${params.toString()}`, {
headers: {
"User-Agent": HTTP_UA,
"Accept": "application/json",
},
});
if (searchResp.ok) {
const searchResults = await searchResp.json();
const syncedCandidate = Array.isArray(searchResults)
? searchResults.find((item) => String(item?.syncedLyrics || '').trim())
: null;
if (syncedCandidate) {
return res.json({
ok: true,
plainLyrics: syncedCandidate?.plainLyrics || data?.plainLyrics || "",
syncedLyrics: syncedCandidate?.syncedLyrics || "",
source: "lrclib",
});
}
}
}
return res.json({
ok: true,
plainLyrics: data?.plainLyrics || "",
syncedLyrics: data?.syncedLyrics || "",
source: "lrclib",
});
}
if (lrclibResp.status === 404) {
const searchResp = await fetch(`https://lrclib.net/api/search?${params.toString()}`, {
headers: {
"User-Agent": HTTP_UA,
"Accept": "application/json",
},
});
if (searchResp.ok) {
const results = await searchResp.json();
const match = Array.isArray(results)
? (results.find((item) => String(item?.syncedLyrics || '').trim()) || results[0])