Apply latest YouTube state after player readiness

This commit is contained in:
codex
2026-06-10 20:01:52 +02:00
parent 741754b68b
commit a7905ddd16
+16 -7
View File
@@ -46,6 +46,8 @@ let currentYoutubeVideoId = "";
let applyingWatchStateUntil = 0;
let pauseEnforcementUntil = 0;
let desiredYoutubePlaying = false;
let pendingWatchState = null;
let pendingWatchStateOptions = null;
let watchPlaylist = [];
const peers = new Map();
@@ -292,6 +294,13 @@ async function ensureYoutubePlayer() {
events: {
onReady: () => {
youtubeReady = true;
if (pendingWatchState) {
const state = pendingWatchState;
const options = pendingWatchStateOptions || {};
pendingWatchState = null;
pendingWatchStateOptions = null;
applyWatchState(state, options).catch(console.error);
}
},
onStateChange: handleYoutubeStateChange
}
@@ -300,7 +309,7 @@ async function ensureYoutubePlayer() {
}
function requestYoutubePlayback(player) {
for (const delay of [0, 150, 750, 1500, 3000]) {
for (const delay of [0, 150, 750, 1500, 3000, 5000]) {
setTimeout(() => {
if (desiredYoutubePlaying) player.playVideo();
}, delay);
@@ -427,11 +436,14 @@ async function applyWatchState(state, { suppressEvents = true } = {}) {
if (shouldPlay) {
const sameVideo = player.getVideoData?.().video_id === currentYoutubeVideoId;
const playerState = player.getPlayerState?.();
if (sameVideo && playerState === YT.PlayerState.PLAYING) {
if (sameVideo) {
player.seekTo(position, true);
} else {
player.loadVideoById(currentYoutubeVideoId, position);
}
if (playerState !== YT.PlayerState.PLAYING) {
player.playVideo();
}
requestYoutubePlayback(player);
} else {
if (player.getVideoData?.().video_id !== currentYoutubeVideoId) {
@@ -452,11 +464,8 @@ async function applyWatchState(state, { suppressEvents = true } = {}) {
}, 2500);
}
} else {
const interval = setInterval(() => {
if (!youtubeReady) return;
clearInterval(interval);
applyWatchState(state, { suppressEvents }).catch(console.error);
}, 100);
pendingWatchState = state;
pendingWatchStateOptions = { suppressEvents };
}
}