Skip to content

Commit ab91e6d

Browse files
rewhexCopilotrewhex
authored
Fixed missing videochange dataupdated event when using shuffle (#3659)
Co-authored-by: Copilot <[email protected]> Co-authored-by: rewhex <[email protected]>
1 parent be3ae4d commit ab91e6d

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/providers/song-info-front.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import type {
1212
import type { SongInfo } from './song-info';
1313
import type { VideoDataChanged } from '@/types/video-data-changed';
1414

15+
const DATAUPDATED_FALLBACK_TIMEOUT_MS = 1500;
16+
1517
let songInfo: SongInfo = {} as SongInfo;
1618
export const getSongInfo = () => songInfo;
1719

@@ -253,12 +255,25 @@ export const setupSongInfo = (api: YoutubePlayer) => {
253255
);
254256

255257
const waitingEvent = new Set<string>();
258+
const waitingTimeouts = new Map<string, NodeJS.Timeout>();
259+
260+
const clearVideoTimeout = (videoId: string) => {
261+
const timeoutId = waitingTimeouts.get(videoId);
262+
263+
if (timeoutId) {
264+
clearTimeout(timeoutId);
265+
waitingTimeouts.delete(videoId);
266+
}
267+
};
268+
256269
// Name = "dataloaded" and abit later "dataupdated"
270+
// Sometimes "dataupdated" is not fired, so we need to fallback to "dataloaded"
257271
api.addEventListener('videodatachange', (name, videoData) => {
258272
videoEventDispatcher(name, videoData);
259273

260274
if (name === 'dataupdated' && waitingEvent.has(videoData.videoId)) {
261275
waitingEvent.delete(videoData.videoId);
276+
clearVideoTimeout(videoData.videoId);
262277
sendSongInfo(videoData);
263278
} else if (name === 'dataloaded') {
264279
const video = document.querySelector<HTMLVideoElement>('video');
@@ -269,7 +284,18 @@ export const setupSongInfo = (api: YoutubePlayer) => {
269284
video?.addEventListener(status, playPausedHandlers[status]);
270285
}
271286

287+
clearVideoTimeout(videoData.videoId);
272288
waitingEvent.add(videoData.videoId);
289+
290+
const timeoutId = setTimeout(() => {
291+
if (waitingEvent.has(videoData.videoId)) {
292+
waitingEvent.delete(videoData.videoId);
293+
waitingTimeouts.delete(videoData.videoId);
294+
sendSongInfo(videoData);
295+
}
296+
}, DATAUPDATED_FALLBACK_TIMEOUT_MS);
297+
298+
waitingTimeouts.set(videoData.videoId, timeoutId);
273299
}
274300
});
275301

0 commit comments

Comments
 (0)