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.
1860 lines
68 KiB
JavaScript
1860 lines
68 KiB
JavaScript
/*
|
||
WATCH VIEW — full-screen player at /watch/:type/:id[/:season/:episode].
|
||
|
||
Flow:
|
||
1. TMDB details (+ season for tv) and api.streams start in parallel.
|
||
2. Streams arrive per provider over SSE and are ranked as they land.
|
||
Playback starts after a short grace window (immediately on a ≥1080p
|
||
hls/file hit, 1.5s after the first playable stream, or on `done`).
|
||
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()
|
||
*/
|
||
import * as api from '../api.js';
|
||
import * as tmdb from '../tmdb.js';
|
||
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) ------------------------------------------------ */
|
||
|
||
const I = {
|
||
play: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5.14v13.72a1 1 0 0 0 1.52.85l10.9-6.86a1 1 0 0 0 0-1.7L9.52 4.29A1 1 0 0 0 8 5.14z"/></svg>',
|
||
pause: '<svg viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4.5" width="4" height="15" rx="1.2"/><rect x="14" y="4.5" width="4" height="15" rx="1.2"/></svg>',
|
||
back: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 18l-6-6 6-6"/></svg>',
|
||
rew: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/><text x="12" y="15.5" font-size="7" font-weight="700" text-anchor="middle" fill="currentColor" stroke="none">10</text></svg>',
|
||
fwd: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 4v5h-5"/><text x="12" y="15.5" font-size="7" font-weight="700" text-anchor="middle" fill="currentColor" stroke="none">10</text></svg>',
|
||
vol: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5L6 9H3v6h3l5 4z" fill="currentColor"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M18.5 5.5a9 9 0 0 1 0 13"/></svg>',
|
||
volLow: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5L6 9H3v6h3l5 4z" fill="currentColor"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/></svg>',
|
||
mute: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5L6 9H3v6h3l5 4z" fill="currentColor"/><path d="M22 9l-6 6M16 9l6 6"/></svg>',
|
||
cc: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><rect x="2.5" y="5" width="19" height="14" rx="3"/><path d="M10.5 10.2a2.4 2.4 0 1 0 0 3.6M17 10.2a2.4 2.4 0 1 0 0 3.6" stroke-linecap="round"/></svg>',
|
||
gear: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',
|
||
sources: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 6h16M4 12h16M4 18h10"/></svg>',
|
||
episodes: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M7 20h10"/></svg>',
|
||
next: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M5 5.5v13a1 1 0 0 0 1.55.83L15 13.5V18a1 1 0 0 0 2 0V6a1 1 0 0 0-2 0v4.5L6.55 4.67A1 1 0 0 0 5 5.5z"/></svg>',
|
||
pip: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><rect x="2.5" y="4.5" width="19" height="15" rx="2.5"/><rect x="12" y="11" width="7" height="5.5" rx="1" fill="currentColor"/></svg>',
|
||
full: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9V5a1 1 0 0 1 1-1h4M15 4h4a1 1 0 0 1 1 1v4M20 15v4a1 1 0 0 1-1 1h-4M9 20H5a1 1 0 0 1-1-1v-4"/></svg>',
|
||
unfull: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 4v4a1 1 0 0 1-1 1H4M20 9h-4a1 1 0 0 1-1-1V4M15 20v-4a1 1 0 0 1 1-1h4M4 15h4a1 1 0 0 1 1 1v4"/></svg>',
|
||
close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>',
|
||
check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>',
|
||
};
|
||
|
||
function icon(name) {
|
||
const span = document.createElement('span');
|
||
span.className = 'pl-ico';
|
||
span.innerHTML = I[name];
|
||
return span;
|
||
}
|
||
|
||
function btn(cls, iconName, label, onClick) {
|
||
const b = h(`button.pl-btn${cls ? `.${cls}` : ''}`, { type: 'button', 'aria-label': label, title: label });
|
||
if (iconName) b.appendChild(icon(iconName));
|
||
if (onClick) b.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
onClick(e);
|
||
});
|
||
return b;
|
||
}
|
||
|
||
function setIcon(b, name) {
|
||
const ico = b.querySelector('.pl-ico');
|
||
if (ico) ico.innerHTML = I[name];
|
||
}
|
||
|
||
/* ---- source ranking ------------------------------------------------------- */
|
||
|
||
const KIND_LABEL = { hls: 'HLS', file: 'MP4', remux: 'Remux', torrent: 'Torrent' };
|
||
|
||
function kindOf(s) {
|
||
return (s.playback && s.playback.kind) || 'file';
|
||
}
|
||
|
||
export function scoreStream(s, lastProvider) {
|
||
const px = Number(s.pixels) || 0;
|
||
// compress 4K so a browser-friendly 1080p beats a heavy 4K remux/torrent
|
||
const q = px >= 2160 ? 1150 : px || 400;
|
||
const kind = kindOf(s);
|
||
let score = q;
|
||
if (kind === 'remux') score -= 150;
|
||
else if (kind === 'torrent') score -= 320 - Math.min(Number(s.seeds) || 0, 100);
|
||
if (s.playback && s.playback.fallback) score += 40; // direct-capable
|
||
if (lastProvider && s.provider === lastProvider) score += 100;
|
||
return score;
|
||
}
|
||
|
||
function isPlayable(s) {
|
||
return !!(s && s.playback && s.playback.url && KIND_LABEL[kindOf(s)]);
|
||
}
|
||
|
||
function fmtSize(s) {
|
||
const b = Number(s.size) || 0;
|
||
if (b > 0) {
|
||
if (b >= 1e9) return `${(b / 1e9).toFixed(b >= 1e10 ? 0 : 1)} GB`;
|
||
return `${Math.round(b / 1e6)} MB`;
|
||
}
|
||
return s.sizeText || '';
|
||
}
|
||
|
||
function kindBadge(s) {
|
||
const k = kindOf(s);
|
||
if (k === 'file') return String(s.type || 'mp4').toUpperCase() === 'WEBM' ? 'WebM' : 'MP4';
|
||
if (k === 'remux') return `${String(s.type || 'mkv').toUpperCase()} · remux`;
|
||
if (k === 'torrent') return s.seeds != null ? `Torrent · ${s.seeds} seeds` : 'Torrent';
|
||
return 'HLS';
|
||
}
|
||
|
||
function sourceName(s) {
|
||
const n = String(s.title || s.name || '').trim();
|
||
return n.toLowerCase() === String(s.provider || '').toLowerCase() ? '' : n;
|
||
}
|
||
|
||
function qualityLabel(s) {
|
||
const px = Number(s.pixels) || 0;
|
||
if (px >= 2160) return '4K';
|
||
if (px) return `${px}p`;
|
||
return s.quality || 'SD?';
|
||
}
|
||
|
||
/* ---- url helpers ----------------------------------------------------------- */
|
||
|
||
function watchPath(type, id, season, episode) {
|
||
return type === 'tv' ? `/watch/tv/${id}/${season}/${episode}` : `/watch/movie/${id}`;
|
||
}
|
||
|
||
function replaceUrl(path) {
|
||
// the router calls update() for same-route changes, which we handle in place
|
||
try {
|
||
router.navigate(path, { replace: true });
|
||
} catch (e) {
|
||
/* router not started (tests) */
|
||
}
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
/* ---- view ------------------------------------------------------------------ */
|
||
|
||
export function render(root, params = {}) {
|
||
const type = params.type === 'tv' ? 'tv' : 'movie';
|
||
const id = String(params.id || '');
|
||
const isTv = type === 'tv';
|
||
|
||
const disposers = [];
|
||
const listen = (target, name, fn, opts) => {
|
||
target.addEventListener(name, fn, opts);
|
||
disposers.push(() => target.removeEventListener(name, fn, opts));
|
||
};
|
||
let destroyed = false;
|
||
|
||
const state = {
|
||
details: null,
|
||
season: isTv ? Number(params.season) || 1 : null,
|
||
episode: isTv ? Number(params.episode) || 1 : null,
|
||
seasonData: null, // tmdb.season() for state.season
|
||
browseSeason: null,
|
||
streams: new Map(), // id → stream
|
||
ranked: [],
|
||
failed: new Set(),
|
||
providers: new Map(), // name → {status, ms, count}
|
||
providerNames: [],
|
||
done: false,
|
||
current: null,
|
||
started: false,
|
||
graceTimer: null,
|
||
sse: null,
|
||
lastPersist: 0,
|
||
prefetched: false,
|
||
nextDismissed: false,
|
||
nextTimer: null,
|
||
loadGen: 0,
|
||
};
|
||
|
||
const showKey = `${type}:${id}`;
|
||
const lastProviderMap = () => prefs.get('lastProvider', {}) || {};
|
||
const lastProvider = () => lastProviderMap()[showKey] || '';
|
||
|
||
/* ---- DOM ------------------------------------------------------------- */
|
||
|
||
const video = h('video.pl-video', { playsinline: true, preload: 'auto' });
|
||
video.setAttribute('webkit-playsinline', '');
|
||
|
||
const backdrop = h('div.pl-backdrop');
|
||
const scrim = h('div.pl-scrim');
|
||
|
||
// loading overlay
|
||
const ldLogo = h('img.pl-load__logo', { alt: '', hidden: true });
|
||
const ldTitle = h('h1.pl-load__title');
|
||
const ldSub = h('p.pl-load__sub');
|
||
const ldStatus = h('div.pl-load__status', 'Finding sources…');
|
||
const ldCount = h('div.pl-load__count');
|
||
const ldBar = h('div.pl-load__bar', h('span'));
|
||
const ldTicker = h('ul.pl-load__ticker', { 'aria-live': 'polite' });
|
||
const ldTorrent = h('div.pl-load__torrent', { hidden: true });
|
||
const ldPick = h('button.pl-chip-btn', { type: 'button' }, 'Choose source');
|
||
const loading = h(
|
||
'div.pl-load',
|
||
h('div.pl-load__inner', ldLogo, ldTitle, ldSub, h('div.pl-ring'), ldStatus, ldCount, ldBar, ldTorrent, ldTicker, ldPick),
|
||
);
|
||
|
||
// top bar
|
||
const backBtn = btn('pl-back', 'back', 'Back', goBack);
|
||
const topTitle = h('div.pl-top__title');
|
||
const topSub = h('div.pl-top__sub');
|
||
const top = h('div.pl-top', backBtn, h('div.pl-top__text', topTitle, topSub));
|
||
|
||
// center
|
||
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'));
|
||
|
||
// seek bar
|
||
const seekBuf = h('div.pl-seek__buf');
|
||
const seekFill = h('div.pl-seek__fill');
|
||
const seekHover = h('div.pl-seek__hover');
|
||
const seekThumb = h('div.pl-seek__thumb');
|
||
const seekTip = h('div.pl-seek__tip');
|
||
const seek = h(
|
||
'div.pl-seek',
|
||
{ role: 'slider', tabindex: '0', 'aria-label': 'Seek', 'aria-valuemin': '0' },
|
||
h('div.pl-seek__track', seekBuf, seekHover, seekFill),
|
||
seekThumb,
|
||
seekTip,
|
||
);
|
||
|
||
// controls row
|
||
const playBtn = btn('', 'play', 'Play (k)', () => player.toggle());
|
||
const rewBtn = btn('', 'rew', 'Back 10s (j)', () => skip(-10));
|
||
const fwdBtn = btn('', 'fwd', 'Forward 10s (l)', () => skip(10));
|
||
const muteBtn = btn('', 'vol', 'Mute (m)', () => setMuted(!video.muted));
|
||
const volFill = h('div.pl-vol__fill');
|
||
const vol = h('div.pl-vol', { role: 'slider', 'aria-label': 'Volume', tabindex: '0' }, h('div.pl-vol__track', volFill));
|
||
const timeEl = h('div.pl-time', '0:00 / 0:00');
|
||
const nextBtn = btn('pl-next-btn', 'next', 'Next episode (n)', () => playNext());
|
||
const epBtn = btn('', 'episodes', 'Episodes', () => togglePanel('episodes'));
|
||
const ccBtn = btn('', 'cc', 'Subtitles (c)', () => toggleMenu('cc', ccBtn));
|
||
const gearBtn = btn('', 'gear', 'Quality & audio', () => toggleMenu('gear', gearBtn));
|
||
const srcBtn = btn('pl-src-btn', 'sources', 'Sources', () => togglePanel('sources'));
|
||
const srcCount = h('span.pl-src-btn__count');
|
||
srcBtn.appendChild(srcCount);
|
||
const pipBtn = btn('', 'pip', 'Picture in picture', togglePip);
|
||
const fullBtn = btn('', 'full', 'Fullscreen (f)', toggleFullscreen);
|
||
const qualityTag = h('span.pl-qtag');
|
||
|
||
if (!isTv) {
|
||
nextBtn.hidden = true;
|
||
epBtn.hidden = true;
|
||
}
|
||
if (!document.pictureInPictureEnabled) pipBtn.hidden = true;
|
||
|
||
const controls = h(
|
||
'div.pl-bottom',
|
||
seek,
|
||
h(
|
||
'div.pl-row',
|
||
playBtn,
|
||
rewBtn,
|
||
fwdBtn,
|
||
h('div.pl-volwrap', muteBtn, vol),
|
||
timeEl,
|
||
h('div.pl-spacer'),
|
||
qualityTag,
|
||
nextBtn,
|
||
epBtn,
|
||
ccBtn,
|
||
gearBtn,
|
||
srcBtn,
|
||
pipBtn,
|
||
fullBtn,
|
||
),
|
||
);
|
||
|
||
// menus + panels
|
||
const menu = h('div.pl-menu', { hidden: true, role: 'menu' });
|
||
const srcList = h('div.pl-panel__list');
|
||
const srcHead = h('div.pl-panel__meta');
|
||
const provList = h('ul.pl-provs');
|
||
const srcPanel = h(
|
||
'aside.pl-panel.pl-panel--sources',
|
||
{ 'aria-label': 'Sources' },
|
||
h('header.pl-panel__head', h('div', h('h2', 'Sources'), srcHead), btn('', 'close', 'Close', () => closePanels())),
|
||
srcList,
|
||
h('details.pl-provs-wrap', h('summary', 'Providers'), provList),
|
||
);
|
||
const epSelect = h('select.pl-select', { 'aria-label': 'Season' });
|
||
const epList = h('div.pl-panel__list.pl-eps');
|
||
const epPanel = h(
|
||
'aside.pl-panel.pl-panel--episodes',
|
||
{ 'aria-label': 'Episodes' },
|
||
h('header.pl-panel__head', h('div', h('h2', 'Episodes'), epSelect), btn('', 'close', 'Close', () => closePanels())),
|
||
epList,
|
||
);
|
||
|
||
// next episode card
|
||
const nextImg = h('div.pl-nextcard__img');
|
||
const nextLabel = h('div.pl-nextcard__label');
|
||
const nextName = h('div.pl-nextcard__name');
|
||
const nextPlay = h('button.pl-nextcard__play', { type: 'button' }, icon('play'), h('span', 'Play now'));
|
||
const nextCancel = h('button.pl-nextcard__cancel', { type: 'button' }, 'Cancel');
|
||
const nextCard = h(
|
||
'div.pl-nextcard',
|
||
{ hidden: true },
|
||
nextImg,
|
||
h('div.pl-nextcard__body', nextLabel, nextName, h('div.pl-nextcard__actions', nextPlay, nextCancel)),
|
||
);
|
||
|
||
const toastBox = h('div.pl-toasts', { 'aria-live': 'polite' });
|
||
|
||
const el = h(
|
||
'div.pl',
|
||
{ 'data-phase': 'finding', tabindex: '-1' },
|
||
backdrop,
|
||
video,
|
||
scrim,
|
||
h('div.pl-center', bigPlay, spinner, centerMsg, joinBtn),
|
||
rippleL,
|
||
rippleR,
|
||
loading,
|
||
top,
|
||
controls,
|
||
menu,
|
||
srcPanel,
|
||
epPanel,
|
||
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'));
|
||
try {
|
||
el.focus({ preventScroll: true });
|
||
} catch (e) {
|
||
/* ignore */
|
||
}
|
||
|
||
/* ---- toast ------------------------------------------------------------ */
|
||
|
||
function toast(msg, kind) {
|
||
const t = h(`div.pl-toast${kind ? `.pl-toast--${kind}` : ''}`, msg);
|
||
toastBox.appendChild(t);
|
||
requestAnimationFrame(() => t.classList.add('is-in'));
|
||
setTimeout(() => {
|
||
t.classList.remove('is-in');
|
||
setTimeout(() => t.remove(), 400);
|
||
}, 3200);
|
||
}
|
||
|
||
/* ---- phase / header ----------------------------------------------------- */
|
||
|
||
function setPhase(p) {
|
||
el.dataset.phase = p;
|
||
}
|
||
|
||
function episodeObj(n) {
|
||
const eps = (state.seasonData && state.seasonData.episodes) || [];
|
||
return eps.find((e) => e.episode_number === n) || null;
|
||
}
|
||
|
||
function renderTitles() {
|
||
const d = state.details;
|
||
const name = d ? d.title || d.name || '' : '';
|
||
const fallback = isTv ? 'TV show' : 'Movie';
|
||
const title = name || fallback;
|
||
let sub = '';
|
||
if (isTv) {
|
||
const ep = episodeObj(state.episode);
|
||
sub = `S${state.season} · E${state.episode}${ep && ep.name ? ` — ${ep.name}` : ''}`;
|
||
} else if (d) {
|
||
const yr = String(d.release_date || '').slice(0, 4);
|
||
sub = [yr, d.runtime ? `${Math.floor(d.runtime / 60)}h ${d.runtime % 60}m` : ''].filter(Boolean).join(' · ');
|
||
}
|
||
topTitle.textContent = title;
|
||
topSub.textContent = sub;
|
||
ldTitle.textContent = title;
|
||
ldSub.textContent = sub;
|
||
if (d) {
|
||
document.title = `${isTv ? `${title} S${state.season}E${state.episode}` : title} — bug.tv`;
|
||
const logo = tmdb.logoFor ? tmdb.logoFor(d) : null;
|
||
if (logo && logo.file_path) {
|
||
ldLogo.src = tmdb.img(logo.file_path, 'w500');
|
||
ldLogo.alt = title;
|
||
ldLogo.hidden = false;
|
||
ldTitle.hidden = true;
|
||
ldLogo.onerror = () => {
|
||
ldLogo.hidden = true;
|
||
ldTitle.hidden = false;
|
||
};
|
||
}
|
||
const ep = isTv ? episodeObj(state.episode) : null;
|
||
const bdPath = d.backdrop_path || (ep && ep.still_path);
|
||
if (bdPath) {
|
||
const url = tmdb.img(bdPath, 'w1280');
|
||
backdrop.style.backgroundImage = `url("${url.replace(/"/g, '%22')}")`;
|
||
if (!video.poster) video.poster = url;
|
||
}
|
||
}
|
||
}
|
||
|
||
/* ---- metadata ------------------------------------------------------------ */
|
||
|
||
async function loadMeta() {
|
||
try {
|
||
const d = await tmdb.details(type, id);
|
||
if (destroyed) return;
|
||
state.details = d;
|
||
} catch (e) {
|
||
console.warn('[watch] details failed', e);
|
||
}
|
||
if (isTv) await loadSeason(state.season);
|
||
renderTitles();
|
||
renderNextButton();
|
||
}
|
||
|
||
const seasonCache = new Map();
|
||
async function fetchSeason(n) {
|
||
if (seasonCache.has(n)) return seasonCache.get(n);
|
||
const p = tmdb.season(id, n).catch(() => null);
|
||
seasonCache.set(n, p);
|
||
return p;
|
||
}
|
||
|
||
async function loadSeason(n) {
|
||
const data = await fetchSeason(n);
|
||
if (destroyed) return;
|
||
if (n === state.season) state.seasonData = data;
|
||
renderEpisodesPanel(n);
|
||
}
|
||
|
||
/* ---- next episode ----------------------------------------------------------- */
|
||
|
||
function seasonList() {
|
||
const d = state.details;
|
||
return ((d && d.seasons) || []).filter((s) => s.season_number > 0 && (s.episode_count || 0) > 0);
|
||
}
|
||
|
||
function nextEpisodeRef() {
|
||
if (!isTv) return null;
|
||
const eps = (state.seasonData && state.seasonData.episodes) || [];
|
||
const sorted = eps.slice().sort((a, b) => a.episode_number - b.episode_number);
|
||
const nxt = sorted.find((e) => e.episode_number > state.episode);
|
||
const today = new Date().toISOString().slice(0, 10);
|
||
if (nxt) {
|
||
if (nxt.air_date && nxt.air_date > today) return null;
|
||
return { season: state.season, episode: nxt.episode_number, ep: nxt };
|
||
}
|
||
const nextSeason = seasonList().find((s) => s.season_number > state.season);
|
||
if (nextSeason && !(nextSeason.air_date && nextSeason.air_date > today)) {
|
||
return { season: nextSeason.season_number, episode: 1, ep: null };
|
||
}
|
||
if (!state.seasonData && !state.details) return { season: state.season, episode: state.episode + 1, ep: null };
|
||
return null;
|
||
}
|
||
|
||
function renderNextButton() {
|
||
if (!isTv) return;
|
||
nextBtn.hidden = !nextEpisodeRef();
|
||
}
|
||
|
||
function playNext() {
|
||
if (isViewer()) return;
|
||
const n = nextEpisodeRef();
|
||
if (!n) return;
|
||
switchEpisode(n.season, n.episode);
|
||
}
|
||
|
||
async function showNextCard(fromEnded) {
|
||
if (!isTv || isViewer() || state.nextDismissed || !nextCard.hidden) return;
|
||
const n = nextEpisodeRef();
|
||
if (!n) return;
|
||
let ep = n.ep;
|
||
if (!ep && n.season !== state.season) {
|
||
const data = await fetchSeason(n.season);
|
||
ep = data && (data.episodes || []).find((e) => e.episode_number === n.episode);
|
||
}
|
||
if (destroyed || state.nextDismissed) return;
|
||
nextImg.style.backgroundImage = ep && ep.still_path ? `url("${tmdb.img(ep.still_path, 'w300')}")` : backdrop.style.backgroundImage;
|
||
nextName.textContent = `S${n.season} · E${n.episode}${ep && ep.name ? ` — ${ep.name}` : ''}`;
|
||
nextCard.hidden = false;
|
||
requestAnimationFrame(() => nextCard.classList.add('is-in'));
|
||
const auto = prefs.get('autoplayNext', true) !== false;
|
||
clearInterval(state.nextTimer);
|
||
if (!auto) {
|
||
nextLabel.textContent = 'Up next';
|
||
return;
|
||
}
|
||
let left = NEXT_COUNTDOWN;
|
||
nextLabel.textContent = `Next episode in ${left}s`;
|
||
nextCard.style.setProperty('--countdown', `${NEXT_COUNTDOWN}s`);
|
||
nextCard.classList.add('is-counting');
|
||
state.nextTimer = setInterval(() => {
|
||
if (video.paused && !video.ended && !fromEnded) return; // pause holds the countdown
|
||
left--;
|
||
nextLabel.textContent = `Next episode in ${left}s`;
|
||
if (left <= 0) {
|
||
clearInterval(state.nextTimer);
|
||
playNext();
|
||
}
|
||
}, 1000);
|
||
}
|
||
|
||
function hideNextCard() {
|
||
clearInterval(state.nextTimer);
|
||
nextCard.classList.remove('is-in', 'is-counting');
|
||
nextCard.hidden = true;
|
||
}
|
||
|
||
nextPlay.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
playNext();
|
||
});
|
||
nextCancel.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
state.nextDismissed = true;
|
||
hideNextCard();
|
||
});
|
||
|
||
/* ---- streams ------------------------------------------------------------------ */
|
||
|
||
function rerank() {
|
||
const lp = lastProvider();
|
||
state.ranked = [...state.streams.values()]
|
||
.filter(isPlayable)
|
||
.map((s) => ({ s, score: scoreStream(s, lp) }))
|
||
.sort((a, b) => b.score - a.score)
|
||
.map((x) => x.s);
|
||
}
|
||
|
||
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();
|
||
state.providers.clear();
|
||
state.providerNames = [];
|
||
state.done = false;
|
||
state.started = false;
|
||
state.eager = false;
|
||
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();
|
||
|
||
const p = { tmdb: id, type };
|
||
if (isTv) {
|
||
p.season = state.season;
|
||
p.episode = state.episode;
|
||
}
|
||
const t0 = performance.now();
|
||
state.sse = api.streams(p, {
|
||
onMeta(m) {
|
||
if (gen !== state.loadGen) return;
|
||
state.providerNames = m.providers || [];
|
||
for (const n of state.providerNames) if (!state.providers.has(n)) state.providers.set(n, { status: 'pending' });
|
||
renderProviders();
|
||
},
|
||
onStreams(ev) {
|
||
if (gen !== state.loadGen) return;
|
||
let best = null;
|
||
for (const s of ev.streams || []) {
|
||
if (!s || !s.id) s.id = `${ev.provider}:${s.playback && s.playback.url}`;
|
||
if (!s.provider) s.provider = ev.provider;
|
||
if (state.streams.has(s.id)) continue;
|
||
state.streams.set(s.id, s);
|
||
if (isPlayable(s) && (!best || (s.pixels || 0) > (best.pixels || 0))) best = s;
|
||
}
|
||
rerank();
|
||
renderSources();
|
||
if (!best || state.started) return;
|
||
if (state.eager) return beginPlayback('eager'); // a previous source failed: don't wait
|
||
const k = kindOf(best);
|
||
if ((best.pixels || 0) >= 1080 && (k === 'hls' || k === 'file')) beginPlayback('fast');
|
||
else if (!state.graceTimer) state.graceTimer = setTimeout(() => beginPlayback('grace'), GRACE_MS);
|
||
},
|
||
onProvider(pv) {
|
||
if (gen !== state.loadGen) return;
|
||
state.providers.set(pv.name, pv);
|
||
if (!state.providerNames.includes(pv.name)) state.providerNames.push(pv.name);
|
||
renderProviders();
|
||
},
|
||
onDone() {
|
||
if (gen !== state.loadGen) return;
|
||
state.done = true;
|
||
for (const [n, v] of state.providers) if (v.status === 'pending') state.providers.set(n, { status: 'timeout' });
|
||
renderProviders();
|
||
console.info(`[watch] sources done in ${Math.round(performance.now() - t0)}ms, ${state.ranked.length} playable`);
|
||
if (!state.started) beginPlayback('done');
|
||
else if (!state.current) tryNext();
|
||
},
|
||
onError(e) {
|
||
console.warn('[watch] streams error', e);
|
||
},
|
||
});
|
||
}
|
||
|
||
function beginPlayback(why) {
|
||
if (state.started || destroyed || isViewer()) return;
|
||
clearTimeout(state.graceTimer);
|
||
const first = state.ranked.find((s) => !state.failed.has(s.id));
|
||
if (!first) {
|
||
if (state.done) showNoSources();
|
||
return;
|
||
}
|
||
state.started = true;
|
||
state.eager = false;
|
||
console.info(`[watch] start (${why}) with`, first.provider, qualityLabel(first), kindOf(first));
|
||
const rec = resume.get(currentKey());
|
||
const startAt = rec && rec.t > 10 ? rec.t : 0;
|
||
playStream(first, startAt);
|
||
if (startAt > 10) toast(`Resuming at ${formatSeconds(startAt)}`);
|
||
}
|
||
|
||
function showNoSources() {
|
||
setPhase('error');
|
||
const failed = state.failed.size;
|
||
ldStatus.textContent = failed ? 'None of the sources would play.' : 'No sources found for this title.';
|
||
ldCount.textContent = failed ? `${failed} source${failed === 1 ? '' : 's'} failed` : '';
|
||
}
|
||
|
||
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 });
|
||
applyVolume();
|
||
renderSources();
|
||
renderMenus();
|
||
publishSoon();
|
||
}
|
||
|
||
function switchTo(s, reason) {
|
||
const t = player.currentTime();
|
||
playStream(s, t > 1 ? t : (resume.get(currentKey()) || {}).t || 0);
|
||
if (reason) toast(reason);
|
||
}
|
||
|
||
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;
|
||
if (state.done) {
|
||
showNoSources();
|
||
if (state.playingOnce) toast('No more sources to try', 'err');
|
||
} else {
|
||
setPhase(state.playingOnce ? 'buffering' : 'finding');
|
||
ldStatus.textContent = 'Waiting for more sources…';
|
||
state.started = false; // the next streams event restarts playback
|
||
state.eager = true;
|
||
}
|
||
return;
|
||
}
|
||
switchTo(next, msg ? `${msg} — trying ${next.provider} ${qualityLabel(next)}` : null);
|
||
}
|
||
|
||
/* ---- player --------------------------------------------------------------------- */
|
||
|
||
const player = createPlayer(video, {
|
||
onState(st) {
|
||
if (destroyed) return;
|
||
switch (st.phase) {
|
||
case 'playing':
|
||
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':
|
||
case 'loading':
|
||
case 'fallback':
|
||
if (state.playingOnce) setPhase('buffering');
|
||
else ldStatus.textContent = st.message || 'Loading…';
|
||
centerMsg.textContent = st.phase === 'fallback' ? 'Switching to relay…' : '';
|
||
break;
|
||
case 'torrent': {
|
||
if (state.playingOnce) setPhase('buffering');
|
||
ldStatus.textContent = st.message || 'Connecting to peers…';
|
||
break;
|
||
}
|
||
case 'ended':
|
||
resume.remove(currentKey());
|
||
if (isTv) showNextCard(true);
|
||
setPhase('paused');
|
||
publishSoon();
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
syncPlayIcon();
|
||
showControls();
|
||
},
|
||
onError(err) {
|
||
if (destroyed) return;
|
||
const s = err.stream || state.current;
|
||
if (s) state.failed.add(s.id);
|
||
console.warn('[watch] source failed', s && s.provider, err.code, err.message);
|
||
renderSources();
|
||
tryNext(`${(s && s.provider) || 'Source'} failed`);
|
||
},
|
||
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 = [];
|
||
if (st.peers != null) parts.push(`${st.peers} peer${st.peers === 1 ? '' : 's'}`);
|
||
if (st.downSpeed != null) parts.push(`${(st.downSpeed / 1e6).toFixed(1)} MB/s`);
|
||
if (st.progress != null) parts.push(`${Math.round(st.progress * 100)}%`);
|
||
const text = parts.join(' · ');
|
||
ldTorrent.hidden = !text;
|
||
ldTorrent.textContent = text;
|
||
if (state.playingOnce && el.dataset.phase === 'buffering') centerMsg.textContent = text;
|
||
},
|
||
});
|
||
|
||
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;
|
||
prefs.set('lastProvider', map);
|
||
}
|
||
// pick subtitles once per source
|
||
autoSubtitles();
|
||
}
|
||
|
||
/* ---- subtitles --------------------------------------------------------------- */
|
||
|
||
let subsAppliedFor = null;
|
||
let activeSub = -1;
|
||
function autoSubtitles() {
|
||
const s = state.current;
|
||
if (!s || subsAppliedFor === s.id) return;
|
||
subsAppliedFor = s.id;
|
||
const lang = String(prefs.get('subtitleLang', '') || '');
|
||
const list = player.subtitles();
|
||
activeSub = -1;
|
||
if (lang && lang !== 'off') {
|
||
const hit = list.find((x) => x.lang.toLowerCase().startsWith(lang.toLowerCase())) ||
|
||
list.find((x) => x.label.toLowerCase().startsWith(lang.toLowerCase()));
|
||
if (hit) activeSub = hit.index;
|
||
}
|
||
player.setSubtitle(activeSub);
|
||
renderMenus();
|
||
publishSoon();
|
||
}
|
||
|
||
function chooseSub(i, remember = true) {
|
||
activeSub = i;
|
||
player.setSubtitle(i).then((ok) => {
|
||
if (!ok) toast('Could not load subtitles', 'err');
|
||
});
|
||
if (remember) {
|
||
const sub = player.subtitles()[i];
|
||
prefs.set('subtitleLang', sub ? sub.lang || sub.label : '');
|
||
}
|
||
renderMenus();
|
||
publishSoon();
|
||
}
|
||
|
||
function toggleCc() {
|
||
const list = player.subtitles();
|
||
if (!list.length) return toast('No subtitles for this source');
|
||
if (activeSub >= 0) chooseSub(-1);
|
||
else {
|
||
const lang = String(prefs.get('subtitleLang', '') || 'en');
|
||
const hit = list.find((x) => x.lang.toLowerCase().startsWith(lang.toLowerCase())) || list[0];
|
||
chooseSub(hit.index);
|
||
}
|
||
toast(activeSub >= 0 ? `Subtitles: ${player.subtitles()[activeSub].label}` : 'Subtitles off');
|
||
}
|
||
|
||
function applySubSize() {
|
||
el.dataset.subsize = prefs.get('subtitleSize', 'm');
|
||
}
|
||
applySubSize();
|
||
|
||
/* ---- menus ----------------------------------------------------------------- */
|
||
|
||
let openMenu = null;
|
||
|
||
function menuItem(label, active, onClick, hint) {
|
||
const b = h('button.pl-menu__item', { type: 'button', role: 'menuitemradio', 'aria-checked': String(!!active) });
|
||
b.appendChild(h('span.pl-menu__check', active ? icon('check') : null));
|
||
b.appendChild(h('span.pl-menu__label', label));
|
||
if (hint) b.appendChild(h('span.pl-menu__hint', hint));
|
||
b.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
onClick();
|
||
});
|
||
return b;
|
||
}
|
||
|
||
function renderMenus() {
|
||
const subs = player.subtitles();
|
||
ccBtn.classList.toggle('is-on', activeSub >= 0);
|
||
ccBtn.classList.toggle('is-dim', !subs.length);
|
||
if (!openMenu) return;
|
||
menu.replaceChildren();
|
||
if (openMenu === 'cc') {
|
||
menu.appendChild(h('div.pl-menu__head', 'Subtitles'));
|
||
menu.appendChild(menuItem('Off', activeSub < 0, () => chooseSub(-1)));
|
||
if (!subs.length) menu.appendChild(h('div.pl-menu__empty', 'This source has no subtitles'));
|
||
for (const s of subs) menu.appendChild(menuItem(s.label, s.index === activeSub, () => chooseSub(s.index), s.lang && !s.label.toLowerCase().includes(s.lang.toLowerCase()) ? s.lang : ''));
|
||
menu.appendChild(h('div.pl-menu__head', 'Size'));
|
||
const size = prefs.get('subtitleSize', 'm');
|
||
const row = h('div.pl-menu__seg');
|
||
for (const [k, label] of [['s', 'Small'], ['m', 'Medium'], ['l', 'Large'], ['xl', 'Huge']]) {
|
||
const b = h(`button.pl-seg${k === size ? '.is-on' : ''}`, { type: 'button' }, label);
|
||
b.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
prefs.set('subtitleSize', k);
|
||
applySubSize();
|
||
renderMenus();
|
||
});
|
||
row.appendChild(b);
|
||
}
|
||
menu.appendChild(row);
|
||
} else if (openMenu === 'gear') {
|
||
const levels = player.levels();
|
||
const cur = player.currentLevel();
|
||
menu.appendChild(h('div.pl-menu__head', 'Quality'));
|
||
if (levels.length) {
|
||
const playing = player.playingLevel();
|
||
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, () => 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'));
|
||
}
|
||
const tracks = player.audioTracks();
|
||
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), 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');
|
||
for (const r of [0.75, 1, 1.25, 1.5, 2]) {
|
||
const b = h(`button.pl-seg${video.playbackRate === r ? '.is-on' : ''}`, { type: 'button' }, `${r}×`);
|
||
b.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
video.playbackRate = r;
|
||
renderMenus();
|
||
});
|
||
seg.appendChild(b);
|
||
}
|
||
menu.appendChild(seg);
|
||
}
|
||
}
|
||
|
||
// 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();
|
||
openMenu = name;
|
||
menu.hidden = false;
|
||
renderMenus();
|
||
const r = anchor.getBoundingClientRect();
|
||
const host = el.getBoundingClientRect();
|
||
menu.style.right = `${Math.max(12, host.right - r.right - 40)}px`;
|
||
requestAnimationFrame(() => menu.classList.add('is-in'));
|
||
showControls();
|
||
}
|
||
|
||
function closeMenu() {
|
||
openMenu = null;
|
||
menu.classList.remove('is-in');
|
||
menu.hidden = true;
|
||
}
|
||
|
||
/* ---- panels ------------------------------------------------------------------ */
|
||
|
||
let openPanel = null;
|
||
function togglePanel(name) {
|
||
if (openPanel === name) return closePanels();
|
||
closeMenu();
|
||
closePanels();
|
||
openPanel = name;
|
||
const p = name === 'sources' ? srcPanel : epPanel;
|
||
p.classList.add('is-open');
|
||
el.classList.add('has-panel');
|
||
if (name === 'episodes') renderEpisodesPanel(state.browseSeason || state.season);
|
||
showControls();
|
||
}
|
||
function closePanels() {
|
||
openPanel = null;
|
||
srcPanel.classList.remove('is-open');
|
||
epPanel.classList.remove('is-open');
|
||
el.classList.remove('has-panel');
|
||
}
|
||
ldPick.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
togglePanel('sources');
|
||
});
|
||
|
||
function renderProviders() {
|
||
const names = state.providerNames.length ? state.providerNames : [...state.providers.keys()];
|
||
const total = names.length;
|
||
let finished = 0;
|
||
for (const n of names) {
|
||
const v = state.providers.get(n);
|
||
if (v && v.status && v.status !== 'pending') finished++;
|
||
}
|
||
const playable = state.ranked.length;
|
||
ldCount.textContent = total
|
||
? `${finished}/${total} providers · ${playable} source${playable === 1 ? '' : 's'}`
|
||
: 'Contacting server…';
|
||
ldBar.firstChild.style.width = total ? `${(finished / total) * 100}%` : '6%';
|
||
srcHead.textContent = total ? `${finished}/${total} providers${state.done ? '' : ' · searching…'}` : '';
|
||
|
||
const order = { ok: 0, pending: 1, empty: 2, timeout: 3, error: 4 };
|
||
const sorted = names
|
||
.map((n) => ({ n, v: state.providers.get(n) || { status: 'pending' } }))
|
||
.sort((a, b) => (order[a.v.status] ?? 5) - (order[b.v.status] ?? 5) || (a.v.ms || 0) - (b.v.ms || 0));
|
||
const mk = ({ n, v }) =>
|
||
h(
|
||
`li.pl-prov.pl-prov--${v.status || 'pending'}`,
|
||
{ title: v.error || '' },
|
||
h('span.pl-prov__dot'),
|
||
h('span.pl-prov__name', n),
|
||
v.status === 'ok' && v.count ? h('span.pl-prov__count', String(v.count)) : null,
|
||
h('span.pl-prov__ms', v.status === 'pending' ? '…' : v.ms != null ? `${v.ms < 1000 ? `${v.ms}ms` : `${(v.ms / 1000).toFixed(1)}s`}` : v.status),
|
||
);
|
||
ldTicker.replaceChildren(...sorted.slice(0, 14).map(mk));
|
||
provList.replaceChildren(...sorted.map(mk));
|
||
}
|
||
|
||
function renderSources() {
|
||
const list = state.ranked;
|
||
srcCount.textContent = list.length ? String(list.length) : '';
|
||
srcBtn.classList.toggle('is-searching', !state.done);
|
||
if (!list.length) {
|
||
srcList.replaceChildren(h('div.pl-panel__empty', state.done ? 'No playable sources.' : 'Searching providers…'));
|
||
renderProviders();
|
||
return;
|
||
}
|
||
const items = list.map((s) => {
|
||
const current = state.current && s.id === state.current.id;
|
||
const failed = state.failed.has(s.id);
|
||
const badges = [
|
||
h(`span.pl-badge.pl-badge--q${(s.pixels || 0) >= 2160 ? '.is-4k' : (s.pixels || 0) >= 1080 ? '.is-hd' : ''}`, qualityLabel(s)),
|
||
h(`span.pl-badge.pl-badge--${kindOf(s)}`, kindBadge(s)),
|
||
];
|
||
const size = fmtSize(s);
|
||
if (size) badges.push(h('span.pl-badge', size));
|
||
if (s.audio) badges.push(h('span.pl-badge', String(s.audio).toUpperCase()));
|
||
if (s.language) badges.push(h('span.pl-badge', s.language));
|
||
if (s.subtitles && s.subtitles.length) badges.push(h('span.pl-badge', `CC ${s.subtitles.length}`));
|
||
if (s.playback && s.playback.fallback) badges.push(h('span.pl-badge.pl-badge--direct', 'Direct'));
|
||
if (failed) badges.push(h('span.pl-badge.pl-badge--fail', 'Failed'));
|
||
const b = h(
|
||
`button.pl-source${current ? '.is-current' : ''}${failed ? '.is-failed' : ''}`,
|
||
{ type: 'button' },
|
||
h('div.pl-source__top', h('span.pl-source__prov', s.provider || 'unknown'), current ? h('span.pl-source__now', 'Playing') : null),
|
||
h('div.pl-source__name', sourceName(s)),
|
||
h('div.pl-source__badges', badges),
|
||
);
|
||
b.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
state.failed.delete(s.id);
|
||
state.started = true;
|
||
switchTo(s, `Switching to ${s.provider} ${qualityLabel(s)}`);
|
||
closePanels();
|
||
});
|
||
return b;
|
||
});
|
||
srcList.replaceChildren(...items);
|
||
renderProviders();
|
||
}
|
||
|
||
async function renderEpisodesPanel(n) {
|
||
if (!isTv) return;
|
||
const seasons = seasonList();
|
||
state.browseSeason = n;
|
||
epSelect.replaceChildren(
|
||
...(seasons.length ? seasons : [{ season_number: n, name: `Season ${n}` }]).map((s) =>
|
||
h('option', { value: String(s.season_number), selected: s.season_number === n }, s.name || `Season ${s.season_number}`),
|
||
),
|
||
);
|
||
if (openPanel !== 'episodes' && n !== state.season) return;
|
||
const data = await fetchSeason(n);
|
||
if (destroyed || state.browseSeason !== n) return;
|
||
const eps = ((data && data.episodes) || []).slice().sort((a, b) => a.episode_number - b.episode_number);
|
||
if (!eps.length) {
|
||
epList.replaceChildren(h('div.pl-panel__empty', 'No episodes listed'));
|
||
return;
|
||
}
|
||
let currentEl = null;
|
||
const items = eps.map((ep) => {
|
||
const current = n === state.season && ep.episode_number === state.episode;
|
||
const rec = resume.get(keyFor({ type, tmdbId: Number(id), season: n, episode: ep.episode_number }));
|
||
const pct = rec && rec.d ? Math.min(100, (rec.t / rec.d) * 100) : 0;
|
||
const still = ep.still_path ? tmdb.img(ep.still_path, 'w300') : '';
|
||
const b = h(
|
||
`button.pl-ep${current ? '.is-current' : ''}`,
|
||
{ type: 'button' },
|
||
h(
|
||
'div.pl-ep__thumb',
|
||
still ? h('img', { src: still, alt: '', loading: 'lazy' }) : h('span', String(ep.episode_number)),
|
||
pct > 0 ? h('div.pl-ep__prog', h('span', { style: { width: `${pct}%` } })) : null,
|
||
current ? h('div.pl-ep__now', 'Now playing') : null,
|
||
),
|
||
h(
|
||
'div.pl-ep__body',
|
||
h('div.pl-ep__num', `E${ep.episode_number}${ep.runtime ? ` · ${ep.runtime}m` : ''}`),
|
||
h('div.pl-ep__name', ep.name || `Episode ${ep.episode_number}`),
|
||
ep.overview ? h('div.pl-ep__ov', ep.overview) : null,
|
||
),
|
||
);
|
||
b.addEventListener('click', (e) => {
|
||
e.stopPropagation();
|
||
closePanels();
|
||
if (!current) switchEpisode(n, ep.episode_number);
|
||
});
|
||
if (current) currentEl = b;
|
||
return b;
|
||
});
|
||
epList.replaceChildren(...items);
|
||
if (currentEl) {
|
||
// not scrollIntoView: that would also scroll the (clipped) player root
|
||
requestAnimationFrame(() => {
|
||
epList.scrollTop = Math.max(0, currentEl.offsetTop - epList.offsetTop - epList.clientHeight / 2 + currentEl.offsetHeight / 2);
|
||
});
|
||
}
|
||
}
|
||
epSelect.addEventListener('change', () => renderEpisodesPanel(Number(epSelect.value)));
|
||
epSelect.addEventListener('click', (e) => e.stopPropagation());
|
||
|
||
/* ---- episodes switching -------------------------------------------------- */
|
||
|
||
async function switchEpisode(season, episode) {
|
||
persistProgress(true);
|
||
hideNextCard();
|
||
state.nextDismissed = false;
|
||
state.prefetched = false;
|
||
state.playingOnce = false;
|
||
subsAppliedFor = null;
|
||
player.stop();
|
||
state.season = season;
|
||
state.episode = episode;
|
||
const qs = params.query && String(params.query);
|
||
replaceUrl(watchPath(type, id, season, episode) + (qs ? `?${qs}` : ''));
|
||
setPhase('finding');
|
||
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);
|
||
renderTitles();
|
||
}
|
||
renderNextButton();
|
||
}
|
||
|
||
/* ---- resume persistence (v4 semantics) ------------------------------------ */
|
||
|
||
function currentKey() {
|
||
return keyFor({ type, tmdbId: Number(id), season: state.season, episode: state.episode });
|
||
}
|
||
|
||
function persistProgress(force) {
|
||
if (!state.current || !state.playingOnce) return;
|
||
const d = player.duration();
|
||
if (!d || !isFinite(d)) return;
|
||
const t = player.currentTime();
|
||
if (t < 10) return;
|
||
const key = currentKey();
|
||
if (t >= d - 15 || t / d >= 0.95) {
|
||
resume.remove(key);
|
||
return;
|
||
}
|
||
const now = Date.now();
|
||
if (!force && now - state.lastPersist < 3000) return;
|
||
state.lastPersist = now;
|
||
const det = state.details;
|
||
const ep = isTv ? episodeObj(state.episode) : null;
|
||
resume.save({
|
||
key,
|
||
type,
|
||
tmdbId: Number(id),
|
||
season: isTv ? state.season : undefined,
|
||
episode: isTv ? state.episode : undefined,
|
||
show: det ? det.name || det.title || '' : '',
|
||
title: ep ? ep.name || '' : '',
|
||
poster: det && det.poster_path ? tmdb.img(det.poster_path, 'w342') : '',
|
||
backdrop: det && det.backdrop_path ? tmdb.img(det.backdrop_path, 'w780') : '',
|
||
still: ep && ep.still_path ? tmdb.img(ep.still_path, 'w300') : undefined,
|
||
t,
|
||
d,
|
||
at: now,
|
||
provider: state.current ? state.current.provider : '',
|
||
});
|
||
}
|
||
|
||
function onProgress() {
|
||
persistProgress(false);
|
||
if (!isTv) return;
|
||
const d = player.duration();
|
||
const t = player.currentTime();
|
||
if (!d) return;
|
||
if (!state.prefetched && t / d >= 0.8) {
|
||
state.prefetched = true;
|
||
const n = nextEpisodeRef();
|
||
if (n) api.prefetch({ tmdb: id, type, season: n.season, episode: n.episode });
|
||
}
|
||
if (d - t <= CREDITS_SEC && d > 120 && !video.paused) showNextCard(false);
|
||
}
|
||
|
||
listen(video, 'timeupdate', onProgress);
|
||
listen(video, 'pause', () => persistProgress(true));
|
||
listen(video, 'seeked', () => persistProgress(true));
|
||
listen(window, 'pagehide', () => persistProgress(true));
|
||
listen(document, 'visibilitychange', () => {
|
||
if (document.hidden) persistProgress(true);
|
||
});
|
||
|
||
/* ---- transport UI ------------------------------------------------------------ */
|
||
|
||
let scrubbing = false;
|
||
let scrubT = 0;
|
||
|
||
function syncPlayIcon() {
|
||
const playing = !video.paused && !video.ended;
|
||
setIcon(playBtn, playing ? 'pause' : 'play');
|
||
playBtn.setAttribute('aria-label', playing ? 'Pause (k)' : 'Play (k)');
|
||
setIcon(bigPlay, 'play');
|
||
}
|
||
|
||
function paintTime() {
|
||
const d = player.duration();
|
||
const t = scrubbing ? scrubT : player.currentTime();
|
||
timeEl.textContent = d ? `${formatSeconds(t)} / ${formatSeconds(d)}` : formatSeconds(t);
|
||
const pct = d ? Math.min(100, (t / d) * 100) : 0;
|
||
seekFill.style.width = `${pct}%`;
|
||
seekThumb.style.left = `${pct}%`;
|
||
seek.setAttribute('aria-valuenow', String(Math.floor(t)));
|
||
seek.setAttribute('aria-valuemax', String(Math.floor(d || 0)));
|
||
seek.setAttribute('aria-valuetext', formatSeconds(t));
|
||
if (d) {
|
||
const ranges = player.buffered();
|
||
const tt = player.currentTime();
|
||
const r = ranges.find(([a, b]) => tt >= a - 1 && tt <= b + 1) || ranges[ranges.length - 1];
|
||
if (r) {
|
||
seekBuf.style.left = `${(r[0] / d) * 100}%`;
|
||
seekBuf.style.width = `${Math.max(0, ((r[1] - r[0]) / d) * 100)}%`;
|
||
} else seekBuf.style.width = '0';
|
||
}
|
||
}
|
||
const tick = setInterval(() => {
|
||
if (!document.hidden) paintTime();
|
||
}, 250);
|
||
disposers.push(() => clearInterval(tick));
|
||
|
||
function seekRatio(clientX) {
|
||
const r = seek.getBoundingClientRect();
|
||
return Math.min(1, Math.max(0, (clientX - r.left) / r.width));
|
||
}
|
||
|
||
listen(seek, 'pointermove', (e) => {
|
||
const d = player.duration();
|
||
if (!d) return;
|
||
const ratio = seekRatio(e.clientX);
|
||
seekTip.textContent = formatSeconds(ratio * d);
|
||
seekTip.style.left = `${ratio * 100}%`;
|
||
seekHover.style.width = `${ratio * 100}%`;
|
||
seek.classList.add('is-hover');
|
||
if (scrubbing) {
|
||
scrubT = ratio * d;
|
||
paintTime();
|
||
}
|
||
});
|
||
listen(seek, 'pointerleave', () => !scrubbing && seek.classList.remove('is-hover'));
|
||
listen(seek, 'pointerdown', (e) => {
|
||
const d = player.duration();
|
||
if (!d) return;
|
||
e.stopPropagation();
|
||
scrubbing = true;
|
||
seek.classList.add('is-scrub');
|
||
seek.setPointerCapture(e.pointerId);
|
||
scrubT = seekRatio(e.clientX) * d;
|
||
paintTime();
|
||
});
|
||
const endScrub = (e) => {
|
||
if (!scrubbing) return;
|
||
scrubbing = false;
|
||
seek.classList.remove('is-scrub', 'is-hover');
|
||
const d = player.duration();
|
||
if (d && e.type === 'pointerup' && !isViewer()) {
|
||
player.seek(seekRatio(e.clientX) * d);
|
||
publishSoon();
|
||
}
|
||
paintTime();
|
||
};
|
||
listen(seek, 'pointerup', endScrub);
|
||
listen(seek, 'pointercancel', endScrub);
|
||
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();
|
||
}
|
||
|
||
/* ---- volume ------------------------------------------------------------------ */
|
||
|
||
function applyVolume() {
|
||
const v = Number(prefs.get('volume', 1));
|
||
video.volume = isFinite(v) ? Math.min(1, Math.max(0, v)) : 1;
|
||
video.muted = !!prefs.get('muted', false);
|
||
paintVolume();
|
||
}
|
||
function paintVolume() {
|
||
const v = video.muted ? 0 : video.volume;
|
||
volFill.style.width = `${v * 100}%`;
|
||
vol.setAttribute('aria-valuenow', String(Math.round(v * 100)));
|
||
setIcon(muteBtn, v === 0 ? 'mute' : v < 0.5 ? 'volLow' : 'vol');
|
||
}
|
||
function setVolume(v) {
|
||
v = Math.min(1, Math.max(0, v));
|
||
video.volume = v;
|
||
video.muted = v === 0;
|
||
prefs.set('volume', Math.round(v * 100) / 100);
|
||
prefs.set('muted', video.muted);
|
||
paintVolume();
|
||
}
|
||
function setMuted(m) {
|
||
video.muted = m;
|
||
if (!m && video.volume === 0) video.volume = 0.5;
|
||
prefs.set('muted', m);
|
||
paintVolume();
|
||
}
|
||
let volDrag = false;
|
||
const volAt = (e) => {
|
||
const r = vol.getBoundingClientRect();
|
||
setVolume((e.clientX - r.left) / r.width);
|
||
};
|
||
listen(vol, 'pointerdown', (e) => {
|
||
e.stopPropagation();
|
||
volDrag = true;
|
||
vol.setPointerCapture(e.pointerId);
|
||
volAt(e);
|
||
});
|
||
listen(vol, 'pointermove', (e) => volDrag && volAt(e));
|
||
listen(vol, 'pointerup', () => (volDrag = false));
|
||
listen(vol, 'click', (e) => e.stopPropagation());
|
||
listen(video, 'volumechange', paintVolume);
|
||
applyVolume();
|
||
|
||
/* ---- fullscreen / pip ------------------------------------------------------------ */
|
||
|
||
function isFull() {
|
||
return !!(document.fullscreenElement || document.webkitFullscreenElement);
|
||
}
|
||
function toggleFullscreen() {
|
||
if (isFull()) (document.exitFullscreen || document.webkitExitFullscreen).call(document);
|
||
else if (el.requestFullscreen) el.requestFullscreen().catch(() => {});
|
||
else if (el.webkitRequestFullscreen) el.webkitRequestFullscreen();
|
||
else if (video.webkitEnterFullscreen) video.webkitEnterFullscreen();
|
||
}
|
||
listen(document, 'fullscreenchange', () => setIcon(fullBtn, isFull() ? 'unfull' : 'full'));
|
||
function togglePip() {
|
||
if (document.pictureInPictureElement) document.exitPictureInPicture().catch(() => {});
|
||
else video.requestPictureInPicture().catch(() => toast('Picture-in-picture unavailable', 'err'));
|
||
}
|
||
|
||
/* ---- controls visibility / gestures ---------------------------------------------- */
|
||
|
||
let hideTimer = null;
|
||
// lift subtitle cues above the control bar while it is visible
|
||
function liftCues(up) {
|
||
for (const t of Array.from(video.textTracks)) {
|
||
if (t.mode !== 'showing' || !t.cues) continue;
|
||
for (const c of Array.from(t.cues)) {
|
||
try {
|
||
c.line = up ? -4 : 'auto';
|
||
} catch (e) {
|
||
/* ignore */
|
||
}
|
||
}
|
||
}
|
||
}
|
||
function setUi(on) {
|
||
if (el.classList.contains('show-ui') === on) return;
|
||
el.classList.toggle('show-ui', on);
|
||
liftCues(on);
|
||
}
|
||
listen(video.textTracks, 'change', () => liftCues(el.classList.contains('show-ui')));
|
||
function showControls() {
|
||
setUi(true);
|
||
clearTimeout(hideTimer);
|
||
hideTimer = setTimeout(() => {
|
||
if (!video.paused && !scrubbing && !openMenu && !openPanel) setUi(false);
|
||
}, CONTROLS_HIDE_MS);
|
||
}
|
||
function hideControls() {
|
||
if (video.paused || openMenu || openPanel) return;
|
||
clearTimeout(hideTimer);
|
||
setUi(false);
|
||
}
|
||
disposers.push(() => clearTimeout(hideTimer));
|
||
listen(el, 'pointermove', (e) => e.pointerType !== 'touch' && showControls());
|
||
listen(el, 'mouseleave', () => hideControls());
|
||
|
||
function ripple(side) {
|
||
const r = side < 0 ? rippleL : rippleR;
|
||
r.classList.remove('is-on');
|
||
void r.offsetWidth;
|
||
r.classList.add('is-on');
|
||
}
|
||
|
||
// Surface taps: video, scrim and the center layer.
|
||
let clickTimer = null;
|
||
let lastTap = 0;
|
||
function onSurface(e) {
|
||
if (e.target.closest('.pl-btn, .pl-bottom, .pl-top, .pl-menu, .pl-panel, .pl-nextcard, .pl-load button')) return;
|
||
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();
|
||
const x = (e.clientX - r.left) / r.width;
|
||
if (touch) {
|
||
if (now - lastTap < 300) {
|
||
clearTimeout(clickTimer);
|
||
lastTap = 0;
|
||
if (x < 0.35) {
|
||
skip(-10);
|
||
ripple(-1);
|
||
} else if (x > 0.65) {
|
||
skip(10);
|
||
ripple(1);
|
||
} else toggleFullscreen();
|
||
return;
|
||
}
|
||
lastTap = now;
|
||
clickTimer = setTimeout(() => {
|
||
if (el.classList.contains('show-ui')) hideControls();
|
||
else showControls();
|
||
}, 280);
|
||
return;
|
||
}
|
||
clearTimeout(clickTimer);
|
||
clickTimer = setTimeout(() => {
|
||
player.toggle();
|
||
showControls();
|
||
}, 220);
|
||
}
|
||
listen(el, 'click', onSurface);
|
||
listen(el, 'dblclick', (e) => {
|
||
if (e.target.closest('.pl-btn, .pl-bottom, .pl-top, .pl-menu, .pl-panel, .pl-nextcard')) return;
|
||
clearTimeout(clickTimer);
|
||
toggleFullscreen();
|
||
});
|
||
disposers.push(() => clearTimeout(clickTimer));
|
||
|
||
/* ---- keyboard ------------------------------------------------------------------ */
|
||
|
||
function onKey(e) {
|
||
if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return;
|
||
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();
|
||
};
|
||
switch (k) {
|
||
case ' ':
|
||
case 'k':
|
||
case 'K':
|
||
if (tag === 'button' && k === ' ') return;
|
||
handled();
|
||
player.toggle();
|
||
break;
|
||
case 'j':
|
||
case 'J':
|
||
handled();
|
||
skip(-10);
|
||
ripple(-1);
|
||
break;
|
||
case 'l':
|
||
case 'L':
|
||
handled();
|
||
skip(10);
|
||
ripple(1);
|
||
break;
|
||
case 'ArrowLeft':
|
||
handled();
|
||
skip(-5);
|
||
break;
|
||
case 'ArrowRight':
|
||
handled();
|
||
skip(5);
|
||
break;
|
||
case 'ArrowUp':
|
||
handled();
|
||
setVolume((video.muted ? 0 : video.volume) + 0.05);
|
||
break;
|
||
case 'ArrowDown':
|
||
handled();
|
||
setVolume((video.muted ? 0 : video.volume) - 0.05);
|
||
break;
|
||
case 'm':
|
||
case 'M':
|
||
handled();
|
||
setMuted(!video.muted);
|
||
break;
|
||
case 'f':
|
||
case 'F':
|
||
handled();
|
||
toggleFullscreen();
|
||
break;
|
||
case 'c':
|
||
case 'C':
|
||
handled();
|
||
toggleCc();
|
||
break;
|
||
case 'n':
|
||
case 'N':
|
||
if (!isTv) return;
|
||
handled();
|
||
playNext();
|
||
break;
|
||
case 'Escape':
|
||
if (openMenu) {
|
||
e.preventDefault();
|
||
closeMenu();
|
||
} else if (openPanel) {
|
||
e.preventDefault();
|
||
closePanels();
|
||
} else if (!nextCard.hidden) {
|
||
e.preventDefault();
|
||
state.nextDismissed = true;
|
||
hideNextCard();
|
||
} else if (!isFull()) {
|
||
e.preventDefault();
|
||
goBack();
|
||
}
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
}
|
||
listen(document, 'keydown', onKey);
|
||
|
||
/* ---- back ------------------------------------------------------------------ */
|
||
|
||
function goBack() {
|
||
if (isViewer()) return;
|
||
persistProgress(true);
|
||
if (isFull()) {
|
||
try {
|
||
(document.exitFullscreen || document.webkitExitFullscreen).call(document);
|
||
} catch (e) {
|
||
/* ignore */
|
||
}
|
||
}
|
||
const fallback = `/title/${type}/${id}`;
|
||
if (typeof router.back === 'function') router.back(fallback);
|
||
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();
|
||
showControls();
|
||
if (!id) {
|
||
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;
|
||
const s = Number(p.season) || 1;
|
||
const e = Number(p.episode) || 1;
|
||
if (s !== state.season || e !== state.episode) switchEpisode(s, e);
|
||
return true;
|
||
},
|
||
};
|
||
activeView = view;
|
||
|
||
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);
|
||
clearInterval(state.nextTimer);
|
||
player.destroy();
|
||
for (const d of disposers) d();
|
||
try {
|
||
video.pause();
|
||
} catch (e) {
|
||
/* ignore */
|
||
}
|
||
if (document.pictureInPictureElement === video) document.exitPictureInPicture().catch(() => {});
|
||
if (isFull()) document.exitFullscreen().catch(() => {});
|
||
};
|
||
}
|