-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayerManager.ts
More file actions
1091 lines (922 loc) Β· 34.1 KB
/
Copy pathPlayerManager.ts
File metadata and controls
1091 lines (922 loc) Β· 34.1 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
/**
* Player Manager - Handles YouTube player operations and synchronization
* Part of Phase 2: Service Layer Extraction
*/
import { SessionStore } from '../state/SessionStore.js';
import { VideoInfo, HeartbeatData, StateChangeEvent } from '../state/StateTypes.js';
import { logger } from '../lib/logger.js';
export interface YouTubeDJMessage {
type: string;
userId: string;
timestamp: number;
data?: any;
}
export class PlayerManager {
private store: SessionStore;
private heartbeatInterval: number | null = null;
constructor(store: SessionStore) {
this.store = store;
// Listen to state changes for player management
Hooks.on('youtubeDJ.stateChanged', this.onStateChanged.bind(this));
// Listen for video load requests from QueueManager
Hooks.on('youtubeDJ.loadVideo', this.onLoadVideoRequest.bind(this));
// Listen for playlist load requests from QueueManager
Hooks.on('youtubeDJ.loadPlaylist', this.onLoadPlaylistRequest.bind(this));
// Listen for video cue requests (load without auto-play)
Hooks.on('youtubeDJ.cueVideo', this.onCueVideoRequest.bind(this));
// Listen for heartbeat synchronization
Hooks.on('youtubeDJ.heartbeat', this.onHeartbeatReceived.bind(this));
// Listen for player commands from other users
Hooks.on('youtubeDJ.playCommand', this.onPlayCommand.bind(this));
Hooks.on('youtubeDJ.pauseCommand', this.onPauseCommand.bind(this));
Hooks.on('youtubeDJ.seekCommand', this.onSeekCommand.bind(this));
Hooks.on('youtubeDJ.loadCommand', this.onLoadCommand.bind(this));
Hooks.on('youtubeDJ.loadPlaylistCommand', this.onLoadPlaylistCommand.bind(this));
}
// Legacy initializePlayer removed - widget handles player initialization
// Legacy destroyPlayer removed - widget handles player lifecycle
/**
* Play current video
*/
async play(): Promise<void> {
if (!this.store.isDJ()) {
throw new Error('Only DJ can control playback');
}
// PRIORITY 1: Check if there are queued videos to play
const queueState = this.store.getQueueState();
const hasQueuedVideo = queueState.items.length > 0 &&
queueState.currentIndex >= 0 &&
queueState.currentIndex < queueState.items.length;
if (hasQueuedVideo) {
const currentQueueItem = queueState.items[queueState.currentIndex];
const playerState = this.store.getPlayerState();
// Check if the current queue item is a playlist
if (currentQueueItem.isPlaylist && currentQueueItem.playlistId) {
// Check if playlist is already loaded
const currentlyLoadedVideo = playerState.currentVideo?.videoId;
const expectedPlaylistId = `playlist:${currentQueueItem.playlistId}`;
if (currentlyLoadedVideo === expectedPlaylistId) {
// Playlist is already loaded, just play it
logger.debug('π΅ YouTube DJ | Playlist already loaded, sending play command');
Hooks.callAll('youtubeDJ.playerCommand', { command: 'playVideo' });
// Update state to playing
this.store.updateState({
player: {
...playerState,
playbackState: 'playing'
}
});
// Broadcast play command
this.broadcastMessage({
type: 'PLAY',
userId: game.user?.id || '',
timestamp: Date.now()
});
return;
} else {
// Need to load the playlist first
logger.debug('π΅ YouTube DJ | Playing playlist from queue:', currentQueueItem.playlistId);
await this.loadPlaylist(currentQueueItem.playlistId, true);
return; // loadPlaylist will handle playing
}
}
logger.debug('π΅ YouTube DJ | Queue has videos, checking if correct video is loaded:', {
queueVideoId: currentQueueItem.videoId,
playerVideoId: playerState.currentVideo?.videoId,
queueTitle: currentQueueItem.title
});
// Check if the player has the correct video loaded
if (playerState.currentVideo?.videoId !== currentQueueItem.videoId) {
logger.debug('π΅ YouTube DJ | Loading correct video from queue:', currentQueueItem.title);
await this.loadVideo(currentQueueItem.videoId);
return; // loadVideo will handle playing
}
// Correct video is already loaded, proceed to play it
logger.debug('π΅ YouTube DJ | Playing current queue video:', currentQueueItem.title);
} else {
// PRIORITY 2: No queue items - check if there's a fallback video loaded
const playerState = this.store.getPlayerState();
const hasValidVideo = playerState.currentVideo?.videoId &&
playerState.currentVideo.videoId.length === 11;
if (!hasValidVideo) {
throw new Error('No video loaded. Please add videos to the queue first.');
}
logger.debug('π΅ YouTube DJ | No queue items, playing loaded video:', {
videoId: playerState.currentVideo.videoId,
title: playerState.currentVideo.title
});
}
try {
// Send command to widget player
Hooks.callAll('youtubeDJ.playerCommand', { command: 'playVideo' });
this.store.updateState({
player: {
...this.store.getPlayerState(),
playbackState: 'playing'
}
});
// Start heartbeat for synchronization
this.startHeartbeat();
// Broadcast play command
const playMessage = {
type: 'PLAY',
userId: game.user?.id || '',
timestamp: Date.now()
};
logger.debug('π΅ YouTube DJ | Broadcasting PLAY message:', playMessage);
this.broadcastMessage(playMessage);
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to play video:', error);
throw error;
}
}
/**
* Pause current video
*/
async pause(): Promise<void> {
if (!this.store.isDJ()) {
throw new Error('Only DJ can control playback');
}
logger.debug('π΅ YouTube DJ | Pausing video...');
try {
// Send command to widget player
Hooks.callAll('youtubeDJ.playerCommand', { command: 'pauseVideo' });
this.store.updateState({
player: {
...this.store.getPlayerState(),
playbackState: 'paused'
}
});
// Stop heartbeat when paused
this.stopHeartbeat();
// Broadcast pause command
this.broadcastMessage({
type: 'PAUSE',
userId: game.user?.id || '',
timestamp: Date.now()
});
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to pause video:', error);
throw error;
}
}
/**
* Seek to specific time
*/
async seekTo(time: number): Promise<void> {
if (!this.store.isDJ()) {
throw new Error('Only DJ can control playback');
}
logger.debug('π΅ YouTube DJ | Seeking to time:', time);
try {
// Send command to widget player
Hooks.callAll('youtubeDJ.playerCommand', { command: 'seekTo', args: [time, true] });
this.store.updateState({
player: {
...this.store.getPlayerState(),
currentTime: time
}
});
// Broadcast seek command
this.broadcastMessage({
type: 'SEEK',
userId: game.user?.id || '',
timestamp: Date.now(),
data: { time }
});
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to seek:', error);
throw error;
}
}
/**
* Load and play video
* @param autoPlay - Whether to auto-play after loading (default true)
*/
async loadVideo(videoId: string, startTime: number = 0, autoPlay: boolean = true): Promise<void> {
if (!this.store.isDJ()) {
throw new Error('Only DJ can load videos');
}
logger.debug('π΅ YouTube DJ | Loading video:', videoId);
try {
// Get video info
const videoInfo = await this.getVideoInfo(videoId);
this.store.updateState({
player: {
...this.store.getPlayerState(),
currentVideo: videoInfo,
playbackState: 'loading'
}
});
// Send command to widget player
if (autoPlay) {
Hooks.callAll('youtubeDJ.playerCommand', { command: 'loadVideoById', args: [videoId, startTime] });
} else {
Hooks.callAll('youtubeDJ.playerCommand', { command: 'cueVideoById', args: [videoId, startTime] });
}
// Broadcast load command with autoPlay flag
this.broadcastMessage({
type: 'LOAD',
userId: game.user?.id || '',
timestamp: Date.now(),
data: { videoId, startTime, videoInfo, autoPlay }
});
logger.info('π΅ YouTube DJ | Video loaded successfully:', videoInfo.title);
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to load video:', error);
throw error;
}
}
/**
* Load a playlist
* @param playlistId - The YouTube playlist ID
* @param autoPlay - Whether to auto-play after loading (default true)
*/
async loadPlaylist(playlistId: string, autoPlay: boolean = true): Promise<void> {
if (!this.store.isDJ()) {
throw new Error('Only DJ can load playlists');
}
logger.debug('π΅ YouTube DJ | Loading playlist:', playlistId);
try {
this.store.updateState({
player: {
...this.store.getPlayerState(),
currentVideo: {
videoId: `playlist:${playlistId}`,
title: 'π΅ YouTube Playlist',
duration: 0
},
playbackState: 'loading'
}
});
// Send command to widget player
if (autoPlay) {
logger.debug('π΅ YouTube DJ | Loading playlist with autoplay');
Hooks.callAll('youtubeDJ.playerCommand', {
command: 'loadPlaylist',
args: [{
list: playlistId,
listType: 'playlist',
index: 0
}]
});
} else {
Hooks.callAll('youtubeDJ.playerCommand', {
command: 'cuePlaylist',
args: [{
list: playlistId,
listType: 'playlist',
index: 0
}]
});
}
// Broadcast playlist load command
this.broadcastMessage({
type: 'LOAD_PLAYLIST',
userId: game.user?.id || '',
timestamp: Date.now(),
data: { playlistId, autoPlay }
});
// Start heartbeat if autoPlay is true
if (autoPlay) {
logger.debug('π΅ YouTube DJ | Starting heartbeat for playlist playback');
this.startHeartbeat();
}
logger.info('π΅ YouTube DJ | Playlist loaded successfully:', playlistId);
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to load playlist:', error);
throw error;
}
}
/**
* Mute the player
*/
async mute(): Promise<void> {
if (!this.store.getPlayerState().isReady) {
throw new Error('Player not ready');
}
try {
// Send command only to local player (not to all users)
Hooks.callAll('youtubeDJ.localPlayerCommand', { command: 'mute' });
// Store mute preference in client settings (per-user)
await game.settings.set('bardic-inspiration', 'youtubeDJ.userMuted', true);
logger.debug('π΅ YouTube DJ | Player muted (local only)');
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to mute:', error);
throw error;
}
}
/**
* Unmute the player
*/
async unmute(): Promise<void> {
if (!this.store.getPlayerState().isReady) {
throw new Error('Player not ready');
}
try {
// Send command only to local player (not to all users)
Hooks.callAll('youtubeDJ.localPlayerCommand', { command: 'unMute' });
// Store mute preference in client settings (per-user)
await game.settings.set('bardic-inspiration', 'youtubeDJ.userMuted', false);
logger.debug('π΅ YouTube DJ | Player unmuted (local only)');
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to unmute:', error);
throw error;
}
}
/**
* Toggle mute state
*/
async toggleMute(): Promise<void> {
// Get mute state from client settings instead of global state
const currentlyMuted = game.settings.get('bardic-inspiration', 'youtubeDJ.userMuted') as boolean;
if (currentlyMuted) {
await this.unmute();
} else {
await this.mute();
}
}
/**
* Get user's current mute preference
*/
getUserMuteState(): boolean {
return game.settings.get('bardic-inspiration', 'youtubeDJ.userMuted') as boolean;
}
/**
* Get user's current volume preference
*/
getUserVolume(): number {
return game.settings.get('bardic-inspiration', 'youtubeDJ.userVolume') as number;
}
/**
* Set user's volume preference
*/
async setUserVolume(volume: number): Promise<void> {
if (volume < 0 || volume > 100) {
throw new Error('Volume must be between 0 and 100');
}
// Store in client settings
await game.settings.set('bardic-inspiration', 'youtubeDJ.userVolume', volume);
// Send command only to local player
Hooks.callAll('youtubeDJ.localPlayerCommand', { command: 'setVolume', args: [volume] });
logger.debug(`π΅ YouTube DJ | User volume set to ${volume} (local only)`);
}
/**
* Start heartbeat for synchronization
*/
startHeartbeat(): void {
if (!this.store.isDJ()) {
logger.debug('π΅ YouTube DJ | Not DJ, skipping heartbeat start');
return;
}
this.stopHeartbeat();
const frequency = this.store.getPlayerState().heartbeatFrequency;
logger.info('π΅ YouTube DJ | Starting heartbeat timer with frequency:', frequency);
this.heartbeatInterval = window.setInterval(() => {
logger.debug('π΅ YouTube DJ | Heartbeat timer tick');
this.sendHeartbeat();
}, frequency);
logger.debug('π΅ YouTube DJ | Heartbeat started for session activity tracking');
}
/**
* Stop heartbeat
*/
stopHeartbeat(): void {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
logger.debug('π΅ YouTube DJ | Heartbeat stopped');
}
}
// Legacy syncWithHeartbeat removed - widget handles synchronization
// Legacy getCurrentTime and getDuration removed - widget handles player queries
/**
* Enable autoplay consent
*/
enableAutoplayConsent(): void {
this.store.updateState({
player: {
...this.store.getPlayerState(),
autoplayConsent: true
}
});
logger.debug('π΅ YouTube DJ | Autoplay consent enabled');
}
// Legacy onPlayerReady removed - widget handles player events
// Legacy onPlayerStateChange removed - widget handles player events
// Legacy onPlayerError removed - widget handles player events
/**
* Send heartbeat to other players
*/
private async sendHeartbeat(): Promise<void> {
if (!this.store.isDJ()) {
return;
}
// Continue heartbeats even when player is not ready for session activity tracking
try {
const playerState = this.store.getPlayerState();
const currentVideo = playerState.currentVideo;
const isPlaying = playerState.playbackState === 'playing';
// Request current time from widget player (only if player is ready)
let currentTime = playerState.currentTime || 0;
let playlistIndex: number | undefined;
let playlistId: string | undefined;
if (playerState.isReady) {
try {
// Emit request for current time and wait for response
const timeRequest = new Promise<number>((resolve) => {
const timeout = setTimeout(() => resolve(currentTime), 100); // 100ms timeout, fallback to stored time
const timeHandler = (data: { currentTime: number }) => {
clearTimeout(timeout);
Hooks.off('youtubeDJ.currentTimeResponse', timeHandler);
resolve(data.currentTime);
};
Hooks.on('youtubeDJ.currentTimeResponse', timeHandler);
Hooks.callAll('youtubeDJ.getCurrentTimeRequest');
});
currentTime = await timeRequest;
// Also request playlist index if playing a playlist
const queueState = this.store.getQueueState();
const currentItem = queueState.items[queueState.currentIndex];
if (currentItem?.isPlaylist) {
playlistId = currentItem.playlistId;
const indexRequest = new Promise<number | undefined>((resolve) => {
const timeout = setTimeout(() => resolve(undefined), 100);
const indexHandler = (data: { playlistIndex: number }) => {
clearTimeout(timeout);
Hooks.off('youtubeDJ.playlistIndexResponse', indexHandler);
resolve(data.playlistIndex);
};
Hooks.on('youtubeDJ.playlistIndexResponse', indexHandler);
Hooks.callAll('youtubeDJ.getPlaylistIndexRequest');
});
playlistIndex = await indexRequest;
}
} catch (error) {
logger.debug('π΅ YouTube DJ | Failed to get current time from widget, using stored time:', currentTime);
}
}
const heartbeat: HeartbeatData = {
videoId: currentVideo?.videoId || '',
currentTime,
duration: playerState.duration || 0,
isPlaying,
timestamp: Date.now(),
serverTime: Date.now(),
playlistId,
playlistIndex
};
// Debug log for playlist heartbeats
if (playlistId) {
logger.debug('π΅ YouTube DJ | Sending playlist heartbeat:', {
playlistId,
playlistIndex,
videoId: currentVideo?.videoId,
currentTime,
isPlaying
});
}
// Update stored current time
this.store.updateState({
player: {
...playerState,
currentTime,
lastHeartbeat: heartbeat
}
});
// Broadcast heartbeat
this.broadcastMessage({
type: 'HEARTBEAT',
userId: game.user?.id || '',
timestamp: Date.now(),
data: heartbeat
});
// Activity tracking is now handled by HeartbeatResponseHandler in SocketManager
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to send heartbeat:', error);
}
}
// Activity tracking is now handled by HeartbeatResponseHandler in SocketManager
// Seek updates are now handled by the widget player
// These methods are no longer needed as the widget manages player state directly
// Pending operations are no longer needed with widget architecture
/**
* Handle video ended event
*/
private handleVideoEnded(): void {
// This will be handled by QueueManager in next step
// For now, emit a hook for the queue to handle
Hooks.callAll('youtubeDJ.videoEnded', {
videoId: this.store.getPlayerState().currentVideo?.videoId
});
}
// Legacy ensureYouTubeAPI removed - widget handles YouTube API
/**
* Get video information from YouTube (public method)
*/
async fetchVideoInfo(videoId: string): Promise<VideoInfo> {
return this.getVideoInfo(videoId);
}
/**
* Get video information from YouTube
*/
private async getVideoInfo(videoId: string): Promise<VideoInfo> {
try {
// Use YouTube oEmbed API to fetch video metadata
const oembedUrl = `https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`;
const response = await fetch(oembedUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
// Log the full oEmbed response to understand available data
logger.debug('π΅ YouTube DJ | oEmbed response:', data);
return {
videoId,
title: data.title || `Video ${videoId}`,
duration: 0, // oEmbed doesn't provide duration, would need YouTube Data API for that
thumbnailUrl: data.thumbnail_url,
authorName: data.author_name,
authorUrl: data.author_url
};
} catch (error) {
logger.warn('π΅ YouTube DJ | Failed to fetch video metadata, using fallback:', error);
// Provide more specific error messages for better user experience
let fallbackTitle = `Video ${videoId}`;
if (error instanceof Error) {
if (error.message.includes('404')) {
fallbackTitle = `Video not found (${videoId})`;
} else if (error.message.includes('403')) {
fallbackTitle = `Private video (${videoId})`;
}
}
// Fallback to basic info if API call fails
return {
videoId,
title: fallbackTitle,
duration: 0
};
}
}
/**
* Broadcast message via socket
*/
private broadcastMessage(message: YouTubeDJMessage): void {
// This will be handled by SocketManager in next step
// For now, use direct socket communication
game.socket?.emit('module.bardic-inspiration', message);
}
/**
* Handle state changes for player management
*/
private onStateChanged(event: StateChangeEvent): void {
// React to specific state changes for player management
if (event.changes.session?.djUserId !== undefined) {
this.handleDJChange(event.previous.session.djUserId, event.current.session.djUserId);
}
}
/**
* Handle load video requests from QueueManager
*/
private async onLoadVideoRequest(data: { videoId: string; videoInfo: VideoInfo }): Promise<void> {
if (!this.store.isDJ()) {
logger.debug('π΅ YouTube DJ | Ignoring load request - not DJ');
return;
}
logger.debug('π΅ YouTube DJ | Loading video from queue request:', data.videoInfo.title);
try {
await this.loadVideo(data.videoId);
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to load video from queue:', error);
}
}
/**
* Handle cue video request (load without auto-play)
* This is used when loading saved queues to preserve user's playback/audio state
*/
private async onCueVideoRequest(data: { videoId: string; videoInfo: VideoInfo; autoPlay?: boolean }): Promise<void> {
if (!this.store.isDJ()) {
logger.debug('π΅ YouTube DJ | Ignoring cue request - not DJ');
return;
}
logger.debug('π΅ YouTube DJ | Cueing video from saved queue:', data.videoInfo.title);
try {
// Load video with autoPlay explicitly set to false
// This preserves the user's current mute/volume settings
await this.loadVideo(data.videoId, 0, false);
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to cue video from saved queue:', error);
}
}
/**
* Handle load playlist requests from QueueManager
*/
private async onLoadPlaylistRequest(data: { playlistId: string; playlistInfo: any }): Promise<void> {
if (!this.store.isDJ()) {
logger.debug('π΅ YouTube DJ | Ignoring playlist load request - not DJ');
return;
}
logger.debug('π΅ YouTube DJ | Loading playlist from queue request:', data.playlistId);
try {
await this.loadPlaylist(data.playlistId);
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to load playlist from queue:', error);
}
}
/**
* Handle heartbeat received from DJ
*/
private async onHeartbeatReceived(data: { heartbeat: HeartbeatData; timestamp: number }): Promise<void> {
if (this.store.isDJ()) {
// DJ doesn't sync to their own heartbeat
return;
}
this.syncWithHeartbeat(data.heartbeat).catch(error => {
logger.error('π΅ YouTube DJ | Failed to sync with heartbeat:', error);
});
}
/**
* Sync with heartbeat data from DJ (for non-DJ users)
*/
private async syncWithHeartbeat(heartbeat: HeartbeatData): Promise<void> {
if (this.store.isDJ()) {
return; // DJ doesn't sync to their own heartbeat
}
// Only sync if we have a different video or significant time difference
const currentVideo = this.store.getPlayerState().currentVideo;
// Check if video changed
if (currentVideo?.videoId !== heartbeat.videoId) {
logger.debug('π΅ YouTube DJ | Syncing to new video from heartbeat:', heartbeat.videoId);
// Send load command to widget
Hooks.callAll('youtubeDJ.playerCommand', {
command: 'loadVideoById',
args: [heartbeat.videoId, heartbeat.currentTime]
});
return;
}
// Get real current time from widget for accurate drift calculation
let localCurrentTime = this.store.getPlayerState().currentTime || 0;
try {
const timeRequest = new Promise<number>((resolve) => {
const timeout = setTimeout(() => resolve(localCurrentTime), 50); // 50ms timeout for sync operation
const timeHandler = (data: { currentTime: number }) => {
clearTimeout(timeout);
Hooks.off('youtubeDJ.currentTimeResponse', timeHandler);
resolve(data.currentTime);
};
Hooks.on('youtubeDJ.currentTimeResponse', timeHandler);
Hooks.callAll('youtubeDJ.getCurrentTimeRequest');
});
localCurrentTime = await timeRequest;
} catch (error) {
logger.debug('π΅ YouTube DJ | Failed to get current time for sync, using stored time');
}
// Use drift tolerance from player state (default 1.0 seconds)
const driftTolerance = this.store.getPlayerState().driftTolerance;
const timeDrift = Math.abs(localCurrentTime - heartbeat.currentTime);
if (timeDrift > driftTolerance) {
logger.debug('π΅ YouTube DJ | Syncing time drift:', {
local: localCurrentTime,
remote: heartbeat.currentTime,
drift: timeDrift,
tolerance: driftTolerance
});
// Send seek command to widget
Hooks.callAll('youtubeDJ.playerCommand', {
command: 'seekTo',
args: [heartbeat.currentTime, true]
});
}
// Sync play/pause state
const localPlaying = this.store.getPlayerState().playbackState === 'playing';
if (localPlaying !== heartbeat.isPlaying) {
logger.debug('π΅ YouTube DJ | Syncing play state:', { local: localPlaying, remote: heartbeat.isPlaying });
if (heartbeat.isPlaying) {
Hooks.callAll('youtubeDJ.playerCommand', { command: 'playVideo' });
} else {
Hooks.callAll('youtubeDJ.playerCommand', { command: 'pauseVideo' });
}
}
// Update local state with heartbeat data
this.store.updateState({
player: {
...this.store.getPlayerState(),
currentTime: heartbeat.currentTime,
duration: heartbeat.duration,
playbackState: heartbeat.isPlaying ? 'playing' : 'paused'
}
});
}
/**
* Handle play command from DJ
*/
private async onPlayCommand(data: { timestamp: number }): Promise<void> {
if (this.store.isDJ()) {
// DJ doesn't need to respond to their own commands
return;
}
if (!this.store.getPlayerState().isReady) {
logger.debug('π΅ YouTube DJ | Cannot sync play - player not ready');
return;
}
try {
// Send command to widget player
Hooks.callAll('youtubeDJ.playerCommand', { command: 'playVideo' });
this.store.updateState({
player: {
...this.store.getPlayerState(),
playbackState: 'playing'
}
});
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to sync play command:', error);
}
}
/**
* Handle pause command from DJ
*/
private async onPauseCommand(data: { timestamp: number }): Promise<void> {
if (this.store.isDJ()) {
// DJ doesn't need to respond to their own commands
return;
}
if (!this.store.getPlayerState().isReady) {
logger.debug('π΅ YouTube DJ | Cannot sync pause - player not ready');
return;
}
try {
// Send command to widget player
Hooks.callAll('youtubeDJ.playerCommand', { command: 'pauseVideo' });
this.store.updateState({
player: {
...this.store.getPlayerState(),
playbackState: 'paused'
}
});
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to sync pause command:', error);
}
}
/**
* Handle seek command from DJ
*/
private async onSeekCommand(data: { time: number; timestamp: number }): Promise<void> {
if (this.store.isDJ()) {
// DJ doesn't need to respond to their own commands
return;
}
if (!this.store.getPlayerState().isReady) {
logger.debug('π΅ YouTube DJ | Cannot sync seek - player not ready');
return;
}
try {
// Send command to widget player
Hooks.callAll('youtubeDJ.playerCommand', { command: 'seekTo', args: [data.time, true] });
this.store.updateState({
player: {
...this.store.getPlayerState(),
currentTime: data.time
}
});
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to sync seek command:', error);
}
}
/**
* Handle load command from DJ
*/
private async onLoadCommand(data: { videoId: string; startTime: number; videoInfo: any; autoPlay?: boolean; timestamp: number }): Promise<void> {
if (this.store.isDJ()) {
// DJ doesn't need to respond to their own commands
return;
}
if (!this.store.getPlayerState().isReady) {
logger.debug('π΅ YouTube DJ | Cannot sync load - player not ready');
return;
}
try {
// Update state with new video info
this.store.updateState({
player: {
...this.store.getPlayerState(),
currentVideo: data.videoInfo,
playbackState: 'loading'
}
});
// Send command to widget player - respect autoPlay flag
const command = data.autoPlay !== false ? 'loadVideoById' : 'cueVideoById';
Hooks.callAll('youtubeDJ.playerCommand', {
command: command,
args: [data.videoId, data.startTime || 0]
});
logger.debug('π΅ YouTube DJ | Synced video command:', {
command,
videoId: data.videoId,
autoPlay: data.autoPlay
});
} catch (error) {
logger.error('π΅ YouTube DJ | Failed to sync load command:', error);
}
}
/**
* Handle load playlist command from DJ
*/
private async onLoadPlaylistCommand(data: { playlistId: string; autoPlay?: boolean; timestamp: number }): Promise<void> {
if (this.store.isDJ()) {
// DJ doesn't need to respond to their own commands
return;
}
// If player not ready, wait a bit and retry
if (!this.store.getPlayerState().isReady) {
logger.debug('π΅ YouTube DJ | Player not ready for playlist load, will retry in 1 second');
setTimeout(() => {
if (this.store.getPlayerState().isReady) {
this.onLoadPlaylistCommand(data);
} else {
logger.warn('π΅ YouTube DJ | Player still not ready after retry, cannot sync playlist');
}
}, 1000);
return;