Compare commits
2
Commits
v5
...
ee0e36d2c7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee0e36d2c7 | ||
|
|
5ab3683f44 |
No files matched your search
+35
@@ -221,3 +221,38 @@ Player workstream owns `web/js/api.js` (bug-tv server client: `streams(params, {
|
||||
- `/v1/remux/<token>/probe?start=<sec>` and `/v1/torrent/<token>/probe?start=<sec>` add `keyframe`: the time the remux really starts at. The player uses it as its clock offset because a `<video>` element can't read `X-Bug-Tv-Offset`.
|
||||
- Extensionless stream URLs are sniffed by their first 1 KB (`src/media/sniff.js`) and typed m3u8/mp4/webm/mkv before `playbackFor` runs.
|
||||
- The Swagger UI moved to `src/public/index.html`, `mod/` and `rest/` are removed, and webtorrent is bumped to ^3.0.21.
|
||||
|
||||
## Party (watch-together hooks)
|
||||
`web/js/party.js` is inert unless a transport attaches, so the public site is unaffected. tv-discord's Activity overlay is the transport.
|
||||
|
||||
```js
|
||||
import { party } from './party.js'; // also exposed as window.bugtvParty (dispatches 'bugtv:party-ready')
|
||||
party.mode // 'solo' | 'host' | 'viewer'
|
||||
party.attach(transport) // transport = { send(type, data) }; the transport then calls:
|
||||
party.receive(msg) // feed server messages: welcome / host / members / route / play / pong
|
||||
party.now() // server-synced ms (falls back to Date.now())
|
||||
party.publish(type, data) // host only: 'route' {path} | 'play' {snapshot}
|
||||
party.on(type, fn) → off // 'mode' | 'members' | 'route' | 'play'
|
||||
```
|
||||
- **Router:** in host mode, every route change publishes `route`. In viewer mode, an incoming `route` calls `navigate(path, {replace:true})`.
|
||||
- **Watch view, host:** publishes a `play` snapshot on load/source/subtitle/quality/audio/episode change, play/pause/seeked/ended, and every 2s while on the watch route. The snapshot shape is in tv-discord `docs/protocol.md`.
|
||||
- **Watch view, viewer:**
|
||||
- Never scrapes. It loads `snapshot.stream` directly through `playStream` and follows the clock: over 1.5s drift it seeks, and at 0.3–1.5s it sets `playbackRate` to 0.95/1.05.
|
||||
- It applies the subtitle (by lang+label, index as fallback), the quality and the audio track.
|
||||
- It hides every control except volume, mute and fullscreen.
|
||||
- **Player:** `createPlayer(video, { forceProxy })`, or `<meta name="bug-tv-force-proxy" content="1">`, always plays `playback.fallback` when present. This is needed because the Activity CSP only allows mapped origins.
|
||||
- **TMDB bases:** `<meta name="bug-tv-tmdb">` (API base) and `<meta name="bug-tv-img">` (image base) override `https://api.themoviedb.org/3` and `https://image.tmdb.org/t/p/`. In the Activity they are `/tmdb/3` and `/img/t/p/`.
|
||||
- **Party mode** (`party.mode !== 'solo'`) hides the trailer button, because the YouTube iframe can't be mapped.
|
||||
|
||||
### Deviations / details (party layer)
|
||||
- **Wire shape:** party calls `transport.send(type, data)` with `('route', {path})`, `('play', {snapshot})` (`{snapshot: null}` when the host leaves the watch page) and `('ping', {at})`; the transport sends `{t: type, ...data}`. party pings by itself (5× at 1s, then every 15s) and takes the median of the last 5 pong offsets; `welcome.now` seeds the offset before the first pong.
|
||||
- **Extra API:** `party.resend()` (host: re-publish current route + snapshot, for the overlay after a reconnect; emits `'resend'`), `party.lastRoute` / `party.lastPlay`, `party.hostName()`, `attach()` returns a detach function. `on('error')` relays server errors. A `welcome.play` whose path differs from `welcome.route` is ignored.
|
||||
- **Route privacy:** host route messages drop session params (`api`, `frame_id`, `instance_id`, `platform`, `guild_id`, `channel_id`, …); viewers keep their own.
|
||||
- **Viewer UI:** controls other than volume/mute/fullscreen/PiP get `.pl-host-only` and are hidden under `.pl.is-viewer`; the seek bar stays visible but inert. Those controls and the autoplay fallback button `.pl-join` ("Click to join", local playback only) carry `data-party-allow` for the overlay's input blocking. Viewers never auto-advance to the next episode; a viewer-side source failure shows "Waiting for <host>…" and the next heartbeat reloads the host's stream.
|
||||
- **Drift:** paused snapshots seek when |drift| > 0.5s; hls/file seeks are rate-limited to 1 per 1.5s, remux to 1 per 3s; a viewer stuck seeking/buffering for 5s (12s remux) is re-seeked. Playback speed is not mirrored.
|
||||
- **Quality:** `snapshot.quality` is the host's explicit menu pick (`chooseLevel`), reset to auto on source change, not hls.js's momentary level.
|
||||
- **Watch handle:** `views/watch.js` exports `active()` → `{player, state, snapshot(), playStream, switchTo, switchEpisode, chooseSub, chooseLevel, role}` for tooling/tests.
|
||||
- **Player:** `player.original` is the Stream passed to `load()`; `player.stream` is the proxied copy under forceProxy. `proxiedStream(s)` is exported.
|
||||
- **API base:** a relative `bug-tv-api` / `?api=` / stored base such as `/tv` resolves against `location.origin` (it used to become `https://tv`).
|
||||
- **Trailer:** hidden by CSS (`html.party-host|party-viewer .js-trailer`), and `trailerModal()` is a no-op outside solo.
|
||||
- **Tests:** `node --test web/test/party.test.mjs`.
|
||||
@@ -25,6 +25,7 @@ stdenvNoCC.mkDerivation {
|
||||
|
||||
cp -r . $out
|
||||
chmod -R u+w $out
|
||||
rm -rf $out/test # node tests for the party layer, not part of the site
|
||||
# no-op on pages without the tag
|
||||
for page in $out/*.html; do
|
||||
sed -i -E ${lib.escapeShellArg sedExpr} "$page"
|
||||
|
||||
@@ -196,3 +196,9 @@
|
||||
.provider-grid { grid-template-columns: 1fr; }
|
||||
.input--sm { max-width: none; flex: 1; }
|
||||
}
|
||||
|
||||
/* watch party: the YouTube trailer iframe can't be mapped inside the Discord Activity */
|
||||
html.party-host .js-trailer,
|
||||
html.party-viewer .js-trailer {
|
||||
display: none !important;
|
||||
}
|
||||
@@ -1290,3 +1290,45 @@ html.pl-open body {
|
||||
from { transform: scaleX(0); }
|
||||
to { transform: scaleX(1); }
|
||||
}
|
||||
|
||||
/* ---- watch party: viewer mode (party.js) ---------------------------------------------- */
|
||||
/* Viewers follow the host: only volume, mute, fullscreen and PiP stay usable. */
|
||||
|
||||
.pl.is-viewer .pl-host-only,
|
||||
.pl.is-viewer .pl-load__count,
|
||||
.pl.is-viewer .pl-load__bar,
|
||||
.pl.is-viewer .pl-load__ticker {
|
||||
display: none !important;
|
||||
}
|
||||
.pl.is-viewer .pl-seek {
|
||||
pointer-events: none;
|
||||
}
|
||||
.pl.is-viewer .pl-seek__thumb,
|
||||
.pl.is-viewer .pl-seek__tip,
|
||||
.pl.is-viewer .pl-seek__hover {
|
||||
display: none;
|
||||
}
|
||||
.pl-join {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 14px 26px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: var(--pl-accent);
|
||||
color: #000;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
pointer-events: auto;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.45);
|
||||
z-index: 1;
|
||||
}
|
||||
.pl-join[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.pl-join .pl-ico {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
import { h, debounce } from './util.js';
|
||||
import { getBase } from './config.js';
|
||||
import './party.js'; // window.bugtvParty for the watch-party overlay
|
||||
import { start, navigate, href, onChange, current } from './router.js';
|
||||
import { toast } from './ui/toast.js';
|
||||
import { icon } from './ui/icons.js';
|
||||
|
||||
@@ -24,6 +24,11 @@ export const TMDB_KEY_STORAGE_KEY = 'bug-tv.tmdbKey.v1';
|
||||
function normalize(value) {
|
||||
let v = String(value || '').trim();
|
||||
if (!v) return '';
|
||||
// "/tv" (Discord Activity URL mapping): same-origin path
|
||||
if (v.startsWith('/') && !v.startsWith('//')) {
|
||||
const origin = typeof location !== 'undefined' && /^https?:$/.test(location.protocol) ? location.origin : '';
|
||||
return (origin + v).replace(/\/+$/, '');
|
||||
}
|
||||
if (!/^https?:\/\//i.test(v)) v = `${/^(localhost|127\.|\[::1\])/.test(v) ? 'http' : 'https'}://${v}`;
|
||||
return v.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
/*
|
||||
party.js — watch-together hooks (docs/api.md "Party"). Inert ('solo') until a
|
||||
transport attaches and the server says who is host; the public site never
|
||||
attaches one.
|
||||
|
||||
import { party } from './party.js' also window.bugtvParty, plus a
|
||||
'bugtv:party-ready' window event
|
||||
|
||||
party.mode 'solo' | 'host' | 'viewer'
|
||||
party.me / host user ids (from welcome / host messages)
|
||||
party.members [{id, username, avatar}]
|
||||
party.attach(transport) transport = { send(type, data) } → detach()
|
||||
party sends: 'route' {path}, 'play' {snapshot}, 'ping' {at}
|
||||
(the transport puts them on the wire as {t: type, ...data})
|
||||
party.receive(msg) server messages {t: 'welcome'|'host'|'members'|'route'|'play'|'pong'|'error', …}
|
||||
party.now() server-synced ms (Date.now() until a pong/welcome arrives)
|
||||
party.publish(type, data) host only; no-op otherwise ('play' {snapshot: null} = left the watch page)
|
||||
party.resend() host only: re-publish current route + snapshot (after a reconnect)
|
||||
party.on(type, fn) → off 'mode' | 'members' | 'route' | 'play' | 'error' | 'resend'
|
||||
party.lastRoute / lastPlay last relayed route path / snapshot (for late subscribers)
|
||||
party.hostName() host's username ('' if unknown)
|
||||
|
||||
Pings: on attach party sends a few pings (1s apart), then one every 15s, and
|
||||
takes the median of the last 5 offsets.
|
||||
*/
|
||||
|
||||
const listeners = new Map();
|
||||
const offsets = [];
|
||||
let offset = 0;
|
||||
let pingTimer = null;
|
||||
let pingCount = 0;
|
||||
|
||||
function emit(type, data) {
|
||||
const set = listeners.get(type);
|
||||
if (!set) return;
|
||||
for (const fn of [...set]) {
|
||||
try {
|
||||
fn(data);
|
||||
} catch (e) {
|
||||
console.error('[party]', type, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setClasses(mode) {
|
||||
if (typeof document === 'undefined') return;
|
||||
const c = document.documentElement.classList;
|
||||
c.toggle('party-host', mode === 'host');
|
||||
c.toggle('party-viewer', mode === 'viewer');
|
||||
}
|
||||
|
||||
function median(list) {
|
||||
const s = list.slice().sort((a, b) => a - b);
|
||||
const m = s.length >> 1;
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
}
|
||||
|
||||
export const party = {
|
||||
mode: 'solo',
|
||||
me: null,
|
||||
host: null,
|
||||
members: [],
|
||||
transport: null,
|
||||
lastRoute: null,
|
||||
lastPlay: null,
|
||||
|
||||
attach(transport) {
|
||||
this.transport = transport || null;
|
||||
clearInterval(pingTimer);
|
||||
pingCount = 0;
|
||||
if (this.transport) {
|
||||
const ping = () => {
|
||||
pingCount++;
|
||||
this._send('ping', { at: Date.now() });
|
||||
if (pingCount === 5) {
|
||||
clearInterval(pingTimer);
|
||||
pingTimer = setInterval(ping, 15000);
|
||||
}
|
||||
};
|
||||
ping();
|
||||
pingTimer = setInterval(ping, 1000);
|
||||
}
|
||||
return () => {
|
||||
if (this.transport !== transport) return;
|
||||
clearInterval(pingTimer);
|
||||
this.transport = null;
|
||||
this._setMode('solo');
|
||||
};
|
||||
},
|
||||
|
||||
receive(msg) {
|
||||
if (!msg || typeof msg !== 'object') return;
|
||||
const t = msg.t || msg.type;
|
||||
switch (t) {
|
||||
case 'welcome': {
|
||||
this.me = msg.you ? String(msg.you.id) : this.me;
|
||||
this.host = msg.host != null ? String(msg.host) : null;
|
||||
this.members = Array.isArray(msg.members) ? msg.members : [];
|
||||
if (typeof msg.now === 'number' && !offsets.length) offset = msg.now - Date.now();
|
||||
this.lastRoute = msg.route || null;
|
||||
// a stale snapshot (host already left the watch page) must not drag viewers back
|
||||
this.lastPlay = msg.play && (!msg.route || msg.play.path === msg.route) ? msg.play : null;
|
||||
this._setMode(this._derive());
|
||||
emit('members', this.members);
|
||||
if (this.mode === 'viewer') {
|
||||
if (this.lastRoute) emit('route', { path: this.lastRoute });
|
||||
if (this.lastPlay) emit('play', this.lastPlay);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'host':
|
||||
this.host = msg.host != null ? String(msg.host) : null;
|
||||
this._setMode(this._derive());
|
||||
break;
|
||||
case 'members':
|
||||
this.members = Array.isArray(msg.members) ? msg.members : [];
|
||||
emit('members', this.members);
|
||||
break;
|
||||
case 'route':
|
||||
if (!msg.path) return;
|
||||
this.lastRoute = msg.path;
|
||||
if (this.mode === 'viewer') emit('route', { path: msg.path });
|
||||
break;
|
||||
case 'play':
|
||||
// snapshot null: the host left the watch page
|
||||
this.lastPlay = msg.snapshot || null;
|
||||
if (this.mode === 'viewer' && msg.snapshot) emit('play', msg.snapshot);
|
||||
break;
|
||||
case 'pong': {
|
||||
if (typeof msg.at !== 'number' || typeof msg.now !== 'number') return;
|
||||
const rtt = Date.now() - msg.at;
|
||||
if (rtt < 0 || rtt > 30000) return;
|
||||
offsets.push(msg.now - (msg.at + rtt / 2));
|
||||
if (offsets.length > 5) offsets.shift();
|
||||
offset = median(offsets);
|
||||
break;
|
||||
}
|
||||
case 'error':
|
||||
emit('error', msg);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
},
|
||||
|
||||
now() {
|
||||
return Date.now() + offset;
|
||||
},
|
||||
|
||||
publish(type, data) {
|
||||
if (this.mode !== 'host') return;
|
||||
this._send(type, data || {});
|
||||
},
|
||||
|
||||
// host: re-publish the current route + snapshot (the overlay calls this after a reconnect)
|
||||
resend() {
|
||||
if (this.mode === 'host') emit('resend', {});
|
||||
},
|
||||
|
||||
on(type, fn) {
|
||||
if (!listeners.has(type)) listeners.set(type, new Set());
|
||||
listeners.get(type).add(fn);
|
||||
return () => listeners.get(type).delete(fn);
|
||||
},
|
||||
|
||||
hostName() {
|
||||
const m = this.members.find((x) => x && String(x.id) === this.host);
|
||||
return (m && (m.global_name || m.username)) || '';
|
||||
},
|
||||
|
||||
_send(type, data) {
|
||||
if (!this.transport || typeof this.transport.send !== 'function') return;
|
||||
try {
|
||||
this.transport.send(type, data);
|
||||
} catch (e) {
|
||||
console.warn('[party] send failed', e);
|
||||
}
|
||||
},
|
||||
|
||||
_derive() {
|
||||
if (!this.transport || !this.me || !this.host) return 'solo';
|
||||
return this.me === this.host ? 'host' : 'viewer';
|
||||
},
|
||||
|
||||
_setMode(mode) {
|
||||
if (mode === this.mode) return;
|
||||
const prev = this.mode;
|
||||
this.mode = mode;
|
||||
setClasses(mode);
|
||||
emit('mode', { mode, prev });
|
||||
},
|
||||
};
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.bugtvParty = party;
|
||||
try {
|
||||
window.dispatchEvent(new CustomEvent('bugtv:party-ready', { detail: party }));
|
||||
} catch (e) {
|
||||
/* very old browsers */
|
||||
}
|
||||
}
|
||||
|
||||
export default party;
|
||||
@@ -15,8 +15,12 @@
|
||||
navigate(path, { replace }), href(path) → string for <a href>, back(fallbackPath),
|
||||
current() → { path, name, params, query }, register(name, pattern, loader),
|
||||
onChange(fn) → unsubscribe, start(outlet), mode, root
|
||||
|
||||
Party (party.js): the host publishes every route change; viewers follow the host's
|
||||
`route` messages and the path of its `play` snapshots (replace, no history entries).
|
||||
*/
|
||||
import { h } from './util.js';
|
||||
import { party } from './party.js';
|
||||
|
||||
const boot = window.__BUGTV_ROUTER || (() => {
|
||||
const meta = document.querySelector('meta[name="bug-tv-root"]');
|
||||
@@ -302,4 +306,52 @@ export function start(el) {
|
||||
});
|
||||
}
|
||||
resolve({ scroll: 'keep' });
|
||||
wireParty();
|
||||
}
|
||||
|
||||
/* ---- party mirroring ---------------------------------------------------------- */
|
||||
|
||||
// session/transport params that must not travel to other members
|
||||
const PRIVATE_PARAMS = /^(api|frame_id|instance_id|platform|guild_id|channel_id|location_id|referrer_id|custom_id|launch_id|user|instance)$/;
|
||||
|
||||
function publicPath(info) {
|
||||
const q = new URLSearchParams(info.query);
|
||||
for (const k of [...q.keys()]) if (PRIVATE_PARAMS.test(k)) q.delete(k);
|
||||
const qs = q.toString();
|
||||
return info.path + (qs ? `?${qs}` : '');
|
||||
}
|
||||
|
||||
function hereKey() {
|
||||
const loc = location_();
|
||||
return publicPath({ path: loc.path, query: new URLSearchParams(loc.search) });
|
||||
}
|
||||
|
||||
function follow(path) {
|
||||
if (!path || party.mode !== 'viewer') return;
|
||||
if (path === hereKey()) return;
|
||||
// keep our own private params (e.g. ?api=) on the viewer's URL
|
||||
const loc = location_();
|
||||
const mine = new URLSearchParams(loc.search);
|
||||
const target = new URL(path, 'http://x');
|
||||
for (const [k, v] of mine) if (PRIVATE_PARAMS.test(k) && !target.searchParams.has(k)) target.searchParams.set(k, v);
|
||||
navigate(target.pathname + target.search, { replace: true });
|
||||
}
|
||||
|
||||
let partyWired = false;
|
||||
function wireParty() {
|
||||
if (partyWired) return;
|
||||
partyWired = true;
|
||||
onChange((info) => {
|
||||
if (party.mode === 'host') party.publish('route', { path: publicPath(info) });
|
||||
});
|
||||
party.on('mode', ({ mode: m }) => {
|
||||
if (m === 'host') party.publish('route', { path: hereKey() });
|
||||
else if (m === 'viewer' && party.lastRoute) follow(party.lastRoute);
|
||||
});
|
||||
party.on('resend', () => party.publish('route', { path: hereKey() }));
|
||||
party.on('route', ({ path }) => follow(path));
|
||||
party.on('play', (snap) => {
|
||||
if (snap && snap.path && snap.path !== location_().path) follow(snap.path);
|
||||
});
|
||||
if (party.mode === 'viewer' && party.lastRoute) follow(party.lastRoute);
|
||||
}
|
||||
+10
-3
@@ -11,15 +11,22 @@
|
||||
import { getTmdbKey } from './config.js';
|
||||
import { safe } from './util.js';
|
||||
|
||||
const API = 'https://api.themoviedb.org/3';
|
||||
export const IMG_BASE = 'https://image.tmdb.org/t/p/';
|
||||
// <meta name="bug-tv-tmdb"> / <meta name="bug-tv-img"> override the bases (the Discord Activity
|
||||
// maps them to /tmdb/3 and /img/t/p/). Relative values resolve against the page origin.
|
||||
function metaBase(name) {
|
||||
const el = typeof document !== 'undefined' && document.querySelector(`meta[name="${name}"]`);
|
||||
const v = el && (el.getAttribute('content') || '').trim();
|
||||
return v && !/^@.*@$/.test(v) ? v : '';
|
||||
}
|
||||
const API = (metaBase('bug-tv-tmdb') || 'https://api.themoviedb.org/3').replace(/\/+$/, '');
|
||||
export const IMG_BASE = (metaBase('bug-tv-img') || 'https://image.tmdb.org/t/p/').replace(/\/*$/, '/');
|
||||
const SESSION_PREFIX = 'bug-tv.tmdb.';
|
||||
const SESSION_TTL = 30 * 60 * 1000;
|
||||
|
||||
const mem = new Map();
|
||||
|
||||
function buildUrl(path, params) {
|
||||
const url = new URL(API + path);
|
||||
const url = new URL(API + path, typeof location !== 'undefined' ? location.href : undefined);
|
||||
url.searchParams.set('api_key', getTmdbKey());
|
||||
if (!params || params.language === undefined) url.searchParams.set('language', 'en-US');
|
||||
for (const [k, v] of Object.entries(params || {})) {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
import { icon } from './icons.js';
|
||||
import { party } from '../party.js';
|
||||
|
||||
export function openModal(content, opts = {}) {
|
||||
const prevFocus = document.activeElement;
|
||||
@@ -57,6 +58,7 @@ export function openModal(content, opts = {}) {
|
||||
}
|
||||
|
||||
export function trailerModal(key, title) {
|
||||
if (party.mode !== 'solo') return () => {}; // the YouTube iframe can't be mapped inside the Activity
|
||||
const frame = h('iframe.modal__video', {
|
||||
src: `https://www.youtube-nocookie.com/embed/${encodeURIComponent(key)}?autoplay=1&rel=0&modestbranding=1`,
|
||||
title: title ? `${title} — trailer` : 'Trailer',
|
||||
|
||||
+33
-2
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
PLAYER ENGINE — plays one Stream (docs/api.md "Stream") in a <video>.
|
||||
|
||||
createPlayer(video, { onState, onError, onLevels, onAudioTracks, onTorrent, onTime })
|
||||
createPlayer(video, { onState, onError, onLevels, onAudioTracks, onTorrent, onTime, forceProxy })
|
||||
load(stream, { startAt, autoplay }) start a source (tears down the previous one)
|
||||
play() / pause() / toggle()
|
||||
seek(t) absolute seconds (offset-aware for remux)
|
||||
@@ -25,6 +25,11 @@
|
||||
engine silently reloads the fallback at the same position. Anything that
|
||||
fails after that is reported to onError({ fatal: true }) so the caller can
|
||||
move on to the next source.
|
||||
|
||||
forceProxy (option, or <meta name="bug-tv-force-proxy" content="1">): always
|
||||
play playback.fallback when present (the direct url is dropped). The Discord
|
||||
Activity CSP only allows mapped origins. `player.stream` is then the proxied
|
||||
copy; `player.original` is the Stream object passed to load().
|
||||
*/
|
||||
import { resolveUrl } from '../config.js';
|
||||
|
||||
@@ -84,7 +89,26 @@ export function probeUrl(url) {
|
||||
return `${path.replace(/\/+$/, '')}/probe${s ? `?${s}` : ''}`;
|
||||
}
|
||||
|
||||
let metaForceProxy = null;
|
||||
function forceProxyMeta() {
|
||||
if (metaForceProxy == null) {
|
||||
const el = typeof document !== 'undefined' && document.querySelector('meta[name="bug-tv-force-proxy"]');
|
||||
const v = el && (el.getAttribute('content') || '').trim();
|
||||
metaForceProxy = !!v && /^(1|true|yes|on)$/i.test(v);
|
||||
}
|
||||
return metaForceProxy;
|
||||
}
|
||||
|
||||
/** Stream with playback.url replaced by playback.fallback (and fallback dropped). */
|
||||
export function proxiedStream(s) {
|
||||
const pb = s && s.playback;
|
||||
if (!pb || !pb.fallback) return s;
|
||||
const { fallback, ...rest } = pb;
|
||||
return { ...s, playback: { ...rest, url: fallback } };
|
||||
}
|
||||
|
||||
export function createPlayer(video, handlers = {}) {
|
||||
const forceProxy = handlers.forceProxy != null ? !!handlers.forceProxy : forceProxyMeta();
|
||||
const h = {
|
||||
onState() {},
|
||||
onError() {},
|
||||
@@ -96,6 +120,7 @@ export function createPlayer(video, handlers = {}) {
|
||||
|
||||
let token = 0;
|
||||
let stream = null;
|
||||
let original = null;
|
||||
let hls = null;
|
||||
let mode = ''; // hls | native-hls | file | remux
|
||||
let offset = 0;
|
||||
@@ -450,7 +475,9 @@ export function createPlayer(video, handlers = {}) {
|
||||
|
||||
function load(s, opts = {}) {
|
||||
reset();
|
||||
stream = s;
|
||||
original = s;
|
||||
stream = forceProxy ? proxiedStream(s) : s;
|
||||
s = stream;
|
||||
wantPlay = opts.autoplay !== false;
|
||||
const startAt = Math.max(0, Number(opts.startAt) || 0);
|
||||
const pb = s.playback || { kind: 'file', url: s.url };
|
||||
@@ -715,6 +742,7 @@ export function createPlayer(video, handlers = {}) {
|
||||
function stop() {
|
||||
reset();
|
||||
stream = null;
|
||||
original = null;
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
@@ -748,6 +776,9 @@ export function createPlayer(video, handlers = {}) {
|
||||
get stream() {
|
||||
return stream;
|
||||
},
|
||||
get original() {
|
||||
return original;
|
||||
},
|
||||
get mode() {
|
||||
return mode;
|
||||
},
|
||||
|
||||
@@ -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
@@ -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);
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// node --test web/test/ — party.js hub semantics (no DOM needed)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { party } from '../js/party.js';
|
||||
|
||||
const sent = [];
|
||||
const welcome = (me, host, extra = {}) => ({ t: 'welcome', you: { id: me, username: me }, host, members: [{ id: 'a', username: 'Ann' }, { id: 'b', username: 'Bob' }], now: Date.now(), ...extra });
|
||||
|
||||
test('solo until a transport attaches and welcome arrives; publish is a no-op', () => {
|
||||
assert.equal(party.mode, 'solo');
|
||||
party.publish('route', { path: '/x' });
|
||||
party.receive(welcome('a', 'a')); // no transport → still solo
|
||||
assert.equal(party.mode, 'solo');
|
||||
});
|
||||
|
||||
test('mode derives from welcome/host; publish only as host', () => {
|
||||
const modes = [];
|
||||
const off = party.on('mode', (m) => modes.push(m.mode));
|
||||
const detach = party.attach({ send: (t, d) => sent.push([t, d]) });
|
||||
assert.equal(sent[0][0], 'ping');
|
||||
party.receive(welcome('a', 'a'));
|
||||
assert.equal(party.mode, 'host');
|
||||
party.publish('route', { path: '/movies' });
|
||||
assert.deepEqual(sent.at(-1), ['route', { path: '/movies' }]);
|
||||
party.receive({ t: 'host', host: 'b' });
|
||||
assert.equal(party.mode, 'viewer');
|
||||
assert.equal(party.hostName(), 'Bob');
|
||||
const n = sent.length;
|
||||
party.publish('route', { path: '/tv' });
|
||||
assert.equal(sent.length, n);
|
||||
assert.deepEqual(modes, ['host', 'viewer']);
|
||||
off();
|
||||
detach();
|
||||
assert.equal(party.mode, 'solo');
|
||||
});
|
||||
|
||||
test('viewer gets route/play events; stale welcome snapshot is dropped', () => {
|
||||
const got = [];
|
||||
const offs = [party.on('route', (r) => got.push(['route', r.path])), party.on('play', (s) => got.push(['play', s.path]))];
|
||||
const detach = party.attach({ send() {} });
|
||||
party.receive(welcome('b', 'a', { route: '/title/movie/550', play: { path: '/watch/movie/550' } }));
|
||||
assert.equal(party.lastPlay, null);
|
||||
assert.deepEqual(got, [['route', '/title/movie/550']]);
|
||||
party.receive({ t: 'play', snapshot: { path: '/watch/movie/550', at: 1 } });
|
||||
assert.equal(party.lastPlay.path, '/watch/movie/550');
|
||||
assert.deepEqual(got.at(-1), ['play', '/watch/movie/550']);
|
||||
offs.forEach((o) => o());
|
||||
detach();
|
||||
});
|
||||
|
||||
test('clock offset is the median of the last 5 pong samples', () => {
|
||||
const detach = party.attach({ send() {} });
|
||||
const realNow = Date.now;
|
||||
let t = 1_000_000;
|
||||
Date.now = () => t;
|
||||
try {
|
||||
// rtt 0 → sample = now - at; offsets 100,100,5000(outlier),100,100 → median 100
|
||||
for (const off of [100, 100, 5000, 100, 100]) party.receive({ t: 'pong', at: t, now: t + off });
|
||||
assert.equal(party.now() - t, 100);
|
||||
} finally {
|
||||
Date.now = realNow;
|
||||
detach();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user