web: watch-party layer for the Discord Activity

party.js is inert unless a transport attaches. The host publishes route changes
and playback snapshots; viewers mirror the route, load the host's stream without
scraping and follow its clock. Also: forceProxy playback, bug-tv-tmdb/bug-tv-img
meta overrides, relative API bases (/tv), trailer hidden in party mode, and the
web package no longer ships web/test.
This commit is contained in:
4DBug committed 2026-10-27 10:00:34 -05:00
1 parent 5ab3683f44
commit ee0e36d2c7
14 files changed
+800 -17

No files matched your search

+1 -1
View File
@@ -120,7 +120,7 @@ export async function render(root, params) {
const actions = h('div.hero__actions',
playBtn,
myListButton(item, { className: 'btn btn--glass btn--lg' }),
trailer ? h('button.btn.btn--glass.btn--lg', { type: 'button', onclick: () => trailerModal(trailer.key, item.title) }, icon('trailer'), h('span', 'Trailer')) : null,
trailer ? h('button.btn.btn--glass.btn--lg.js-trailer', { type: 'button', onclick: () => trailerModal(trailer.key, item.title) }, icon('trailer'), h('span', 'Trailer')) : null,
h('button.btn.btn--glass.btn--lg.btn--icon', { type: 'button', 'aria-label': 'Share', title: 'Share', onclick: () => shareTitle(item.title, titlePath(type, id)) }, icon('share')),
);
+345 -11
View File
@@ -9,6 +9,10 @@
3. Fatal errors / startup stalls fail over to the next ranked source.
4. Progress is persisted with the v4 semantics (storage.resume).
5. TV: prefetch next episode at 80%, "Next episode" card at the credits.
6. Party (party.js): the host publishes a `play` snapshot on every change and
every 2s; a viewer never scrapes, it loads the host's stream and follows
its clock (seek over 1.5s drift, playbackRate 0.95/1.05 under it), with
only volume/mute/fullscreen/PiP controls.
export render(root, params) → cleanup()
*/
@@ -18,11 +22,17 @@ import * as router from '../router.js';
import { resume, keyFor, prefs } from '../storage.js';
import { h, formatSeconds } from '../util.js';
import { createPlayer } from '../ui/player.js';
import { party } from '../party.js';
const GRACE_MS = 1500;
const CONTROLS_HIDE_MS = 3000;
const NEXT_COUNTDOWN = 10;
const CREDITS_SEC = 30;
const HEARTBEAT_MS = 2000;
const DRIFT_MS = 500;
const SEEK_DRIFT = 1.5;
const RATE_DRIFT = 0.3;
const PAUSED_DRIFT = 0.5;
/* ---- icons (static markup) ------------------------------------------------ */
@@ -140,6 +150,11 @@ function replaceUrl(path) {
let activeView = null;
/** The mounted watch view's handle ({ player, state, snapshot(), playStream, switchTo, switchEpisode, chooseSub, role }) or null. */
export function active() {
return activeView;
}
/** Router hook: same-route change (e.g. another episode) handled in place. */
export function update(params) {
return activeView ? activeView.update(params) : false;
@@ -219,6 +234,7 @@ export function render(root, params = {}) {
const bigPlay = btn('pl-bigplay', 'play', 'Play', () => player.toggle());
const spinner = h('div.pl-spin', h('div.pl-ring'));
const centerMsg = h('div.pl-center-msg');
const joinBtn = h('button.pl-join', { type: 'button', hidden: true }, icon('play'), h('span', 'Click to join'));
const rippleL = h('div.pl-ripple.pl-ripple--l', icon('rew'), h('span', '10s'));
const rippleR = h('div.pl-ripple.pl-ripple--r', icon('fwd'), h('span', '10s'));
@@ -325,7 +341,7 @@ export function render(root, params = {}) {
backdrop,
video,
scrim,
h('div.pl-center', bigPlay, spinner, centerMsg),
h('div.pl-center', bigPlay, spinner, centerMsg, joinBtn),
rippleL,
rippleR,
loading,
@@ -337,6 +353,14 @@ export function render(root, params = {}) {
nextCard,
toastBox,
);
for (const x of [backBtn, bigPlay, playBtn, rewBtn, fwdBtn, nextBtn, epBtn, ccBtn, gearBtn, srcBtn, qualityTag, ldPick, menu, srcPanel, epPanel, nextCard]) {
x.classList.add('pl-host-only');
}
// the Activity overlay blocks viewer clicks except on [data-party-allow]
for (const x of [muteBtn, vol, fullBtn, pipBtn, joinBtn]) x.setAttribute('data-party-allow', '');
let role = party.mode; // 'solo' | 'host' | 'viewer'
const isViewer = () => role === 'viewer';
el.classList.toggle('is-viewer', isViewer());
root.replaceChildren(el);
document.documentElement.classList.add('pl-open');
disposers.push(() => document.documentElement.classList.remove('pl-open'));
@@ -470,13 +494,14 @@ export function render(root, params = {}) {
}
function playNext() {
if (isViewer()) return;
const n = nextEpisodeRef();
if (!n) return;
switchEpisode(n.season, n.episode);
}
async function showNextCard(fromEnded) {
if (!isTv || state.nextDismissed || !nextCard.hidden) return;
if (!isTv || isViewer() || state.nextDismissed || !nextCard.hidden) return;
const n = nextEpisodeRef();
if (!n) return;
let ep = n.ep;
@@ -537,9 +562,12 @@ export function render(root, params = {}) {
.map((x) => x.s);
}
function startStreams() {
function startStreams(opts = {}) {
const gen = ++state.loadGen;
if (state.sse) state.sse.close();
state.sse = null;
if (isViewer()) return; // viewers never scrape: they follow the host's snapshot
const keep = opts.keep ? state.current : null;
state.streams.clear();
state.ranked = [];
state.failed.clear();
@@ -551,6 +579,11 @@ export function render(root, params = {}) {
state.current = null;
clearTimeout(state.graceTimer);
state.graceTimer = null;
if (keep) {
// promoted viewer: keep what is playing, search in the background for the sources panel
state.current = keep;
state.started = true;
}
renderProviders();
renderSources();
@@ -607,7 +640,7 @@ export function render(root, params = {}) {
}
function beginPlayback(why) {
if (state.started || destroyed) return;
if (state.started || destroyed || isViewer()) return;
clearTimeout(state.graceTimer);
const first = state.ranked.find((s) => !state.failed.has(s.id));
if (!first) {
@@ -630,15 +663,17 @@ export function render(root, params = {}) {
ldCount.textContent = failed ? `${failed} source${failed === 1 ? '' : 's'} failed` : '';
}
function playStream(s, startAt) {
function playStream(s, startAt, autoplay = true) {
state.current = s;
state.levelPick = -1; // new source starts on auto
qualityTag.textContent = qualityLabel(s);
if (!state.playingOnce) setPhase('starting');
ldStatus.textContent = `Starting ${s.provider} · ${qualityLabel(s)} ${kindBadge(s)}`;
player.load(s, { startAt, autoplay: true });
player.load(s, { startAt, autoplay });
applyVolume();
renderSources();
renderMenus();
publishSoon();
}
function switchTo(s, reason) {
@@ -648,6 +683,21 @@ export function render(root, params = {}) {
}
function tryNext(msg) {
if (isViewer()) {
// the host decides on failover; show the waiting screen until its next snapshot.
// back off retrying the same stream (2s, 4s, 8s … 30s) so a source that is dead only
// for this viewer doesn't reload on every heartbeat
if (viewer.loadedId) {
viewer.failCount = viewer.failedId === viewer.loadedId ? viewer.failCount + 1 : 1;
viewer.failedId = viewer.loadedId;
viewer.retryAt = Date.now() + Math.min(30000, 2000 * 2 ** (viewer.failCount - 1));
}
state.current = null;
viewer.loadedId = null;
setPhase(state.playingOnce ? 'buffering' : 'finding');
ldStatus.textContent = `Waiting for ${party.hostName() || 'the host'}…`;
return;
}
const next = state.ranked.find((s) => !state.failed.has(s.id) && s !== state.current);
if (!next) {
state.current = null;
@@ -675,12 +725,19 @@ export function render(root, params = {}) {
state.playingOnce = true;
setPhase('playing');
rememberProvider();
joinBtn.hidden = true;
publishSoon();
break;
case 'ready':
case 'blocked':
case 'paused':
if (state.playingOnce || st.phase !== 'paused') setPhase('paused');
state.playingOnce = state.playingOnce || st.phase === 'blocked' || st.phase === 'ready';
if (st.phase === 'blocked' && isViewer()) {
viewer.blocked = true;
joinBtn.hidden = false;
}
if (st.phase === 'paused') publishSoon();
break;
case 'buffering':
case 'seeking':
@@ -699,6 +756,7 @@ export function render(root, params = {}) {
resume.remove(currentKey());
if (isTv) showNextCard(true);
setPhase('paused');
publishSoon();
break;
default:
break;
@@ -716,11 +774,15 @@ export function render(root, params = {}) {
},
onLevels() {
renderMenus();
if (isViewer()) applyTracks();
else publishSoon();
const lv = player.playingLevel();
if (lv && lv.height) qualityTag.textContent = lv.height >= 2160 ? '4K' : `${lv.height}p`;
},
onAudioTracks() {
renderMenus();
if (isViewer()) applyTracks();
else publishSoon();
},
onTorrent(st) {
const parts = [];
@@ -737,6 +799,7 @@ export function render(root, params = {}) {
function rememberProvider() {
const s = state.current;
if (!s) return;
if (isViewer()) return applyTracks(); // the host picks subtitles
const map = lastProviderMap();
if (map[showKey] !== s.provider) {
map[showKey] = s.provider;
@@ -764,6 +827,7 @@ export function render(root, params = {}) {
}
player.setSubtitle(activeSub);
renderMenus();
publishSoon();
}
function chooseSub(i, remember = true) {
@@ -776,6 +840,7 @@ export function render(root, params = {}) {
prefs.set('subtitleLang', sub ? sub.lang || sub.label : '');
}
renderMenus();
publishSoon();
}
function toggleCc() {
@@ -842,9 +907,9 @@ export function render(root, params = {}) {
menu.appendChild(h('div.pl-menu__head', 'Quality'));
if (levels.length) {
const playing = player.playingLevel();
menu.appendChild(menuItem('Auto', cur < 0, () => player.setLevel(-1), cur < 0 && playing ? playing.label : ''));
menu.appendChild(menuItem('Auto', cur < 0, () => chooseLevel(-1), cur < 0 && playing ? playing.label : ''));
for (const l of levels.slice().sort((a, b) => b.height - a.height || b.bitrate - a.bitrate)) {
menu.appendChild(menuItem(l.label, l.index === cur, () => player.setLevel(l.index), l.bitrate ? `${(l.bitrate / 1e6).toFixed(1)} Mbps` : ''));
menu.appendChild(menuItem(l.label, l.index === cur, () => chooseLevel(l.index), l.bitrate ? `${(l.bitrate / 1e6).toFixed(1)} Mbps` : ''));
}
} else {
menu.appendChild(h('div.pl-menu__empty', state.current ? `${qualityLabel(state.current)} · fixed by source` : 'No source yet'));
@@ -853,7 +918,7 @@ export function render(root, params = {}) {
if (tracks.length > 1) {
menu.appendChild(h('div.pl-menu__head', 'Audio'));
const ca = player.currentAudioTrack();
for (const t of tracks) menu.appendChild(menuItem(t.label, t.index === ca, () => player.setAudioTrack(t.index), t.lang && !t.label.toLowerCase().includes(t.lang.toLowerCase()) ? t.lang : ''));
for (const t of tracks) menu.appendChild(menuItem(t.label, t.index === ca, () => (player.setAudioTrack(t.index), publishSoon()), t.lang && !t.label.toLowerCase().includes(t.lang.toLowerCase()) ? t.lang : ''));
}
menu.appendChild(h('div.pl-menu__head', 'Speed'));
const seg = h('div.pl-menu__seg');
@@ -870,6 +935,14 @@ export function render(root, params = {}) {
}
}
// the host's quality pick (level height, -1 auto) for snapshots; hls.js may report auto mid-switch
function chooseLevel(i) {
const l = i >= 0 ? player.levels()[i] : null;
state.levelPick = l && l.height ? l.height : -1;
player.setLevel(i);
publishSoon();
}
function toggleMenu(name, anchor) {
if (openMenu === name) return closeMenu();
closePanels();
@@ -1062,10 +1135,14 @@ export function render(root, params = {}) {
const qs = params.query && String(params.query);
replaceUrl(watchPath(type, id, season, episode) + (qs ? `?${qs}` : ''));
setPhase('finding');
ldStatus.textContent = 'Finding sources…';
ldStatus.textContent = isViewer() ? `Waiting for ${party.hostName() || 'the host'}…` : 'Finding sources…';
ldTorrent.hidden = true;
renderTitles();
state.current = null;
viewer.loadedId = null;
startStreams();
publishSoon();
if (isViewer() && party.lastPlay) applySnapshot(party.lastPlay);
if (!state.seasonData || state.seasonData.season_number !== season) {
state.seasonData = null;
await loadSeason(season);
@@ -1207,7 +1284,10 @@ export function render(root, params = {}) {
scrubbing = false;
seek.classList.remove('is-scrub', 'is-hover');
const d = player.duration();
if (d && e.type === 'pointerup') player.seek(seekRatio(e.clientX) * d);
if (d && e.type === 'pointerup' && !isViewer()) {
player.seek(seekRatio(e.clientX) * d);
publishSoon();
}
paintTime();
};
listen(seek, 'pointerup', endScrub);
@@ -1215,10 +1295,12 @@ export function render(root, params = {}) {
listen(seek, 'click', (e) => e.stopPropagation());
function skip(delta) {
if (isViewer()) return;
const d = player.duration();
let t = player.currentTime() + delta;
if (d) t = Math.min(d - 1, t);
player.seek(Math.max(0, t));
publishSoon();
showControls();
}
@@ -1337,6 +1419,11 @@ export function render(root, params = {}) {
if (openMenu) return closeMenu();
if (openPanel) return closePanels();
if (el.dataset.phase === 'finding' || el.dataset.phase === 'starting' || el.dataset.phase === 'error') return;
if (isViewer()) {
if (el.classList.contains('show-ui')) hideControls();
else showControls();
return;
}
const touch = e.pointerType === 'touch' || (e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents);
const now = Date.now();
const r = el.getBoundingClientRect();
@@ -1382,6 +1469,7 @@ export function render(root, params = {}) {
const tag = ((e.target && e.target.tagName) || '').toLowerCase();
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
const k = e.key;
if (isViewer() && !/^[mMfF]$/.test(k)) return;
const handled = () => {
e.preventDefault();
showControls();
@@ -1468,6 +1556,7 @@ export function render(root, params = {}) {
/* ---- back ------------------------------------------------------------------ */
function goBack() {
if (isViewer()) return;
persistProgress(true);
if (isFull()) {
try {
@@ -1481,6 +1570,233 @@ export function render(root, params = {}) {
else router.navigate(fallback);
}
/* ---- party: host publishing --------------------------------------------------- */
function mediaRef() {
return { type, id: Number(id), season: isTv ? state.season : null, episode: isTv ? state.episode : null };
}
function snapshot() {
const sub = activeSub >= 0 ? player.subtitles()[activeSub] : null;
return {
path: watchPath(type, id, state.season, state.episode),
media: mediaRef(),
stream: state.current || null, // the Stream object as loaded (player.original), never the proxied copy
subtitle: sub ? { index: sub.index, lang: sub.lang, label: sub.label } : null,
quality: state.levelPick > 0 ? state.levelPick : -1,
audio: state.current ? player.currentAudioTrack() : -1,
playing: !!state.current && !video.paused && !video.ended,
position: state.current ? player.currentTime() : 0,
duration: state.current ? player.duration() : 0,
};
}
let publishTimer = null;
function publishNow() {
clearTimeout(publishTimer);
publishTimer = null;
if (destroyed || role !== 'host' || party.mode !== 'host') return;
party.publish('play', { snapshot: snapshot() });
}
// bursts (load + subtitle + level events) collapse into one message
function publishSoon() {
if (role !== 'host' || publishTimer) return;
publishTimer = setTimeout(publishNow, 100);
}
listen(video, 'seeked', publishSoon);
const heartbeat = setInterval(publishNow, HEARTBEAT_MS);
disposers.push(() => clearInterval(heartbeat));
/* ---- party: viewer ------------------------------------------------------------- */
const viewer = {
snap: null, // last applied snapshot (for this media)
loadedId: null, // stream id we loaded for it
subKey: undefined, // applied subtitle key
lastSeek: 0,
stuckSince: 0,
blocked: false,
failedId: null, // stream that last failed for this viewer, and when to retry it
failCount: 0,
retryAt: 0,
};
function sameMedia(m) {
if (!m) return false;
const mt = m.type === 'tv' ? 'tv' : 'movie';
if (mt !== type || String(m.id) !== id) return false;
return !isTv || (Number(m.season) === state.season && Number(m.episode) === state.episode);
}
function targetTime(snap) {
const pos = Number(snap.position) || 0;
if (!snap.playing || !snap.at) return pos;
return pos + Math.max(0, party.now() - snap.at) / 1000;
}
function viewerWait() {
if (!state.playingOnce) setPhase('finding');
else setPhase('buffering');
ldStatus.textContent = `Waiting for ${party.hostName() || 'the host'}…`;
ldCount.textContent = '';
}
function applySnapshot(snap) {
if (destroyed || !isViewer() || !snap || !sameMedia(snap.media)) return;
viewer.snap = snap;
const s = snap.stream;
if (!s || !s.playback) {
if (state.current) player.stop();
state.current = null;
viewer.loadedId = null;
viewerWait();
return;
}
if (viewer.loadedId !== s.id || !state.current) {
if (s.id === viewer.failedId && Date.now() < viewer.retryAt) return;
viewer.loadedId = s.id;
viewer.subKey = undefined;
viewer.lastSeek = Date.now();
playStream(s, targetTime(snap), !!snap.playing && !viewer.blocked);
}
applyTracks();
if (snap.playing) {
if (video.paused && !viewer.blocked) player.play();
} else if (!video.paused) player.pause();
if (!snap.playing) joinBtn.hidden = true;
else if (viewer.blocked) joinBtn.hidden = false;
}
// subtitle / quality / audio from the snapshot; re-run when tracks or levels appear
function applyTracks() {
const snap = viewer.snap;
if (!isViewer() || !snap || !state.current || viewer.loadedId !== (snap.stream && snap.stream.id)) return;
const sub = snap.subtitle;
const key = sub ? `${sub.lang}|${sub.label}|${sub.index}` : 'off';
const subs = player.subtitles();
if (key !== viewer.subKey && (!sub || subs.length)) {
viewer.subKey = key;
let i = -1;
if (sub) {
const hit = subs.find((x) => x.lang === sub.lang && x.label === sub.label) || subs[sub.index];
i = hit ? hit.index : -1;
}
subsAppliedFor = state.current.id;
if (i !== activeSub) chooseSub(i, false);
}
const levels = player.levels();
if (levels.length) {
let want = -1;
if (snap.quality > 0) {
let best = null;
for (const l of levels) if (!best || Math.abs(l.height - snap.quality) < Math.abs(best.height - snap.quality)) best = l;
if (best) want = best.index;
}
if (want !== player.currentLevel()) player.setLevel(want);
}
const tracks = player.audioTracks();
if (snap.audio >= 0 && tracks[snap.audio] && player.currentAudioTrack() !== snap.audio) {
viewer.lastSeek = Date.now();
player.setAudioTrack(snap.audio);
}
}
function correctDrift() {
const snap = viewer.snap;
if (!isViewer() || !snap || !state.current || viewer.loadedId !== (snap.stream && snap.stream.id)) return;
if (viewer.blocked || document.hidden) return;
const now = Date.now();
// let a seek/buffer settle, but nudge one that has been stuck for a while
let stuck = false;
if (video.readyState < 2 || video.seeking) {
if (!viewer.stuckSince) viewer.stuckSince = now;
if (now - viewer.stuckSince < (player.mode === 'remux' ? 12000 : 5000)) return;
viewer.stuckSince = now;
stuck = true;
} else viewer.stuckSince = 0;
const target = targetTime(snap);
const d = player.duration();
if (d && target >= d - 0.5) return; // at the end: let it end on its own
const drift = player.currentTime() - target;
const abs = Math.abs(drift);
const remux = player.mode === 'remux';
if (!snap.playing) {
if (video.playbackRate !== 1) video.playbackRate = 1;
if (abs > PAUSED_DRIFT && (stuck || now - viewer.lastSeek > (remux ? 3000 : 1000))) {
viewer.lastSeek = now;
player.seek(target);
}
return;
}
if (video.paused) return;
if (abs > SEEK_DRIFT || (stuck && abs > PAUSED_DRIFT)) {
if (!stuck && now - viewer.lastSeek < (remux ? 3000 : 1500)) return;
viewer.lastSeek = now;
video.playbackRate = 1;
// remux reloads from the keyframe before t, hls/file land close to t
player.seek(target + (remux ? 0 : 0.2));
} else if (abs > RATE_DRIFT) {
video.playbackRate = drift < 0 ? 1.05 : 0.95;
} else if (video.playbackRate !== 1) video.playbackRate = 1;
}
const driftTimer = setInterval(correctDrift, DRIFT_MS);
disposers.push(() => clearInterval(driftTimer));
joinBtn.addEventListener('click', (e) => {
e.stopPropagation();
viewer.blocked = false;
joinBtn.hidden = true;
if (viewer.snap && state.current) {
// local playback only: jump to the host's clock, then start
player.seek(targetTime(viewer.snap));
if (viewer.snap.playing) player.play();
}
});
function setRole(next) {
if (next === role || destroyed) return;
const was = role;
role = next;
el.classList.toggle('is-viewer', isViewer());
if (isViewer()) {
// stop scraping and follow the host from here on
state.loadGen++;
if (state.sse) state.sse.close();
state.sse = null;
clearTimeout(state.graceTimer);
state.graceTimer = null;
closeMenu();
closePanels();
hideNextCard();
viewer.loadedId = null;
if (party.lastPlay && sameMedia(party.lastPlay.media)) applySnapshot(party.lastPlay);
else {
if (state.current) player.stop();
state.current = null;
viewerWait();
}
return;
}
if (was === 'viewer') {
// promoted: keep playing what the old host had, search sources for the panel
video.playbackRate = 1;
joinBtn.hidden = true;
viewer.snap = null;
startStreams({ keep: true });
if (!state.current && el.dataset.phase === 'finding') ldStatus.textContent = 'Finding sources…';
}
publishSoon();
}
const partyOffs = [
party.on('mode', ({ mode: m }) => setRole(m)),
party.on('resend', () => publishNow()),
party.on('play', (snap) => applySnapshot(snap)),
party.on('members', () => {
if (isViewer() && !state.current) viewerWait();
}),
];
/* ---- boot ---------------------------------------------------------------------- */
renderTitles();
@@ -1489,11 +1805,25 @@ export function render(root, params = {}) {
setPhase('error');
ldStatus.textContent = 'Missing title id.';
} else {
if (isViewer()) viewerWait();
startStreams();
loadMeta();
if (isViewer() && party.lastPlay) applySnapshot(party.lastPlay);
}
const view = {
// handle for party/debug tooling
player,
state,
snapshot,
playStream,
switchTo,
switchEpisode,
chooseSub,
chooseLevel,
get role() {
return role;
},
update(p) {
if ((p.type === 'tv' ? 'tv' : 'movie') !== type || String(p.id) !== id) return false;
if (!isTv) return true;
@@ -1508,6 +1838,10 @@ export function render(root, params = {}) {
return function cleanup() {
persistProgress(true);
destroyed = true;
clearTimeout(publishTimer);
for (const off of partyOffs) off();
// left the watch page: viewers stop following this snapshot
if (role === 'host' && party.mode === 'host') party.publish('play', { snapshot: null });
if (activeView === view) activeView = null;
if (state.sse) state.sse.close();
clearTimeout(state.graceTimer);