-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
1104 lines (986 loc) · 34.2 KB
/
server.js
File metadata and controls
1104 lines (986 loc) · 34.2 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
// Custom server for Next.js with WebSocket support
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const { Server } = require("socket.io");
const fetch = require("node-fetch");
// Simple rating generator for server-side use
function generateRandomRating() {
const grades = [
"A+",
"A",
"A-",
"B+",
"B",
"B-",
"C+",
"C",
"C-",
"D+",
"D",
"F",
];
const weights = [5, 15, 20, 25, 20, 10, 3, 1, 0.5, 0.3, 0.1, 0.1];
const messages = {
"A+": [
"Absolutely phenomenal!",
"Perfect performance!",
"Outstanding!",
"Flawless execution!",
"Simply amazing!",
],
A: [
"Fantastic job!",
"Excellent performance!",
"Superb singing!",
"Really impressive!",
"Great work!",
],
"A-": [
"Very well done!",
"Nice performance!",
"Really good!",
"Well executed!",
"Solid performance!",
],
"B+": [
"Good job!",
"Nice work!",
"Well done!",
"Pretty good!",
"Good effort!",
],
B: [
"Not bad!",
"Decent performance!",
"Good try!",
"Nice attempt!",
"Keep it up!",
],
"B-": [
"Good effort!",
"Nice try!",
"Keep practicing!",
"Getting there!",
"Room for improvement!",
],
"C+": [
"Keep trying!",
"Practice makes perfect!",
"You'll get it!",
"Don't give up!",
"Keep working at it!",
],
C: [
"Keep practicing!",
"You're learning!",
"Don't stop trying!",
"Every performance counts!",
"Keep going!",
],
"C-": [
"Practice more!",
"You can do better!",
"Keep at it!",
"Don't give up!",
"Try again!",
],
"D+": [
"Keep trying!",
"Practice helps!",
"Don't quit!",
"You'll improve!",
"Keep going!",
],
D: [
"Keep practicing!",
"Don't give up!",
"Try again!",
"You can improve!",
"Keep at it!",
],
F: [
"Keep trying!",
"Practice makes perfect!",
"Don't give up!",
"You'll get better!",
"Keep singing!",
],
};
const gradeToScore = {
"A+": [95, 100],
A: [90, 94],
"A-": [85, 89],
"B+": [80, 84],
B: [75, 79],
"B-": [70, 74],
"C+": [65, 69],
C: [60, 64],
"C-": [55, 59],
"D+": [50, 54],
D: [45, 49],
F: [0, 44],
};
// Weighted random selection
const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
let random = Math.random() * totalWeight;
let selectedGrade = "B";
for (let i = 0; i < grades.length; i++) {
random -= weights[i];
if (random <= 0) {
selectedGrade = grades[i];
break;
}
}
const [minScore, maxScore] = gradeToScore[selectedGrade];
const score =
Math.floor(Math.random() * (maxScore - minScore + 1)) + minScore;
const gradeMessages = messages[selectedGrade];
const message =
gradeMessages[Math.floor(Math.random() * gradeMessages.length)];
return { grade: selectedGrade, score, message };
}
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = process.env.PORT || 3000;
// When using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = createServer(async (req, res) => {
try {
// Handle debug endpoint before Next.js
if (req.url === "/debug/websocket-state" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
// Get unique users by name for display
const uniqueUsers = currentSession
? currentSession.connectedUsers.reduce((acc, user) => {
if (!acc.find(u => u.name === user.name)) {
acc.push({
name: user.name,
isHost: user.isHost,
connectedAt: user.connectedAt,
lastSeen: user.lastSeen,
socketId: user.socketId,
});
}
return acc;
}, [])
: [];
res.end(
JSON.stringify(
{
currentSession: currentSession
? {
id: currentSession.id,
name: currentSession.name,
queueLength: currentSession.queue?.length || 0,
currentSong: currentSession.currentSong
? {
title: currentSession.currentSong.mediaItem.title,
status: currentSession.currentSong.status,
}
: null,
connectedUsers: currentSession.connectedUsers?.length || 0,
uniqueUsers: uniqueUsers,
uniqueUserCount: uniqueUsers.length,
queue:
currentSession.queue?.map(item => ({
title: item.mediaItem.title,
artist: item.mediaItem.artist,
status: item.status,
addedBy: item.addedBy,
})) || [],
}
: null,
connectedUsersMapSize: connectedUsers.size,
duplicateDetection: {
totalConnections: currentSession?.connectedUsers?.length || 0,
uniqueUsers: uniqueUsers.length,
duplicatesRemoved:
(currentSession?.connectedUsers?.length || 0) -
uniqueUsers.length,
},
},
null,
2
)
);
return;
}
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true);
await handle(req, res, parsedUrl);
} catch (err) {
console.error("Error occurred handling", req.url, err);
res.statusCode = 500;
res.end("internal server error");
}
});
// Initialize Socket.IO server
const io = new Server(server, {
cors: {
origin: dev ? ["http://localhost:3000", "http://localhost:3003"] : false,
methods: ["GET", "POST"],
},
});
// Store for session management (simplified for server.js)
let sessionManager = null;
let currentSession = null;
const connectedUsers = new Map();
// Periodic cleanup of stale connections
const cleanupStaleConnections = () => {
if (!currentSession) return;
const now = new Date();
const staleThreshold = 5 * 60 * 1000; // 5 minutes
const initialCount = currentSession.connectedUsers.length;
// Remove users who haven't been seen in a while
currentSession.connectedUsers = currentSession.connectedUsers.filter(
user => {
const timeSinceLastSeen = now - new Date(user.lastSeen);
const isStale = timeSinceLastSeen > staleThreshold;
if (isStale) {
console.log(
`Removing stale user: ${user.name} (last seen ${Math.round(timeSinceLastSeen / 1000)}s ago)`
);
// Also remove from connectedUsers map
connectedUsers.delete(user.socketId);
}
return !isStale;
}
);
const removedCount = initialCount - currentSession.connectedUsers.length;
if (removedCount > 0) {
console.log(
`Cleaned up ${removedCount} stale connections. Active users: ${currentSession.connectedUsers.length}`
);
}
};
// Run cleanup every 2 minutes
setInterval(cleanupStaleConnections, 2 * 60 * 1000);
// Basic WebSocket connection handling with session management
io.on("connection", socket => {
console.log("Client connected:", socket.id);
let currentUserId = null;
let currentSessionId = null;
// Auto-join for TV display
if (socket.handshake.query && socket.handshake.query.client === "tv") {
const userId = `tv_${Date.now()}`;
const userName = "TV Display";
currentUserId = userId;
currentSessionId = "main-session";
console.log(`Auto-joining TV client ${userId} to main-session`);
// Create session if it doesn't exist
if (!currentSession) {
currentSession = {
id: "main-session",
name: "Karaoke Session",
queue: [],
currentSong: null,
connectedUsers: [],
createdAt: new Date(),
};
}
// DEDUPLICATION: Remove any existing TV Display users
const existingTvIndex = currentSession.connectedUsers.findIndex(
u => u.name === userName
);
if (existingTvIndex !== -1) {
const existingTv = currentSession.connectedUsers[existingTvIndex];
console.log(
`Removing duplicate TV Display (old socket: ${existingTv.socketId})`
);
// Remove from both session and connectedUsers map
currentSession.connectedUsers.splice(existingTvIndex, 1);
// Find and remove old socket from connectedUsers map
for (const [socketId, user] of connectedUsers.entries()) {
if (user.name === userName) {
connectedUsers.delete(socketId);
console.log(`Cleaned up old TV socket mapping: ${socketId}`);
break;
}
}
}
// Add TV user to session
const user = {
id: userId,
name: userName,
socketId: socket.id,
isHost: true,
connectedAt: new Date(),
lastSeen: new Date(),
};
currentSession.connectedUsers.push(user);
connectedUsers.set(socket.id, user);
// Join the session room
socket.join("main-session");
// Notify client
socket.emit("session-joined", {
session: currentSession,
userId: userId,
queue: currentSession.queue,
currentSong: currentSession.currentSong,
playbackState: {
isPlaying: false,
currentTime: 0,
volume: 80,
isMuted: false,
lyricsOffset: 0,
},
});
console.log("TV client auto-joined to main-session (deduplicated)");
}
socket.on("join-session", data => {
console.log("Client joining session:", data);
const { sessionId, userName } = data;
console.log("Joining socket to room:", sessionId);
socket.join(sessionId);
console.log("Socket rooms after join:", Array.from(socket.rooms));
// Create or join session
if (!currentSession) {
console.log("Creating new session:", sessionId);
currentSession = {
id: sessionId,
name: "Karaoke Session",
queue: [],
currentSong: null,
connectedUsers: [],
createdAt: new Date(),
};
} else {
console.log("Joining existing session:", currentSession.id);
}
// DEDUPLICATION: Remove any existing users with the same name
const existingUserIndex = currentSession.connectedUsers.findIndex(
u => u.name === userName
);
if (existingUserIndex !== -1) {
const existingUser = currentSession.connectedUsers[existingUserIndex];
console.log(
`Removing duplicate user: ${userName} (old socket: ${existingUser.socketId})`
);
// Remove from both session and connectedUsers map
currentSession.connectedUsers.splice(existingUserIndex, 1);
// Find and remove old socket from connectedUsers map
for (const [socketId, user] of connectedUsers.entries()) {
if (user.name === userName) {
connectedUsers.delete(socketId);
console.log(
`Cleaned up old socket mapping for ${userName}: ${socketId}`
);
break;
}
}
}
// Add user to session
const user = {
id: `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
name: userName,
socketId: socket.id,
isHost: currentSession.connectedUsers.length === 0,
connectedAt: new Date(),
lastSeen: new Date(),
};
currentSession.connectedUsers.push(user);
connectedUsers.set(socket.id, user);
currentUserId = user.id;
console.log(
"Session now has",
currentSession.connectedUsers.length,
"users (deduplicated)"
);
// Send session state to client
socket.emit("session-updated", {
session: currentSession,
queue: currentSession.queue,
currentSong: currentSession.currentSong,
playbackState: {
isPlaying: false,
currentTime: 0,
volume: 80,
isMuted: false,
lyricsOffset: 0,
},
});
// Notify other clients
console.log("Notifying other clients in room:", sessionId);
socket.to(sessionId).emit("user-joined", user);
console.log(
`User ${userName} joined session ${sessionId} (deduplicated)`
);
});
socket.on("add-song", async data => {
console.log("Adding song:", data);
// Get the user for this socket
const user = connectedUsers.get(socket.id);
if (!user) {
console.log("ERROR: No user found for socket");
socket.emit("error", {
code: "NOT_IN_SESSION",
message: "You must join a session first",
});
return;
}
// Use the global session (there should only be one)
if (!currentSession) {
console.log("ERROR: No current session");
socket.emit("error", {
code: "NOT_IN_SESSION",
message: "No active session",
});
return;
}
console.log("Current session exists:", !!currentSession);
console.log("Current user ID:", user.id);
console.log("Session ID:", currentSession.id);
console.log(
"Connected users in session:",
currentSession.connectedUsers?.length
);
const { mediaItem, position } = data;
const queueItem = {
id: `queue_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
mediaItem,
addedBy: user.name, // Use user.name instead of user.id
addedByUserId: user.id, // Keep user ID for reference if needed
addedAt: new Date(),
position: position ?? currentSession.queue.length,
status: "pending",
};
if (position !== undefined) {
currentSession.queue.splice(position, 0, queueItem);
} else {
currentSession.queue.push(queueItem);
}
// Update positions
currentSession.queue.forEach((item, index) => {
item.position = index;
});
// Check if this is the first song added to an empty queue and no song is currently playing
const wasQueueEmpty = currentSession.queue.length === 1;
const noCurrentSong = !currentSession.currentSong;
if (wasQueueEmpty && noCurrentSong) {
console.log("First song added to empty queue, auto-starting playback");
// Mark the song as playing
queueItem.status = "playing";
currentSession.currentSong = queueItem;
// Initialize or update playback state
if (!currentSession.playbackState) {
currentSession.playbackState = {
isPlaying: true,
currentTime: 0,
volume: 80,
isMuted: false,
playbackRate: 1.0,
lyricsOffset: 0,
};
} else {
currentSession.playbackState.isPlaying = true;
currentSession.playbackState.currentTime = 0;
}
// Broadcast song started immediately
const sessionId = currentSession.id || "main-session";
io.to(sessionId).emit("song-started", queueItem);
io.to(sessionId).emit(
"playback-state-changed",
currentSession.playbackState
);
console.log("Auto-started song:", queueItem.mediaItem.title);
}
// SYNC WITH SESSION MANAGER: Also add to the API session manager
try {
const response = await fetch("http://localhost:3000/api/queue", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "add-song",
mediaItem: mediaItem,
userId: user.id,
userName: user.name,
position: position,
}),
});
if (!response.ok) {
console.log(
"Failed to sync with session manager, creating session..."
);
// Try to create session first
await fetch("http://localhost:3000/api/queue", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "create-session",
userName: user.name,
}),
});
// Then try adding the song again
await fetch("http://localhost:3000/api/queue", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "add-song",
mediaItem: mediaItem,
userId: user.id,
userName: user.name,
position: position,
}),
});
}
console.log("Successfully synced with session manager");
} catch (error) {
console.log("Failed to sync with session manager:", error.message);
}
console.log("Broadcasting queue update to session:", currentSession.id);
console.log("Queue length:", currentSession.queue.length);
console.log("Rooms for this socket:", Array.from(socket.rooms));
// Broadcast queue update to ALL clients in the session room
console.log("Broadcasting to room:", currentSession.id);
io.to(currentSession.id).emit("queue-updated", currentSession.queue);
// Also broadcast to main-session room as backup
io.to("main-session").emit("queue-updated", currentSession.queue);
console.log("Song added to queue and broadcast sent");
});
socket.on("remove-song", data => {
console.log("Removing song:", data);
if (!currentSession || !currentUserId) {
socket.emit("error", {
code: "NOT_IN_SESSION",
message: "You must join a session first",
});
return;
}
const { queueItemId } = data;
const itemIndex = currentSession.queue.findIndex(
item => item.id === queueItemId
);
if (itemIndex === -1) {
socket.emit("error", {
code: "SONG_NOT_FOUND",
message: "Song not found in queue",
});
return;
}
const item = currentSession.queue[itemIndex];
const user = connectedUsers.get(socket.id);
// Check permissions
// if (item.addedBy !== currentUserId && !user?.isHost) {
// socket.emit('error', { code: 'UNAUTHORIZED', message: 'You can only remove your own songs' })
// return
// }
currentSession.queue.splice(itemIndex, 1);
// Update positions
currentSession.queue.forEach((item, index) => {
item.position = index;
});
// Broadcast queue update
io.to(currentSession.id).emit("queue-updated", currentSession.queue);
console.log("Song removed from queue");
});
socket.on("playback-control", command => {
console.log("Playback control:", command);
// Get the user for this socket
const user = connectedUsers.get(socket.id);
console.log("Current user:", user?.name || "Unknown");
console.log("Current session exists:", !!currentSession);
// Allow TV clients or users in session
if (!user && !currentSession) {
console.log("No user and no session, must join session first");
socket.emit("error", {
code: "NOT_IN_SESSION",
message: "You must join a session first",
});
return;
}
if (!currentSession) {
console.log("No current session");
socket.emit("error", {
code: "NOT_IN_SESSION",
message: "No active session",
});
return;
}
try {
switch (command.action) {
case "play":
console.log("Processing play command");
if (!currentSession.currentSong) {
console.log("No current song, starting next song from queue");
// Find next pending song
const nextSong = currentSession.queue.find(
item => item.status === "pending"
);
if (nextSong) {
console.log("Found next song:", nextSong.mediaItem.title);
// Mark song as playing
nextSong.status = "playing";
currentSession.currentSong = nextSong;
// Initialize playback state for new song
if (!currentSession.playbackState) {
currentSession.playbackState = {
isPlaying: true,
currentTime: 0,
volume: 80,
isMuted: false,
playbackRate: 1.0,
lyricsOffset: 0,
};
} else {
currentSession.playbackState.isPlaying = true;
currentSession.playbackState.currentTime = 0; // Only reset time for new songs
}
// Broadcast song started
const sessionId = currentSession.id || "main-session";
io.to(sessionId).emit("song-started", nextSong);
io.to(sessionId).emit("queue-updated", currentSession.queue);
io.to(sessionId).emit(
"playback-state-changed",
currentSession.playbackState
);
console.log("Song started successfully");
} else {
console.log("No pending songs in queue");
}
} else {
console.log("Resuming current song");
// Just resume playback - don't change currentTime
if (!currentSession.playbackState) {
currentSession.playbackState = {
isPlaying: true,
currentTime: 0,
volume: 80,
isMuted: false,
playbackRate: 1.0,
lyricsOffset: 0,
};
} else {
currentSession.playbackState.isPlaying = true;
// Keep existing currentTime - don't reset it
}
const sessionId = currentSession.id || "main-session";
io.to(sessionId).emit(
"playback-state-changed",
currentSession.playbackState
);
}
break;
case "pause":
console.log("Processing pause command");
if (!currentSession.playbackState) {
currentSession.playbackState = {
isPlaying: false,
currentTime: 0,
volume: 80,
isMuted: false,
playbackRate: 1.0,
lyricsOffset: 0,
};
} else {
currentSession.playbackState.isPlaying = false;
// Keep existing currentTime - don't reset it
}
const sessionId = currentSession.id || "main-session";
io.to(sessionId).emit(
"playback-state-changed",
currentSession.playbackState
);
break;
case "volume":
if (command.value !== undefined) {
if (!currentSession.playbackState) {
currentSession.playbackState = {
isPlaying: currentSession.currentSong ? true : false,
currentTime: 0,
volume: command.value,
isMuted: false,
playbackRate: 1.0,
lyricsOffset: 0,
};
} else {
currentSession.playbackState.volume = command.value;
// Keep existing currentTime and other properties
}
const sessionId = currentSession.id || "main-session";
io.to(sessionId).emit(
"playback-state-changed",
currentSession.playbackState
);
}
break;
case "seek":
if (command.value !== undefined) {
if (!currentSession.playbackState) {
currentSession.playbackState = {
isPlaying: currentSession.currentSong ? true : false,
currentTime: command.value,
volume: 80,
isMuted: false,
playbackRate: 1.0,
lyricsOffset: 0,
};
} else {
currentSession.playbackState.currentTime = command.value;
// Keep existing other properties
}
const sessionId = currentSession.id || "main-session";
io.to(sessionId).emit(
"playback-state-changed",
currentSession.playbackState
);
}
break;
case "mute":
if (!currentSession.playbackState) {
currentSession.playbackState = {
isPlaying: currentSession.currentSong ? true : false,
currentTime: 0,
volume: 80,
isMuted: true,
playbackRate: 1.0,
lyricsOffset: 0,
};
} else {
currentSession.playbackState.isMuted = true;
// Keep existing currentTime and other properties
}
const sessionId2 = currentSession.id || "main-session";
io.to(sessionId2).emit(
"playback-state-changed",
currentSession.playbackState
);
break;
case "time-update":
// Update the server's tracking of current playback time
if (command.value !== undefined && currentSession.playbackState) {
currentSession.playbackState.currentTime = command.value;
// Don't broadcast time updates - they're just for server tracking
}
break;
case "lyrics-offset":
console.log("Processing lyrics-offset command:", command.value);
if (command.value !== undefined) {
if (!currentSession.playbackState) {
currentSession.playbackState = {
isPlaying: currentSession.currentSong ? true : false,
currentTime: 0,
volume: 80,
isMuted: false,
playbackRate: 1.0,
lyricsOffset: command.value,
};
} else {
currentSession.playbackState.lyricsOffset = command.value;
// Keep existing currentTime and other properties
}
const sessionId = currentSession.id || "main-session";
io.to(sessionId).emit(
"playback-state-changed",
currentSession.playbackState
);
console.log("Lyrics offset updated to:", command.value);
}
break;
default:
console.log("Unknown playback action:", command.action);
}
} catch (error) {
console.error("Error handling playback control:", error);
socket.emit("error", {
code: "PLAYBACK_ERROR",
message: "Failed to control playback",
});
}
});
socket.on("skip-song", () => {
console.log("Skipping song");
if (!currentSession || !currentSession.currentSong) {
socket.emit("error", {
code: "NO_CURRENT_SONG",
message: "No song currently playing",
});
return;
}
// Mark current song as skipped and move to next
const skippedSong = currentSession.currentSong;
skippedSong.status = "skipped";
// Remove skipped song from queue immediately
currentSession.queue = currentSession.queue.filter(
item => item.status !== "completed" && item.status !== "skipped"
);
// Update positions for remaining songs
currentSession.queue = currentSession.queue.map((item, index) => ({
...item,
position: index,
}));
currentSession.currentSong = null;
// Reset playback state for the next song
if (currentSession.playbackState) {
currentSession.playbackState.currentTime = 0;
currentSession.playbackState.isPlaying = false;
} else {
currentSession.playbackState = {
isPlaying: false,
currentTime: 0,
volume: 80,
isMuted: false,
playbackRate: 1.0,
lyricsOffset: 0,
};
}
// Broadcast song ended
const sessionId = currentSession.id || "main-session";
io.to(sessionId).emit("song-ended", skippedSong);
// Start next song if available
const nextSong = currentSession.queue.find(
item => item.status === "pending"
);
if (nextSong) {
nextSong.status = "playing";
currentSession.currentSong = nextSong;
// Ensure playback state is ready for new song
currentSession.playbackState.isPlaying = true;
currentSession.playbackState.currentTime = 0; // Explicitly reset to 0
io.to(sessionId).emit("song-started", nextSong);
io.to(sessionId).emit("queue-updated", currentSession.queue);
io.to(sessionId).emit(
"playback-state-changed",
currentSession.playbackState
);
}
});
socket.on("song-ended", () => {
console.log("Song ended naturally");
if (!currentSession || !currentSession.currentSong) {
console.log("No current song to end");
return;
}
// Mark current song as completed and move to next
const completedSong = currentSession.currentSong;
completedSong.status = "completed";
// Remove completed song from queue immediately
currentSession.queue = currentSession.queue.filter(
item => item.status !== "completed" && item.status !== "skipped"
);
// Update positions for remaining songs
currentSession.queue = currentSession.queue.map((item, index) => ({
...item,
position: index,
}));
// Generate rating for the completed song
const rating = generateRandomRating();
console.log(
`Generated rating for "${completedSong.mediaItem.title}": ${rating.grade} (${rating.score}/100)`
);
currentSession.currentSong = null;
// Reset playback state for the next song
if (currentSession.playbackState) {
currentSession.playbackState.currentTime = 0;
currentSession.playbackState.isPlaying = false;
} else {
currentSession.playbackState = {
isPlaying: false,
currentTime: 0,
volume: 80,
isMuted: false,
playbackRate: 1.0,
lyricsOffset: 0,
};
}
// Find next song but don't start it immediately - let the client handle transitions
const nextSong = currentSession.queue.find(
item => item.status === "pending"
);
// Broadcast song ended with rating data for transitions
const sessionId = currentSession.id || "main-session";