diff --git a/.gitignore b/.gitignore index 04ec903..ae143d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ node_modules/ result* -activity/dist/ +site/ config.json -activity/vendor/bugtv/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..9188303 --- /dev/null +++ b/README.md @@ -0,0 +1,33 @@ +# tv-discord + +A Discord Activity for watching [bug.tv](https://tv.bug.tools) together. The Activity is the whole bug.tv site with a small watch-party overlay on top. Whoever starts the Activity is the **host** and controls everything. Everyone else in the call follows the host's page and playback in sync, and can only change volume and fullscreen. If the host leaves, the next person to have joined takes over. + +The contract is in [docs/protocol.md](docs/protocol.md). + +## Layout +- `src/server.js`: static files, `/api/config`, `/api/token` (OAuth code exchange), `/api/avatar/:id`, and the `/ws` relay (one hub per Activity instance). +- `activity/js/discord.js`: the overlay. It handles the Discord SDK and auth, the WebSocket transport for bug.tv's `party.js`, the members pill, the viewer banner and input blocking. esbuild bundles it into `discord.js`. +- `activity/overlay.css`: the overlay styles. +- `scripts/build-activity.sh [apiBase=/tv]`: builds the Activity site. + +## Run +```sh +npm install +bash scripts/build-activity.sh ../tv/web site # or nix build .#activity +cp config.example.json config.json # applicationId, tokenFile, clientSecretFile +npm start +``` +The bot token is only used to check who is in an Activity instance; there is no gateway connection. + +**Discord URL mappings:** +- `/` → this server +- `/tv` → api-tv.bug.tools +- `/tmdb` → api.themoviedb.org +- `/img` → image.tmdb.org + +**Dev without Discord:** set `"dev": true` and `"devApiUrl": "http://127.0.0.1:8789"` (a local bug-tv API). Build the site with an absolute API base, or use the default `/tv`, which the dev server proxies. Then open `/?user=1&instance=x` and `/?user=2&instance=x` in two browsers. + +## Test +```sh +npm test +``` diff --git a/activity/css/activity.css b/activity/css/activity.css deleted file mode 100644 index 790dc80..0000000 --- a/activity/css/activity.css +++ /dev/null @@ -1,146 +0,0 @@ -:root { - --bg: #08080c; - --fg: #f4f2f8; - --muted: #a39fb0; - --accent: #c084fc; - --accent-2: #a855f7; - --glass: rgba(14, 12, 20, 0.72); - --line: rgba(255, 255, 255, 0.16); - color-scheme: dark; - font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; -} - -* { box-sizing: border-box; } -html, body { margin: 0; height: 100%; background: var(--bg); color: var(--fg); overflow: hidden; } -button { font: inherit; color: inherit; } -[hidden] { display: none !important; } - -.app { position: fixed; inset: 0; user-select: none; -webkit-user-select: none; } - -.video { position: absolute; inset: 0; width: 100%; height: 100%; background: #000; object-fit: contain; } -.video::cue { background: rgba(0, 0, 0, 0.62); font-size: clamp(14px, 3.2vh, 30px); } - -.backdrop { - position: absolute; inset: 0; background-size: cover; background-position: center; - opacity: 0; transition: opacity 0.6s; filter: blur(2px) brightness(0.35); -} - -/* ---- full screens -------------------------------------------------------- */ - -.screen { - position: absolute; inset: 0; display: none; flex-direction: column; align-items: center; justify-content: center; - gap: 12px; padding: 24px; text-align: center; - background: radial-gradient(ellipse at 50% 35%, rgba(192, 132, 252, 0.14), transparent 60%), var(--bg); -} -.app[data-view="boot"] .idle, -.app[data-view="idle"] .idle, -.app[data-view="error"] .idle { display: flex; } -.app[data-view="finding"] .finding { display: flex; background: transparent; } -.app[data-view="finding"] .backdrop { opacity: 1; } -.app:not([data-view="play"]) .video, -.app:not([data-view="play"]) .top, -.app:not([data-view="play"]) .bottom, -.app:not([data-view="play"]) .spinner, -.app:not([data-view="play"]) .join, -.app:not([data-view="play"]) .unmute { display: none; } - -.idle__logo { width: clamp(64px, 16vh, 120px); height: auto; animation: bob 3.2s ease-in-out infinite; filter: drop-shadow(0 8px 24px rgba(192, 132, 252, 0.35)); } -.idle__title { margin: 0; font-size: clamp(28px, 7vh, 52px); font-weight: 800; letter-spacing: -0.03em; } -.idle__title span { color: var(--accent); } -.idle__msg { margin: 0; color: var(--muted); font-size: clamp(14px, 2.6vh, 18px); max-width: 32em; } -.app[data-view="error"] .idle__msg { color: #fca5a5; } -@keyframes bob { 50% { transform: translateY(-8px) rotate(-4deg); } } - -.finding__title { margin: 8px 0 0; font-size: clamp(20px, 4.5vh, 34px); font-weight: 700; } -.finding__msg { margin: 0; color: var(--muted); } - -.ring { - width: 44px; height: 44px; border-radius: 50%; - border: 3px solid rgba(255, 255, 255, 0.14); border-top-color: var(--accent); - animation: spin 0.9s linear infinite; -} -@keyframes spin { to { transform: rotate(360deg); } } - -.spinner { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; pointer-events: none; } -.spinner p { margin: 0; color: var(--muted); font-size: 14px; text-shadow: 0 1px 4px #000; } - -/* ---- overlays ------------------------------------------------------------ */ - -.top, .bottom { position: absolute; left: 0; right: 0; transition: opacity 0.25s, transform 0.25s; } -.app.is-idle .top, .app.is-idle .bottom { opacity: 0; pointer-events: none; } -.app.is-idle { cursor: none; } -.app.is-idle .top { transform: translateY(-8px); } -.app.is-idle .bottom { transform: translateY(8px); } - -.top { - top: 0; display: flex; align-items: flex-start; gap: 16px; - padding: max(14px, env(safe-area-inset-top)) 18px 40px; - background: linear-gradient(to bottom, rgba(0, 0, 0, 0.75), transparent); -} -.top__text { min-width: 0; flex: 1; } -.top__title { font-size: clamp(15px, 2.8vh, 22px); font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.top__sub { color: var(--muted); font-size: 13px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.top__src { - flex: none; font-size: 12px; font-weight: 600; padding: 4px 9px; border-radius: 999px; - background: rgba(192, 132, 252, 0.16); color: var(--accent); border: 1px solid rgba(192, 132, 252, 0.35); -} -.top__src:empty { display: none; } - -.bottom { - bottom: 0; padding: 40px 14px max(10px, env(safe-area-inset-bottom)); - background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent); -} -.row { display: flex; align-items: center; gap: 10px; } -.spacer { flex: 1; } - -.btn { - width: 40px; height: 40px; display: grid; place-items: center; border: 0; border-radius: 10px; - background: transparent; cursor: pointer; -} -.btn:hover { background: rgba(255, 255, 255, 0.1); } -.btn svg { width: 24px; height: 24px; } -.time { font-variant-numeric: tabular-nums; font-size: 13px; color: #ddd; } - -.viewers { display: flex; align-items: center; gap: 6px; font-size: 13px; color: #ddd; } -.viewers svg { width: 18px; height: 18px; color: var(--accent); } - -.seek { position: relative; height: 18px; display: flex; align-items: center; cursor: pointer; touch-action: none; } -.seek__track { position: relative; width: 100%; height: 4px; border-radius: 4px; background: rgba(255, 255, 255, 0.2); overflow: hidden; transition: height 0.15s; } -.seek:hover .seek__track { height: 6px; } -.seek__buf, .seek__fill { position: absolute; left: 0; top: 0; bottom: 0; width: 0; } -.seek__buf { background: rgba(255, 255, 255, 0.28); } -.seek__fill { background: var(--accent); } -.seek__tip { - position: absolute; bottom: 22px; transform: translateX(-50%); padding: 3px 7px; border-radius: 6px; - background: var(--glass); font-size: 12px; font-variant-numeric: tabular-nums; pointer-events: none; -} - -.join { - position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); - display: flex; align-items: center; gap: 12px; padding: 18px 26px; border: 0; border-radius: 16px; - background: var(--accent); color: #1a0b2e; font-weight: 800; font-size: clamp(15px, 2.8vh, 20px); - box-shadow: 0 10px 40px rgba(192, 132, 252, 0.45); cursor: pointer; -} -.join svg { width: 26px; height: 26px; } -.join:hover { background: #d0a2fd; } - -.unmute { - position: absolute; right: 16px; top: 64px; display: flex; align-items: center; gap: 8px; - padding: 8px 14px; border: 1px solid var(--line); border-radius: 999px; background: var(--glass); - font-weight: 600; font-size: 13px; cursor: pointer; -} -.unmute svg { width: 18px; height: 18px; } - -/* ---- toasts -------------------------------------------------------------- */ - -.toasts { position: absolute; left: 50%; top: 70px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 8px; align-items: center; pointer-events: none; z-index: 5; } -.toast { - padding: 9px 16px; border-radius: 10px; background: var(--glass); border: 1px solid var(--line); - font-size: 14px; max-width: 80vw; opacity: 0; transform: translateY(-6px); transition: opacity 0.25s, transform 0.25s; -} -.toast.is-in { opacity: 1; transform: none; } - -@media (max-width: 520px) { - .top { padding-left: 12px; padding-right: 12px; } - .top__src { display: none; } -} diff --git a/activity/img/bug.svg b/activity/img/bug.svg deleted file mode 100644 index f8986dd..0000000 --- a/activity/img/bug.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/activity/index.html b/activity/index.html deleted file mode 100644 index 4743a62..0000000 --- a/activity/index.html +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - bug.tv - - - - - -
- - - -
- -

bug.tv

-

Connecting…

-
- -
- -

-

Finding sources…

-
- - - - - -
-
-
-
-
-
-
- - - -
-
-
- -
-
- -
0:00 / 0:00
-
-
-
-
- -
-
- - diff --git a/activity/js/discord.js b/activity/js/discord.js new file mode 100644 index 0000000..ae95fbb --- /dev/null +++ b/activity/js/discord.js @@ -0,0 +1,533 @@ +/* + discord.js — the watch-party overlay on top of the bug.tv site (docs/protocol.md "Overlay"). + Bundled with @discord/embedded-app-sdk by esbuild into /discord.js. + + - Inside Discord (?frame_id=…): SDK ready → patchUrlMappings → authorize/token/authenticate → + WS /ws hello {token, instanceId, channelId, guildId}. + - Outside Discord (dev): ?user=&instance=[&name=], only when /api/config says dev. + Without those params the overlay stays out of the way and the site runs solo. + - Transport for bug-tv's party layer (window.bugtvParty / 'bugtv:party-ready'): + party.attach({ send(type, data) }) and party.receive(msg) for every server message. + - UI: members pill, "👑 is in control" banner for viewers, toasts; viewers get + html.party-viewer and their clicks/keys are blocked except volume/mute/fullscreen (m, f). +*/ +import { DiscordSDK, patchUrlMappings } from '@discord/embedded-app-sdk'; + +const params = new URLSearchParams(location.search); +const inDiscord = params.has('frame_id'); +const PING_MS = 5000; +const MAX_BACKOFF_MS = 15000; +const ALLOW = '.pl-volwrap, [data-party-allow], .pl-btn[aria-label^="Fullscreen"], .pl-btn[aria-label^="Exit fullscreen"], .bp-root'; +const ALLOWED_KEYS = new Set(['m', 'M', 'f', 'F']); +const TOAST_MS = 3500; + +/* ---- state --------------------------------------------------------------- */ + +let ws = null; +let hello = null; +let me = null; +let hostId = null; +let members = []; +let welcomed = 0; // number of welcomes so far (>1 → this is a reconnect) +let fatal = false; +let backoff = 1000; +let pingTimer = null; +let party = null; +const pending = []; // server messages received before the party layer appeared +// last route/play this client published, replayed after a reconnect if the party can't resend +const lastSent = { route: null, play: null, playAt: 0 }; + +const isHost = () => !!me && me.id === hostId; +const memberById = (id) => members.find((m) => m.id === id) || null; +const nameOf = (id) => (memberById(id) || {}).username || 'someone'; + +/* ---- party layer --------------------------------------------------------- */ + +const transport = { + send(type, data) { + const msg = { ...(data && typeof data === 'object' ? data : {}), t: type }; + if (type === 'route') lastSent.route = msg; + else if (type === 'play') { + lastSent.play = msg; + lastSent.playAt = performance.now(); + } + if (ws && ws.readyState === 1 && me) ws.send(JSON.stringify(msg)); + }, +}; + +function toParty(msg) { + if (!party) { + pending.push(msg); + if (pending.length > 200) pending.splice(0, pending.length - 200); + return; + } + try { + party.receive(msg); + } catch (e) { + console.warn('[bugtv-party] receive failed', e); + } +} + +function withParty(p) { + if (party || !p || typeof p.attach !== 'function') return; + party = p; + try { + party.attach(transport); + } catch (e) { + console.warn('[bugtv-party] attach failed', e); + } + for (const m of pending.splice(0)) toParty(m); +} + +function findParty() { + if (window.bugtvParty) return withParty(window.bugtvParty); + window.addEventListener('bugtv:party-ready', (e) => withParty((e && e.detail) || window.bugtvParty), { once: true }); +} + +/** The host (again) after a reconnect / handover: make sure viewers get the current state. */ +function republish(reconnect) { + if (party && typeof party.resend === 'function') { + try { + party.resend(); + return; + } catch (e) { + console.warn('[bugtv-party] resend failed', e); + } + } + if (!reconnect || !ws || ws.readyState !== 1) return; + if (lastSent.route) ws.send(JSON.stringify(lastSent.route)); + if (lastSent.play) { + const p = lastSent.play; + let snap = p.snapshot; + if (snap && snap.playing && typeof snap.position === 'number') { + snap = { ...snap, position: snap.position + (performance.now() - lastSent.playAt) / 1000 }; + } + ws.send(JSON.stringify({ ...p, snapshot: snap })); + } +} + +/* ---- connection ---------------------------------------------------------- */ + +function wsUrl() { + return `${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/ws`; +} + +function ping() { + if (ws && ws.readyState === 1) ws.send(JSON.stringify({ t: 'ping', at: Date.now() })); +} + +function connect() { + setConn('connecting'); + const sock = new WebSocket(wsUrl()); + ws = sock; + sock.onopen = () => { + sock.send(JSON.stringify(hello)); + }; + sock.onmessage = (ev) => { + let m; + try { + m = JSON.parse(ev.data); + } catch (e) { + return; + } + if (!m || typeof m !== 'object') return; + onServer(m); + }; + sock.onclose = (ev) => { + if (ws !== sock) return; + clearInterval(pingTimer); + pingTimer = null; + const wasMe = me; + me = null; + if (fatal || ev.code === 4001) { + fatal = true; + setConn('error'); + if (wasMe) applyRole(); + return; + } + setConn('connecting', 'Reconnecting…'); + setTimeout(connect, backoff + Math.random() * 300); + backoff = Math.min(backoff * 2, MAX_BACKOFF_MS); + }; + sock.onerror = () => {}; +} + +function onServer(m) { + switch (m.t) { + case 'welcome': { + welcomed++; + backoff = 1000; + me = m.you; + const prevHost = hostId; + hostId = m.host; + const prev = members; + members = Array.isArray(m.members) ? m.members : []; + setConn('live'); + toParty(m); + // clock samples: a few quick pings, then every 5s + ping(); + setTimeout(ping, 400); + setTimeout(ping, 1200); + clearInterval(pingTimer); + pingTimer = setInterval(ping, PING_MS); + if (welcomed > 1) diffMembers(prev, members); + if (welcomed > 1 && prevHost !== hostId) hostToast(); + render(); + applyRole(); + if (isHost()) republish(welcomed > 1); + return; + } + case 'members': { + const prev = members; + members = Array.isArray(m.members) ? m.members : []; + diffMembers(prev, members); + toParty(m); + render(); + return; + } + case 'host': { + const was = isHost(); + hostId = m.host; + toParty(m); + hostToast(); + render(); + applyRole(); + if (!was && isHost()) republish(false); + return; + } + case 'error': + toParty(m); + if (/slow down/.test(m.message || '')) return; + fatal = true; + setConn('error', errorText(m.message)); + toast(errorText(m.message), 'error'); + return; + default: + // route, play, pong, … + toParty(m); + } +} + +function errorText(msg) { + const s = String(msg || 'error'); + if (/not in this activity/.test(s)) return 'Not part of this Activity — reopen it from the call.'; + if (/dev mode/.test(s)) return 'Dev mode is off on the server.'; + if (/authentication/.test(s)) return 'Discord sign-in failed.'; + return s; +} + +/* ---- auth ---------------------------------------------------------------- */ + +async function discordHello(cfg) { + const sdk = new DiscordSDK(cfg.applicationId); + await sdk.ready(); + // /api and /ws stay on the root mapping (our server); relative /tv, /tmdb, /img already hit + // their mappings — this rewrites absolute URLs of those hosts. + patchUrlMappings([ + { prefix: '/tv', target: 'api-tv.bug.tools' }, + { prefix: '/tmdb', target: 'api.themoviedb.org' }, + { prefix: '/img', target: 'image.tmdb.org' }, + ]); + const { code } = await sdk.commands.authorize({ + client_id: cfg.applicationId, + response_type: 'code', + state: '', + prompt: 'none', + scope: ['identify'], + }); + const r = await fetch('/api/token', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ code }), + }); + if (!r.ok) throw new Error(`token exchange failed (${r.status})`); + const { access_token } = await r.json(); + await sdk.commands.authenticate({ access_token }); + if (!sdk.instanceId) throw new Error('no activity instance'); + return { + t: 'hello', + token: access_token, + instanceId: sdk.instanceId, + channelId: sdk.channelId || undefined, + guildId: sdk.guildId || undefined, + }; +} + +function devHello(cfg) { + const userId = params.get('user'); + const instanceId = params.get('instance'); + if (!userId || !instanceId || !cfg.dev) return null; + return { t: 'hello', dev: true, userId, instanceId, username: params.get('name') || `dev-${userId}` }; +} + +/* ---- UI ------------------------------------------------------------------ */ + +const ui = {}; +let bannerCollapsed = false; +let connState = 'connecting'; +let connText = 'Connecting…'; + +function el(tag, cls, text) { + const e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = text; + return e; +} + +function buildUi() { + const root = el('div', 'bp-root'); + root.setAttribute('aria-live', 'polite'); + root.dataset.conn = 'connecting'; + + const pill = el('button', 'bp-pill bp-glass'); + pill.type = 'button'; + pill.setAttribute('aria-label', 'Watch party'); + const dot = el('span', 'bp-dot'); + const avatars = el('span', 'bp-avatars'); + const host = el('span', 'bp-host', 'Connecting…'); + pill.append(dot, avatars, host); + + const list = el('div', 'bp-list bp-glass'); + list.hidden = true; + + const banner = el('div', 'bp-banner bp-glass'); + banner.hidden = true; + const bannerText = el('span', 'bp-banner__text'); + const x = el('button', 'bp-x', '×'); + x.type = 'button'; + x.setAttribute('aria-label', 'Hide'); + x.title = 'Hide (click the pill to show again)'; + banner.append(bannerText, x); + + const toasts = el('div', 'bp-toasts'); + root.append(pill, list, banner, toasts); + document.body.appendChild(root); + + pill.addEventListener('click', () => { + if (!isHost() && me && bannerCollapsed) { + bannerCollapsed = false; + render(); + return; + } + list.hidden = !list.hidden; + render(); + }); + x.addEventListener('click', () => { + bannerCollapsed = true; + render(); + }); + document.addEventListener('click', (e) => { + if (!list.hidden && !root.contains(e.target)) { + list.hidden = true; + } + }); + Object.assign(ui, { root, pill, avatars, host, list, banner, bannerText, toasts }); +} + +function avatar(m, extra = '') { + const a = el('span', `bp-av${extra}`); + const initial = (m.username || '?').trim().charAt(0) || '?'; + if (m.avatar) { + const img = new Image(); + img.alt = ''; + img.decoding = 'async'; + img.referrerPolicy = 'no-referrer'; + img.onerror = () => { + img.remove(); + a.textContent = initial; + }; + img.src = m.avatar; + a.appendChild(img); + } else { + a.textContent = initial; + a.style.background = `hsl(${hue(m.id)} 45% 32%)`; + } + a.title = m.username || ''; + return a; +} + +function hue(s) { + let h = 0; + for (const c of String(s || '')) h = (h * 31 + c.charCodeAt(0)) >>> 0; + return h % 360; +} + +function setConn(state, text) { + connState = state; + connText = text || (state === 'connecting' ? 'Connecting…' : state === 'error' ? 'Disconnected' : ''); + render(); +} + +function render() { + if (!ui.root) return; + ui.root.dataset.conn = connState; + ui.avatars.replaceChildren(); + const shown = members.slice(0, 5); + for (const m of shown) ui.avatars.appendChild(avatar(m, m.id === hostId ? ' is-host' : '')); + if (members.length > shown.length) ui.avatars.appendChild(el('span', 'bp-more', `+${members.length - shown.length}`)); + + const live = connState === 'live' && me; + ui.host.classList.toggle('is-me', !!live && isHost()); + ui.host.textContent = live ? `👑 ${isHost() ? 'You' : nameOf(hostId)}` : connText; + ui.pill.title = live ? `${members.length} watching · ${members.map((m) => m.username).join(', ')}` : connText; + + // member list + if (!ui.list.hidden) { + ui.list.replaceChildren(); + for (const m of members) { + const row = el('div', 'bp-row'); + row.append(avatar(m, m.id === hostId ? ' is-host' : ''), el('span', 'bp-row__name', m.username)); + const tags = [m.id === hostId ? '👑 host' : '', me && m.id === me.id ? 'you' : ''].filter(Boolean).join(' · '); + if (tags) row.appendChild(el('span', 'bp-row__tag', tags)); + ui.list.appendChild(row); + } + if (!live) ui.list.appendChild(el('div', 'bp-status', connText)); + else if (isHost()) ui.list.appendChild(el('div', 'bp-status', 'You are in control — everyone follows what you watch.')); + } + + // viewer banner + const viewer = !!live && !isHost(); + ui.banner.hidden = !viewer || bannerCollapsed; + if (viewer) { + ui.bannerText.replaceChildren( + document.createTextNode('👑 '), + el('b', '', nameOf(hostId)), + document.createTextNode(' is in control'), + el('span', 'bp-banner__sub', 'You can change volume and fullscreen.'), + ); + } +} + +function toast(text, kind = '') { + if (!ui.toasts) return; + const t = el('div', `bp-toast bp-glass${kind ? ` bp-toast--${kind}` : ''}`, text); + ui.toasts.appendChild(t); + while (ui.toasts.children.length > 3) ui.toasts.firstChild.remove(); + requestAnimationFrame(() => t.classList.add('is-shown')); + setTimeout(() => { + t.classList.remove('is-shown'); + setTimeout(() => t.remove(), 300); + }, TOAST_MS); +} + +function hostToast() { + if (!me || !hostId) return; + toast(isHost() ? '👑 You are in control now' : `👑 ${nameOf(hostId)} is in control`, 'host'); +} + +function diffMembers(prev, next) { + if (!me) return; + const before = new Set(prev.map((m) => m.id)); + const after = new Set(next.map((m) => m.id)); + for (const m of next) if (!before.has(m.id) && m.id !== me.id) toast(`${m.username} joined`); + for (const m of prev) if (!after.has(m.id) && m.id !== me.id) toast(`${m.username} left`); +} + +/* ---- viewer input blocking ----------------------------------------------- */ + +const viewerNow = () => document.documentElement.classList.contains('party-viewer'); + +function applyRole() { + const viewer = !!me && !isHost(); + document.documentElement.classList.toggle('party-viewer', viewer); + document.documentElement.classList.toggle('party-host', !!me && isHost()); + if (viewer) { + const a = document.activeElement; + if (a && a !== document.body && !allowed(a) && typeof a.blur === 'function') a.blur(); + } +} + +function allowed(target) { + return !!(target && target.closest && target.closest(ALLOW)); +} + +function blockPointer(e) { + if (!viewerNow() || allowed(e.target)) return; + e.stopImmediatePropagation(); + // touchstart must stay passive-compatible so scrolling keeps working + if (e.cancelable && e.type !== 'touchstart' && e.type !== 'touchmove') e.preventDefault(); +} + +function editable(t) { + return !!(t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))); +} + +function blockKey(e) { + if (!viewerNow() || allowed(e.target)) return; + if (e.ctrlKey || e.metaKey || e.altKey) return; // browser / Discord shortcuts + if (ALLOWED_KEYS.has(e.key) && !editable(e.target)) return; + e.stopImmediatePropagation(); + // keep native scrolling keys (arrows, space, page up/down) on the page itself + if (editable(e.target) || e.key === 'Enter' || e.key === 'Escape' || e.key === 'Tab' || e.key.length === 1) { + if (e.key !== ' ' || editable(e.target)) e.preventDefault(); + } +} + +function blockForm(e) { + if (!viewerNow() || allowed(e.target)) return; + e.stopImmediatePropagation(); + if (e.cancelable) e.preventDefault(); +} + +function installBlocking() { + for (const t of ['click', 'dblclick', 'auxclick', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'contextmenu', 'touchstart', 'touchend']) { + window.addEventListener(t, blockPointer, { capture: true, passive: false }); + } + for (const t of ['keydown', 'keypress', 'keyup']) window.addEventListener(t, blockKey, { capture: true }); + for (const t of ['submit', 'input', 'change', 'beforeinput']) window.addEventListener(t, blockForm, { capture: true }); + window.addEventListener( + 'focusin', + (e) => { + if (viewerNow() && editable(e.target) && !allowed(e.target)) e.target.blur(); + }, + true, + ); +} + +/* ---- boot ---------------------------------------------------------------- */ + +async function boot() { + let cfg; + try { + cfg = await (await fetch('/api/config')).json(); + } catch (e) { + console.warn('[bugtv-party] no /api/config — overlay off'); + return; + } + if (!inDiscord) { + hello = devHello(cfg); + if (!hello) return; // plain site, nothing to do + } + buildUi(); + installBlocking(); + findParty(); + if (inDiscord) { + try { + hello = await discordHello(cfg); + } catch (e) { + console.warn('[bugtv-party] discord auth failed', e); + setConn('error', `Discord: ${e.message || e}`); + return; + } + } + connect(); +} + +// leaving the page (or Discord closing the iframe): close now so the host hands over at once +let hidden = false; +window.addEventListener('pagehide', () => { + if (!ws) return; + hidden = true; + fatal = true; + ws.close(1000, 'bye'); +}); +// restored from the back/forward cache: join again +window.addEventListener('pageshow', (e) => { + if (!e.persisted || !hidden || !hello) return; + hidden = false; + fatal = false; + connect(); +}); + +if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once: true }); +else boot(); diff --git a/activity/js/main.js b/activity/js/main.js deleted file mode 100644 index ac2d294..0000000 --- a/activity/js/main.js +++ /dev/null @@ -1,635 +0,0 @@ -/* - Activity entry (bundled by esbuild → dist/main.js). - - Inside Discord (frame_id query param): SDK ready → patchUrlMappings → authorize → POST /api/token - → authenticate → WS hello {token, channelId}. Dev (plain browser): hello {dev, userId, channelId} - from ?channel=&user= (only accepted by a server with cfg.dev). - - The room's publicState drives everything: which stream is loaded, play/pause, subtitle and quality. - A 500ms loop keeps the local player on the room clock (see sync.js). The leader reports - duration, levels, buffering, ended, fatal errors and a 5s position heartbeat. -*/ -import { DiscordSDK, patchUrlMappings } from '@discord/embedded-app-sdk'; -import { createPlayer } from '../vendor/bugtv/js/ui/player.js'; -import * as S from './sync.js'; -import { inDiscord, param, wsUrl, imgUrl, TV_PREFIX, IMG_PREFIX } from './urls.js'; - -const HLS_SRC = '/vendor/bugtv/vendor/hls.min.js'; -const HEARTBEAT_MS = 5000; -const SYNC_MS = 500; -const CONTROLS_HIDE_MS = 3000; - -const ICON = { - play: '', - pause: '', - people: '', -}; - -const $ = (id) => document.getElementById(id); -const ui = { - app: $('app'), - video: $('video'), - backdrop: $('backdrop'), - idleMsg: $('idleMsg'), - findTitle: $('findTitle'), - findMsg: $('findMsg'), - spinner: $('spinner'), - spinMsg: $('spinMsg'), - joinBtn: $('joinBtn'), - unmuteBtn: $('unmuteBtn'), - title: $('title'), - sub: $('sub'), - srcLabel: $('srcLabel'), - seek: $('seek'), - seekBuf: $('seekBuf'), - seekFill: $('seekFill'), - seekTip: $('seekTip'), - playBtn: $('playBtn'), - time: $('time'), - viewers: $('viewers'), - toasts: $('toasts'), -}; -const video = ui.video; - -/* ---- app state --------------------------------------------------------- */ - -let me = null; // { id, username } -let state = null; // latest publicState -let hello = null; // hello payload, resent on reconnect -let ws = null; -let fatalError = false; -let retryMs = 1000; -const clock = S.createClock(5); - -let streamKey = ''; -let retriedKey = ''; -let appliedSub = null; -let appliedQuality = null; -let lastSeekAt = 0; -let forceSync = false; -let blocked = false; // autoplay refused even muted → waiting for a click -let lastNotice = null; -const reported = { duration: 0, levels: '', buffering: null, error: '' }; - -const isLeader = () => !!(me && state && state.leader === me.id); -const offset = () => clock.offset(); - -/* ---- small UI helpers ---------------------------------------------------- */ - -function setView(v) { - ui.app.dataset.view = v; -} - -function toast(msg) { - const t = document.createElement('div'); - t.className = 'toast'; - t.textContent = msg; - ui.toasts.appendChild(t); - requestAnimationFrame(() => t.classList.add('is-in')); - setTimeout(() => { - t.classList.remove('is-in'); - setTimeout(() => t.remove(), 300); - }, 4000); - while (ui.toasts.children.length > 3) ui.toasts.firstChild.remove(); -} - -function fail(message) { - fatalError = true; - setView('error'); - ui.idleMsg.textContent = message; -} - -let spinTimer = null; -function spinner(on, msg = '') { - clearTimeout(spinTimer); - if (!on) { - ui.spinner.hidden = true; - return; - } - ui.spinMsg.textContent = msg; - // avoid flashing for sub-second stalls - spinTimer = setTimeout(() => (ui.spinner.hidden = false), ui.spinner.hidden ? 300 : 0); -} - -let idleTimer = null; -function poke() { - ui.app.classList.remove('is-idle'); - clearTimeout(idleTimer); - idleTimer = setTimeout(() => { - if (state && state.playing && !blocked) ui.app.classList.add('is-idle'); - }, CONTROLS_HIDE_MS); -} - -/* ---- websocket ----------------------------------------------------------- */ - -function send(msg) { - if (ws && ws.readyState === 1) ws.send(JSON.stringify(msg)); -} - -function cmd(op, args = {}) { - send({ t: 'cmd', op, args }); -} - -// sourceId lets the room drop late reports about a source it already left -function report(data) { - const sourceId = player.stream ? player.stream.id : state && state.stream ? state.stream.id : undefined; - send({ t: 'report', sourceId, ...data }); -} - -let pingTimer = null; -function startPings() { - clearTimeout(pingTimer); - let n = 0; - const tick = () => { - send({ t: 'ping', at: Date.now() }); - n++; - pingTimer = setTimeout(tick, n < 5 ? 400 : 10000); - }; - tick(); -} - -function connect() { - ws = new WebSocket(wsUrl()); - ws.onopen = () => { - retryMs = 1000; - send(hello); - startPings(); - }; - ws.onmessage = (ev) => { - let m; - try { - m = JSON.parse(ev.data); - } catch (e) { - return; - } - if (m.t === 'pong') clock.add(S.offsetSample(m.at, m.now, Date.now())); - else if (m.t === 'welcome') { - me = m.user; - onState(m.state); - } else if (m.t === 'state') onState(m.state); - else if (m.t === 'error') { - if (/auth|voice|hello|missing/i.test(m.message)) fail(m.message === 'join the voice channel first' ? 'Join the voice channel to watch together.' : `Error: ${m.message}`); - else toast(m.message); - } - }; - ws.onclose = (ev) => { - clearTimeout(pingTimer); - if (fatalError || ev.code === 4001) { - if (!fatalError) fail('Disconnected.'); - return; - } - if (!state || !state.media) ui.idleMsg.textContent = 'Reconnecting…'; - setTimeout(connect, retryMs); - retryMs = Math.min(retryMs * 2, 15000); - }; -} - -/* ---- auth ---------------------------------------------------------------- */ - -async function discordHello() { - const cfg = await (await fetch('/api/config')).json(); - const sdk = new DiscordSDK(cfg.applicationId); - await sdk.ready(); - patchUrlMappings([ - { prefix: TV_PREFIX, target: 'api-tv.bug.tools' }, - { prefix: IMG_PREFIX, target: 'image.tmdb.org' }, - ]); - const { code } = await sdk.commands.authorize({ - client_id: cfg.applicationId, - response_type: 'code', - state: '', - prompt: 'none', - scope: ['identify'], - }); - const r = await fetch('/api/token', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ code }), - }); - if (!r.ok) throw new Error(`token exchange failed (${r.status})`); - const { access_token } = await r.json(); - await sdk.commands.authenticate({ access_token }); - if (!sdk.channelId) throw new Error('Open the Activity from a voice channel.'); - return { t: 'hello', token: access_token, channelId: sdk.channelId }; -} - -function devHello() { - const channelId = param('channel'); - const userId = param('user'); - if (!channelId || !userId) throw new Error('Dev mode: add ?channel=&user= (and ?api=).'); - return { t: 'hello', dev: true, channelId, userId, username: param('name') || `dev-${userId}` }; -} - -/* ---- player -------------------------------------------------------------- */ - -let hlsPromise = null; -function ensureHls() { - if (window.Hls) return Promise.resolve(); - if (!hlsPromise) { - hlsPromise = new Promise((resolve) => { - const s = document.createElement('script'); - s.src = HLS_SRC; - s.onload = resolve; - s.onerror = () => { - hlsPromise = null; - resolve(); - }; - document.head.appendChild(s); - }); - } - return hlsPromise; -} - -const player = createPlayer(video, { - onState(e) { - switch (e.phase) { - case 'loading': - case 'seeking': - case 'fallback': - spinner(true, e.message || ''); - break; - case 'torrent': - spinner(true, torrentMsg(e.torrent) || e.message || ''); - break; - case 'buffering': - spinner(true, ''); - if (isLeader() && player.started) reportBuffering(true); - break; - case 'playing': - spinner(false); - cancelPendingError(); - if (isLeader()) reportBuffering(false); - break; - case 'ready': - case 'paused': - spinner(false); - break; - case 'metadata': - case 'probe': - reportDuration(); - break; - case 'ended': - if (isLeader()) report({ ended: true }); - break; - case 'blocked': - onBlocked(); - break; - default: - } - }, - onError(err) { - spinner(false); - const key = streamKey; - if (isLeader()) { - // the player's startup watchdog can fire on a slow proxied start that then plays fine: - // only fail the source (room switches for everyone) if it is still not playing shortly after - cancelPendingError(); - pendingError = setTimeout(() => { - pendingError = null; - if (streamKey !== key || (video.readyState >= 3 && !video.paused)) return; - reported.error = key; - report({ error: { fatal: true, message: err.message || 'Playback failed' } }); - toast('Source failed, trying the next one…'); - }, 4000); - } else if (retriedKey !== key) { - // a follower's failure may be local (network hiccup): reload once - retriedKey = key; - setTimeout(() => { - if (streamKey === key && state && state.stream) loadStream(state); - }, 2000); - } else toast('This source does not play here.'); - }, - onLevels() { - applyQuality(); - reportLevels(); - }, -}); - -let pendingError = null; -function cancelPendingError() { - if (pendingError) clearTimeout(pendingError); - pendingError = null; -} - -function torrentMsg(t) { - if (!t) return ''; - const pct = t.progress != null ? ` ${Math.round(t.progress * 100)}%` : ''; - return t.peers ? `Downloading · ${t.peers} peers${pct}` : 'Connecting to peers…'; -} - -function keyOf(stream) { - const pb = stream.playback || {}; - return `${stream.id}|${pb.fallback || pb.url}`; -} - -/** Always the proxied URL: playback.fallback when present, else playback.url. */ -function proxied(stream) { - const pb = { ...(stream.playback || {}) }; - if (pb.fallback) pb.url = pb.fallback; - delete pb.fallback; - return { ...stream, playback: pb }; -} - -async function loadStream(s) { - const key = keyOf(s.stream); - streamKey = key; - appliedSub = null; - appliedQuality = null; - reported.duration = 0; - reported.levels = ''; - reported.buffering = null; - spinner(true, 'Loading…'); - if ((s.stream.playback || {}).kind === 'hls') await ensureHls(); - if (streamKey !== key) return; - const target = S.targetTime(state, offset()); - player.load(proxied(state.stream), { startAt: target, autoplay: state.playing }); - lastSeekAt = Date.now(); - forceSync = false; - applySubtitle(); -} - -function unloadStream() { - if (!streamKey) return; - streamKey = ''; - player.stop(); - spinner(false); - video.playbackRate = 1; -} - -function applySubtitle() { - if (!state || appliedSub === state.subtitle) return; - appliedSub = state.subtitle; - player.setSubtitle(Number.isInteger(state.subtitle) ? state.subtitle : -1); -} - -function applyQuality() { - if (!state || appliedQuality === state.quality || !player.levels().length) return; - appliedQuality = state.quality; - player.setLevel(Number.isInteger(state.quality) ? state.quality : -1); -} - -function applyPlayPause() { - if (!state || !player.mode) return; - if (state.playing) { - if (video.paused && !blocked) player.play(); - } else if (!video.paused) player.pause(); -} - -function onBlocked() { - // autoplay without a gesture was refused: try muted, else ask for a click - if (!state || !state.playing) return; - video.muted = true; - video.play().then( - () => { - ui.unmuteBtn.hidden = false; - }, - () => { - video.muted = false; - blocked = true; - ui.joinBtn.hidden = false; - spinner(false); - poke(); - }, - ); -} - -ui.joinBtn.addEventListener('click', (e) => { - e.stopPropagation(); - blocked = false; - ui.joinBtn.hidden = true; - video.muted = false; - forceSync = true; - player.play(); -}); - -ui.unmuteBtn.addEventListener('click', (e) => { - e.stopPropagation(); - video.muted = false; - ui.unmuteBtn.hidden = true; -}); - -/* ---- leader reports ------------------------------------------------------ */ - -function reportDuration() { - if (!isLeader()) return; - const d = player.duration(); - if (d > 0 && Math.abs(d - reported.duration) > 1) { - reported.duration = d; - report({ duration: d }); - } -} - -function reportLevels() { - if (!isLeader()) return; - const levels = player.levels().map((l) => ({ index: l.index, height: l.height, bitrate: l.bitrate })); - const json = JSON.stringify(levels); - if (levels.length && json !== reported.levels) { - reported.levels = json; - report({ levels }); - } -} - -// buffering=true only after a 1s stall (hls fires short 'waiting' blips), false at once -let bufTimer = null; -function reportBuffering(b) { - clearTimeout(bufTimer); - const go = () => { - if (reported.buffering === b || !isLeader()) return; - reported.buffering = b; - report({ buffering: b }); - }; - if (b) bufTimer = setTimeout(go, 1000); - else go(); -} - -setInterval(() => { - // never while stalled: a stale position would rewind everyone - if (isLeader() && state.playing && player.started && !video.paused && video.readyState >= 3 && !video.seeking) { - report({ position: player.currentTime() }); - } -}, HEARTBEAT_MS); - -/* ---- state --------------------------------------------------------------- */ - -function onState(next) { - if (!next) return; - // first estimate before any pong lands (ignores latency) - if (!clock.count && Number.isFinite(next.now)) clock.add(next.now - Date.now()); - const prev = state; - state = next; - - if (next.notice && next.notice !== lastNotice) toast(next.notice); - lastNotice = next.notice || null; - - render(); - - if (!next.media || !next.stream) { - unloadStream(); - return; - } - if (keyOf(next.stream) !== streamKey) { - loadStream(next); - return; - } - if (S.isJump(prev, next, offset())) forceSync = true; - if (prev && prev.playing !== next.playing) poke(); - applySubtitle(); - applyQuality(); - applyPlayPause(); - // a new leader picks up the reporting duties - if (isLeader() && (!prev || prev.leader !== next.leader)) { - reported.duration = 0; - reported.levels = ''; - reported.buffering = null; - reportDuration(); - reportLevels(); - } -} - -/* ---- sync loop ----------------------------------------------------------- */ - -setInterval(() => { - if (!state || !state.stream || !streamKey || !player.mode || blocked) return; - const now = Date.now(); - const ready = state.playing ? video.readyState >= 3 : video.readyState >= 1; - if (!ready || video.seeking) return; - applyPlayPause(); - const target = S.targetTime(state, offset(), now); - const cooldown = player.mode === 'remux' ? 6000 : 2500; - const act = S.driftAction(player.currentTime(), target, { playing: state.playing, canSeek: forceSync || now - lastSeekAt > cooldown }); - if (act.action === 'seek') { - lastSeekAt = now; - forceSync = false; - video.playbackRate = 1; - player.seek(target); - } else if (video.playbackRate !== act.rate) video.playbackRate = act.rate; - if (isLeader()) { - reportDuration(); - reportLevels(); - } -}, SYNC_MS); - -/* ---- render -------------------------------------------------------------- */ - -const KIND = { hls: 'HLS', file: 'MP4', remux: 'Remux', torrent: 'Torrent' }; - -function sourceLabel(s) { - if (!s) return ''; - const px = Number(s.pixels) || 0; - const q = px >= 2160 ? '4K' : px ? `${px}p` : s.quality || ''; - const kind = KIND[(s.playback && s.playback.kind) || 'file'] || ''; - return [s.provider, q, kind].filter(Boolean).join(' · '); -} - -function render() { - const s = state; - if (!s.media) { - setView('idle'); - ui.idleMsg.textContent = 'Use /watch in chat to pick something'; - ui.backdrop.style.backgroundImage = ''; - document.title = 'bug.tv'; - return; - } - const m = s.media; - const name = m.title || 'bug.tv'; - const tv = m.type === 'tv'; - ui.title.textContent = name + (!tv && m.year ? ` (${m.year})` : ''); - ui.sub.textContent = tv ? `S${m.season} · E${m.episode}${m.episodeTitle ? ` — ${m.episodeTitle}` : ''}` : ''; - ui.srcLabel.textContent = sourceLabel(s.stream); - document.title = `${tv ? `${name} S${m.season}E${m.episode}` : name} — bug.tv`; - const bg = imgUrl(m.backdrop || m.still || m.poster, 'w1280'); - const bgCss = bg ? `url("${bg}")` : ''; - if (ui.backdrop.style.backgroundImage !== bgCss) ui.backdrop.style.backgroundImage = bgCss; - - if (!s.stream) { - setView('finding'); - ui.findTitle.textContent = ui.title.textContent + (tv ? ` · S${m.season}E${m.episode}` : ''); - ui.findMsg.textContent = s.notice || 'Finding sources…'; - return; - } - setView('play'); - ui.playBtn.innerHTML = s.playing ? ICON.pause : ICON.play; - ui.playBtn.setAttribute('aria-label', s.playing ? 'Pause' : 'Play'); - const n = (s.viewers || []).length; - ui.viewers.innerHTML = `${ICON.people}${n}`; - ui.viewers.title = `${n} watching${isLeader() ? ' · you are the leader' : ''}`; - renderTime(); -} - -function duration() { - return (state && state.duration) || player.duration() || 0; -} - -function renderTime() { - if (!state || !state.stream) return; - const d = duration(); - const t = player.mode && video.readyState >= 1 ? player.currentTime() : S.targetTime(state, offset()); - ui.time.textContent = `${S.formatTime(t)} / ${S.formatTime(d)}`; - ui.seekFill.style.width = d > 0 ? `${Math.min(100, (t / d) * 100)}%` : '0%'; - let buf = 0; - for (const [a, b] of player.buffered()) if (t >= a - 1 && t <= b + 1) buf = b; - ui.seekBuf.style.width = d > 0 ? `${Math.min(100, (buf / d) * 100)}%` : '0%'; - ui.seek.setAttribute('aria-valuemax', String(Math.round(d))); - ui.seek.setAttribute('aria-valuenow', String(Math.round(t))); -} -setInterval(renderTime, 250); - -/* ---- input --------------------------------------------------------------- */ - -function seekRatio(clientX) { - const r = ui.seek.getBoundingClientRect(); - return Math.min(1, Math.max(0, (clientX - r.left) / r.width)); -} - -ui.seek.addEventListener('click', (e) => { - e.stopPropagation(); - const d = duration(); - if (d > 0) cmd('seek', { t: Math.round(seekRatio(e.clientX) * d) }); -}); -ui.seek.addEventListener('pointermove', (e) => { - const d = duration(); - if (!d) return; - const r = seekRatio(e.clientX); - ui.seekTip.hidden = false; - ui.seekTip.textContent = S.formatTime(r * d); - ui.seekTip.style.left = `${r * 100}%`; -}); -ui.seek.addEventListener('pointerleave', () => (ui.seekTip.hidden = true)); - -ui.playBtn.addEventListener('click', (e) => { - e.stopPropagation(); - cmd(state && state.playing ? 'pause' : 'play'); -}); - -// a click on the video only reveals the controls (no accidental room-wide pause on touch) -video.addEventListener('dblclick', () => !blocked && cmd(state && state.playing ? 'pause' : 'play')); - -document.addEventListener('keydown', (e) => { - if (!state || !state.stream || e.ctrlKey || e.metaKey || e.altKey) return; - if (e.key === ' ' || e.key === 'k') cmd(state.playing ? 'pause' : 'play'); - else if (e.key === 'ArrowLeft' || e.key === 'j') cmd('seekBy', { d: -10 }); - else if (e.key === 'ArrowRight' || e.key === 'l') cmd('seekBy', { d: 10 }); - else if (e.key === 'm') video.muted = !video.muted; - else return; - e.preventDefault(); - poke(); -}); - -for (const ev of ['pointermove', 'pointerdown', 'touchstart']) ui.app.addEventListener(ev, poke, { passive: true }); - -/* ---- boot ---------------------------------------------------------------- */ - -(async () => { - ui.idleMsg.textContent = 'Connecting…'; - try { - hello = inDiscord ? await discordHello() : devHello(); - } catch (e) { - fail(e && e.message ? e.message : String(e)); - return; - } - connect(); - poke(); -})(); - -// debug hook for headless checks -window.__tv = { player, video, get state() { return state; }, get me() { return me; }, offset, cmd }; diff --git a/activity/js/sync.js b/activity/js/sync.js deleted file mode 100644 index 2c7dace..0000000 --- a/activity/js/sync.js +++ /dev/null @@ -1,88 +0,0 @@ -/* - sync.js — pure playback-sync math (no DOM), unit-tested in test/sync.test.js. - - Clock: the server sends `updatedAt`/`now` in its own clock. `offset` = server − local (ms), - estimated from ping/pong as the median of the last few samples. -*/ - -export const HARD_DRIFT = 1.5; // s — beyond this: seek -export const SOFT_DRIFT = 0.3; // s — beyond this: nudge playbackRate -export const RATE_SLOW = 0.95; -export const RATE_FAST = 1.05; -export const JUMP = 0.5; // s — a state change that moves the target by more than this is an explicit seek - -/** Where playback should be right now, in seconds. */ -export function targetTime(state, offset = 0, now = Date.now()) { - if (!state) return 0; - let t = Number(state.position) || 0; - if (state.playing) t += Math.max(0, (now + offset - (Number(state.updatedAt) || 0)) / 1000); - const d = Number(state.duration) || 0; - if (d > 0) t = Math.min(t, d); - return Math.max(0, t); -} - -/** - * What to do about the difference between the local player and the target. - * → { action: 'seek' | 'rate' | 'none', drift, rate } - * drift > 0 means the local player is ahead. - * `canSeek` false (cooldown after a recent seek) downgrades a hard seek to a rate nudge. - */ -export function driftAction(current, target, { playing = true, canSeek = true } = {}) { - const drift = current - target; - const abs = Math.abs(drift); - if (!playing) { - // paused: rate does nothing, so line up exactly once we're noticeably off - if (abs > SOFT_DRIFT && canSeek) return { action: 'seek', drift, rate: 1 }; - return { action: 'none', drift, rate: 1 }; - } - if (abs > HARD_DRIFT && canSeek) return { action: 'seek', drift, rate: 1 }; - if (abs > SOFT_DRIFT) return { action: 'rate', drift, rate: drift > 0 ? RATE_SLOW : RATE_FAST }; - return { action: 'none', drift, rate: 1 }; -} - -/** True when `next` moved the playhead (seek, source/episode change) rather than just ticking on. */ -export function isJump(prev, next, offset = 0, now = Date.now()) { - if (!prev || !next) return true; - return Math.abs(targetTime(prev, offset, now) - targetTime(next, offset, now)) > JUMP; -} - -/** One ping/pong round trip → { offset, rtt } (ms). */ -export function offsetSample(sentAt, serverNow, recvAt) { - const rtt = Math.max(0, recvAt - sentAt); - return { offset: serverNow - (sentAt + rtt / 2), rtt }; -} - -export function median(values) { - const v = values.filter((x) => Number.isFinite(x)).sort((a, b) => a - b); - if (!v.length) return 0; - const m = v.length >> 1; - return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2; -} - -/** Rolling clock-offset estimator: median of the last `size` samples. */ -export function createClock(size = 5) { - const samples = []; - return { - add(sample) { - const o = typeof sample === 'number' ? sample : sample && sample.offset; - if (!Number.isFinite(o)) return; - samples.push(o); - while (samples.length > size) samples.shift(); - }, - offset() { - return median(samples); - }, - get count() { - return samples.length; - }, - }; -} - -export function formatTime(sec) { - sec = Math.max(0, Math.floor(Number(sec) || 0)); - const h = Math.floor(sec / 3600); - const m = Math.floor((sec % 3600) / 60); - const s = sec % 60; - const ss = String(s).padStart(2, '0'); - return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`; -} diff --git a/activity/js/urls.js b/activity/js/urls.js deleted file mode 100644 index 23e7f71..0000000 --- a/activity/js/urls.js +++ /dev/null @@ -1,52 +0,0 @@ -/* - urls.js — where things live, inside Discord vs local dev. - - Inside Discord the Activity runs on https://.discordsays.com and may only talk to that - origin; Discord's URL mappings forward path prefixes (most specific wins): - / → our server (tv-activity.bug.tools): /api/config, /api/token, /ws, static files - /tv → api-tv.bug.tools (bug-tv API) - /img → image.tmdb.org - So inside Discord bug-tv URLs become same-origin "/tv/v1/…". The bug-tv prefix cannot be "/api" - because "/api/token" must reach our server (see docs/protocol.md "Deviations"). - patchUrlMappings() (called in main.js) only rewrites *absolute* URLs of the mapped hosts; the - relative ones built here already hit the right prefix. The legacy "/.proxy/" prefix is not needed. - - Dev (no frame_id): bug-tv base = ?api= (default http://127.0.0.1:8789), ws on this origin. -*/ - -const params = new URLSearchParams(typeof location !== 'undefined' ? location.search : ''); - -export const inDiscord = - typeof location !== 'undefined' && (params.has('frame_id') || /\.discordsays\.com$/.test(location.hostname)); - -export const TV_PREFIX = '/tv'; -export const IMG_PREFIX = '/img'; - -export function param(name) { - return params.get(name); -} - -export function apiBase() { - if (inDiscord) return TV_PREFIX; - return (params.get('api') || 'http://127.0.0.1:8789').replace(/\/+$/, ''); -} - -/** bug-tv API-relative URL ("/v1/p/…") → fetchable URL. Absolute URLs pass through. */ -export function resolveUrl(u) { - const s = String(u || ''); - if (/^[a-z][a-z0-9+.-]*:/i.test(s)) return s; - return apiBase() + (s.startsWith('/') ? s : `/${s}`); -} - -export function wsUrl() { - return `${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/ws`; -} - -/** TMDB image: a path ("/abc.jpg") or a full image.tmdb.org URL → loadable URL. */ -export function imgUrl(p, size = 'w780') { - if (!p) return ''; - let u = String(p); - if (u.startsWith('/')) u = `https://image.tmdb.org/t/p/${size}${u}`; - if (inDiscord) u = u.replace(/^https?:\/\/image\.tmdb\.org/, IMG_PREFIX); - return u; -} diff --git a/activity/overlay.css b/activity/overlay.css new file mode 100644 index 0000000..c73f0dd --- /dev/null +++ b/activity/overlay.css @@ -0,0 +1,190 @@ +/* + overlay.css — the watch-party overlay injected by discord.js on top of the bug.tv site: + members pill (top right), viewer banner, toasts, and viewer input blocking. +*/ +.bp-root { + --bp-accent: #c084fc; + --bp-accent-soft: rgba(192, 132, 252, 0.18); + --bp-glass: rgba(15, 15, 18, 0.72); + --bp-border: rgba(255, 255, 255, 0.14); + --bp-text: #f4f4f6; + --bp-text-2: #b6b6c0; + --bp-danger: #ff5f5f; + --bp-warn: #f5a524; + position: fixed; + top: calc(var(--header-h, 72px) + max(8px, env(safe-area-inset-top))); + right: max(16px, env(safe-area-inset-right)); + z-index: 2147483000; + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 8px; + pointer-events: none; + font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + font-size: 13px; + line-height: 1.3; + color: var(--bp-text); +} +.bp-root * { box-sizing: border-box; } +.bp-root button { font: inherit; color: inherit; } + +.bp-glass { + background: var(--bp-glass); + border: 1px solid var(--bp-border); + -webkit-backdrop-filter: blur(14px) saturate(1.4); + backdrop-filter: blur(14px) saturate(1.4); + box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45); +} + +/* ---- pill ----------------------------------------------------------------------------- */ +.bp-pill { + pointer-events: auto; + display: inline-flex; + align-items: center; + gap: 8px; + height: 36px; + padding: 0 12px 0 6px; + border-radius: 999px; + cursor: pointer; + opacity: 0.9; + transition: opacity 0.2s, border-color 0.2s; + max-width: min(320px, calc(100vw - 32px)); +} +.bp-pill:hover { opacity: 1; border-color: rgba(192, 132, 252, 0.5); } +.bp-dot { + width: 8px; + height: 8px; + border-radius: 50%; + flex-shrink: 0; + margin-left: 4px; + background: var(--bp-warn); + box-shadow: 0 0 0 3px rgba(245, 165, 36, 0.18); +} +.bp-root[data-conn="live"] .bp-dot { background: var(--bp-accent); box-shadow: 0 0 0 3px var(--bp-accent-soft); } +.bp-root[data-conn="error"] .bp-dot { background: var(--bp-danger); box-shadow: 0 0 0 3px rgba(255, 95, 95, 0.18); } +.bp-avatars { display: inline-flex; align-items: center; } +.bp-av { + width: 24px; + height: 24px; + border-radius: 50%; + flex-shrink: 0; + border: 2px solid rgba(15, 15, 18, 0.9); + background: #26262d; + color: var(--bp-text); + font-size: 11px; + font-weight: 700; + display: inline-flex; + align-items: center; + justify-content: center; + overflow: hidden; + text-transform: uppercase; +} +.bp-av + .bp-av { margin-left: -8px; } +.bp-av img { width: 100%; height: 100%; object-fit: cover; display: block; } +.bp-av.is-host { border-color: var(--bp-accent); } +.bp-more { margin-left: 4px; color: var(--bp-text-2); font-size: 12px; font-weight: 600; } +.bp-host { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-weight: 600; +} +.bp-host.is-me { color: var(--bp-accent); } + +/* ---- member list (pill click) -------------------------------------------------------- */ +.bp-list { + pointer-events: auto; + min-width: 200px; + max-width: min(320px, calc(100vw - 32px)); + padding: 6px; + border-radius: 14px; +} +.bp-list[hidden] { display: none; } +.bp-row { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 10px; } +.bp-row .bp-av { width: 26px; height: 26px; } +.bp-row__name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.bp-row__tag { color: var(--bp-text-2); font-size: 11px; } +.bp-status { padding: 6px 8px 4px; color: var(--bp-text-2); font-size: 12px; } + +/* ---- viewer banner -------------------------------------------------------------------- */ +.bp-banner { + pointer-events: auto; + display: inline-flex; + align-items: center; + gap: 10px; + padding: 8px 8px 8px 14px; + border-radius: 12px; + border-color: rgba(192, 132, 252, 0.4); + max-width: min(360px, calc(100vw - 32px)); +} +.bp-banner[hidden] { display: none; } +.bp-banner__text { min-width: 0; } +.bp-banner__text b { color: var(--bp-accent); font-weight: 700; } +.bp-banner__sub { display: block; color: var(--bp-text-2); font-size: 11px; margin-top: 1px; } +.bp-x { + flex-shrink: 0; + width: 26px; + height: 26px; + border: 0; + border-radius: 8px; + background: transparent; + cursor: pointer; + color: var(--bp-text-2); + font-size: 16px; + line-height: 1; +} +.bp-x:hover { background: rgba(255, 255, 255, 0.1); color: var(--bp-text); } + +/* ---- toasts --------------------------------------------------------------------------- */ +.bp-toasts { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; } +.bp-toast { + padding: 8px 12px; + border-radius: 10px; + opacity: 0; + transform: translateY(-6px); + transition: opacity 0.25s, transform 0.25s; + max-width: min(320px, calc(100vw - 32px)); +} +.bp-toast.is-shown { opacity: 1; transform: none; } +.bp-toast--host { border-color: rgba(192, 132, 252, 0.5); } +.bp-toast--error { border-color: rgba(255, 95, 95, 0.5); } + +/* ---- viewers: look-but-don't-touch --------------------------------------------------- + discord.js also blocks clicks/keys in the capture phase; this makes it visible + (no hover states, no pointer cursor) and keeps scrolling working. */ +html.party-viewer body a, +html.party-viewer body button, +html.party-viewer body input, +html.party-viewer body select, +html.party-viewer body textarea, +html.party-viewer body label, +html.party-viewer body summary, +html.party-viewer body [role="slider"], +html.party-viewer body [role="button"], +html.party-viewer body [role="menuitem"], +html.party-viewer body [tabindex], +html.party-viewer .pl-video, +html.party-viewer .pl-seek { + pointer-events: none !important; +} +html.party-viewer body .pl-volwrap, +html.party-viewer body .pl-volwrap *, +html.party-viewer body [data-party-allow], +html.party-viewer body [data-party-allow] *, +html.party-viewer body .pl-btn[aria-label^="Fullscreen"], +html.party-viewer body .pl-btn[aria-label^="Exit fullscreen"], +html.party-viewer body .bp-root, +html.party-viewer body .bp-root * { + pointer-events: auto !important; +} +html.party-viewer body .bp-root { pointer-events: none !important; } +html.party-viewer .header-search { opacity: 0.55; } + +@media (max-width: 640px) { + .bp-root { right: 12px; } + .bp-host { max-width: 110px; } +} +@media (prefers-reduced-motion: reduce) { + .bp-toast { transition: none; } +} diff --git a/activity/package.json b/activity/package.json deleted file mode 100644 index 5ffd980..0000000 --- a/activity/package.json +++ /dev/null @@ -1 +0,0 @@ -{ "type": "module" } diff --git a/config.example.json b/config.example.json index 3c41086..853f699 100644 --- a/config.example.json +++ b/config.example.json @@ -1,9 +1,7 @@ { "port": 8791, - "apiUrl": "http://127.0.0.1:8789", "applicationId": "YOUR_APPLICATION_ID", - "guildIds": [], "tokenFile": "/path/to/bot-token", "clientSecretFile": "/path/to/client-secret", - "tmdbKey": "YOUR_TMDB_API_KEY" + "activityDir": "./site" } diff --git a/docs/protocol.md b/docs/protocol.md index 4f973fe..58fe316 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -1,104 +1,74 @@ -# tv-discord: module and protocol contract +# tv-discord v2: watch-party protocol -Every workstream codes against this file. If you need to deviate, keep it backwards compatible and record it under "Deviations" at the bottom. +The Activity is the full bug.tv site (built from the bug-tv repo's `packages.web`) plus a small overlay script (`activity/js/discord.js`). Whoever starts an Activity instance is the **host**. The host's site does everything: search, scraping, source picking and failover. The server relays what the host is doing to everyone else in the instance (the **viewers**), who mirror it. -## Runtime -- Node 22+, CommonJS in `src/`. Deps: `discord.js` 14, `ws` 8. The Activity bundles `@discord/embedded-app-sdk` with esbuild (`npm run build:activity` → `activity/dist/main.js`). -- The bug-tv API contract is `~/library/repositories/tv/docs/api.md`: `GET /v1/streams` (SSE `meta`/`streams`/`provider`/`done`, or `?format=json`), `GET /v1/prefetch`, and the Stream shape with `playback {kind,url,fallback,status}` (URLs relative to the API base). +There is no bot gateway or slash commands. The bot token is only used for `GET /applications/{app}/activity-instances/{instanceId}` (membership checks) and the client secret for the OAuth code exchange. -## Config (`src/config.js`, already written) -`loadConfig()` reads JSON from `$BUG_TV_DISCORD_CONFIG` (default `./config.json`): +## Server (`src/server.js`) +`createServer(cfg, { discordFetch?, now?, log? })` → `http.Server`. +- **HTTP:** + - Static files from `cfg.activityDir` (the merged site + overlay), with SPA fallback to `index.html`. A leading `/.proxy` is stripped. + - `GET /api/config` → `{ applicationId, dev }` + - `POST /api/token {code}` → `{ access_token }`, via Discord oauth2/token with client credentials. + - `GET /healthz` +- **WebSocket `/ws`** (JSON): + - client → server + - `{t:'hello', token, instanceId, channelId?, guildId?}`: the server checks the token with `GET /users/@me` (cached 10 min), then membership: `GET /applications/{cfg.applicationId}/activity-instances/{instanceId}` with `Authorization: Bot ${cfg.token}`. The result lists `users: [id…]` and is cached 10s per instance; one refetch is allowed on a miss. If the user isn't in the list → `error` + close. In dev (`cfg.dev === true`), `{t:'hello', dev:true, userId, username, instanceId}` is accepted without Discord. + - `{t:'route', path}`: host only. + - `{t:'play', snapshot}`: host only. The server stamps `snapshot.at = now()` on receipt and stores it. + - `{t:'ping', at}`: anyone. + - Anything from a non-host apart from `ping` is ignored. + - server → client + - `{t:'welcome', you:{id,username,avatar}, host, members:[{id,username,avatar}], route, play, now}` + - `{t:'host', host}`: on handover. + - `{t:'members', members}` + - `{t:'route', path}` and `{t:'play', snapshot}`: relayed to everyone except the host. + - `{t:'pong', at, now}` + - `{t:'error', message}` +- **Hubs:** one per `instanceId`, `{ members (join order), host, route, play }`. + - The first member is host. When the host's last socket closes, the earliest remaining member becomes host, and everyone gets `host`. + - A hub is dropped 10 minutes after it empties. If the original host rejoins within that window, they get host back. + - A user with several sockets counts once. + +## Snapshot (`play`) ``` -{ host, port (8791), apiUrl ("http://127.0.0.1:8789", server-side calls), applicationId, guildIds: [], - token | tokenFile, clientSecret | clientSecretFile, tmdbKey | tmdbKeyFile, activityDir (default ./activity), - providers: [] (empty = bug-tv defaults) } +{ path: "/watch/tv/1399/1/2", + media: { type, id, season, episode }, + stream: | null, + subtitle: { index, lang, label } | null, // viewers match lang+label, index as fallback + quality: -1 | , // -1 = auto + audio: -1 | , + playing: bool, position: seconds, duration: seconds, at: } ``` -`*File` values are read and trimmed into `token`, `clientSecret` and `tmdbKey`. +Viewers compute the target time as `position + (playing ? (serverNow - at) / 1000 : 0)`. Server time comes from `pong` (median of the last 5 offsets). -## Wiring (`src/index.js`, already written) -```js -const rooms = createRooms(cfg); // src/room.js -const bot = await createBot(cfg, rooms); // src/bot/index.js → { client, isInVoice(channelId, userId), voiceMembers(channelId) } -const server = createServer(cfg, rooms, { isInVoice: bot.isInVoice }); // src/server.js → http.Server -``` +## Overlay (`activity/js/discord.js`, bundled with `@discord/embedded-app-sdk`) +1. If not inside Discord (no `frame_id`), use dev mode: `?user=&instance=`, and the server must have `cfg.dev`. +2. In Discord: + - `new DiscordSDK(applicationId)` → `ready()` → `patchUrlMappings([{prefix:'/tv',target:'api-tv.bug.tools'},{prefix:'/tmdb',target:'api.themoviedb.org'},{prefix:'/img',target:'image.tmdb.org'}])` + - `authorize` → `POST /api/token` → `authenticate` + - WS `hello` with `sdk.instanceId`. +3. Attach to the site: `window.bugtvParty.attach(transport)` (see bug-tv `docs/api.md` → "Party"), then feed it server messages through `party.receive(msg)`. +4. UI: a small top-right pill showing member avatars and "👑 name". For viewers it adds a banner "👑 is in control", and `html.party-viewer` blocks clicks and inputs outside the player's volume/fullscreen controls. +5. Reconnect with backoff. On reconnect, resend `hello`, and the host resends route and snapshot. -## Rooms (`src/room.js`, workstream A) -`createRooms(cfg)` → `{ get(id), create({ id, guildId, textChannelId }), delete(id), all() }`. `id` is the **voice channel id**. +## Build (`nix/activity.nix`) +Start from bug-tv `packages.web.override { apiBase = "/tv"; }`, then in `index.html` and `404.html`: +- set ``, `` and `` +- remove the Google Fonts `` tags +- append `` and `\n|' "$f" +done + +cp "$here/activity/overlay.css" "$out/overlay.css" +# shellcheck disable=SC2086 +(cd "$here" && $esbuild activity/js/discord.js --bundle --format=esm --target=es2020 --minify --legal-comments=none \ + --log-level=warning --outfile="$out/discord.js") + +echo "build-activity: $out (api $api)" diff --git a/scripts/register-commands.js b/scripts/register-commands.js deleted file mode 100644 index 7059e76..0000000 --- a/scripts/register-commands.js +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env node -// Register slash commands without starting the bot. -// node scripts/register-commands.js → guild-scoped for cfg.guildIds, else global -// node scripts/register-commands.js --global → global -// node scripts/register-commands.js --clear → remove them (same scope rules) - -const { REST, Routes } = require('discord.js'); -const { loadConfig } = require('../src/config'); -const { commandDefs } = require('../src/bot/commands'); - -async function main() { - const cfg = loadConfig(); - const args = process.argv.slice(2); - const body = args.includes('--clear') ? [] : commandDefs; - const rest = new REST({ version: '10' }).setToken(cfg.token); - const guilds = args.includes('--global') ? [] : cfg.guildIds || []; - if (guilds.length) { - for (const g of guilds) { - const res = await rest.put(Routes.applicationGuildCommands(cfg.applicationId, g), { body }); - console.log(`guild ${g}: ${res.length} commands`); - } - } else { - // keep Discord's Activity entry-point command (type 4): a bulk overwrite without it fails - const existing = await rest.get(Routes.applicationCommands(cfg.applicationId)); - const res = await rest.put(Routes.applicationCommands(cfg.applicationId), { - body: [...body, ...existing.filter((c) => c.type === 4)], - }); - console.log(`global: ${res.length} commands (may take up to an hour to appear)`); - } -} - -main().catch((e) => { - console.error(e); - process.exit(1); -}); diff --git a/scripts/vendor-bugtv.sh b/scripts/vendor-bugtv.sh deleted file mode 100755 index 89c4c7d..0000000 --- a/scripts/vendor-bugtv.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bash -# Copies bug-tv's player engine + hls.js into activity/vendor/bugtv/, mirroring bug-tv's web/ layout: -# activity/vendor/bugtv/js/ui/player.js (unchanged copy) -# activity/vendor/bugtv/js/config.js (shim: resolveUrl from activity/js/urls.js) -# activity/vendor/bugtv/vendor/hls.min.js (unchanged copy; main.js preloads it as window.Hls) -# Run before `npm run build:activity` (esbuild bundles player.js + the shim into dist/main.js). -# -# usage: scripts/vendor-bugtv.sh [activity dir] -set -euo pipefail - -web="${1:?usage: vendor-bugtv.sh [activity dir]}" -here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -activity="${2:-$here/activity}" -out="$activity/vendor/bugtv" - -for f in js/ui/player.js vendor/hls.min.js; do - [ -f "$web/$f" ] || { echo "vendor-bugtv: missing $web/$f" >&2; exit 1; } -done - -rm -rf "$out" -mkdir -p "$out/js/ui" "$out/vendor" -install -m 0644 "$web/js/ui/player.js" "$out/js/ui/player.js" -install -m 0644 "$web/vendor/hls.min.js" "$out/vendor/hls.min.js" -cat > "$out/js/config.js" <<'EOF' -// generated by scripts/vendor-bugtv.sh — player.js imports only resolveUrl from here -export { resolveUrl } from '../../../js/urls.js'; -EOF -echo "vendor-bugtv: $web → $out" diff --git a/src/bot/autocomplete.js b/src/bot/autocomplete.js deleted file mode 100644 index 911ce0d..0000000 --- a/src/bot/autocomplete.js +++ /dev/null @@ -1,26 +0,0 @@ -// /watch query autocomplete → TMDB search/multi. - -const { clip } = require('./render'); - -function choiceFor(r) { - return { - name: clip(`${r.title}${r.year ? ` (${r.year})` : ''} · ${r.type === 'tv' ? 'Series' : 'Movie'}`, 100), - value: `${r.type}:${r.id}`, - }; -} - -async function handleAutocomplete(interaction, ctx) { - const focused = interaction.options.getFocused(true); - if (focused.name !== 'query') return interaction.respond([]); - const q = String(focused.value || '').trim(); - if (q.length < 2) return interaction.respond([]); - let results = []; - try { - results = await ctx.bugtv.searchMulti(q); - } catch (e) { - console.warn(`[bot] autocomplete: ${e.message}`); - } - return interaction.respond(results.slice(0, 25).map(choiceFor)).catch(() => {}); -} - -module.exports = { handleAutocomplete, choiceFor }; diff --git a/src/bot/commands.js b/src/bot/commands.js deleted file mode 100644 index c9b7530..0000000 --- a/src/bot/commands.js +++ /dev/null @@ -1,135 +0,0 @@ -// Slash commands: /watch, /np, /stop. - -const { MessageFlags } = require('discord.js'); -const { render } = require('./render'); - -const STRING = 3; -const INTEGER = 4; - -const commandDefs = [ - { - name: 'watch', - description: 'Watch a movie or series together in your voice channel', - contexts: [0], - integration_types: [0], - options: [ - { type: STRING, name: 'query', description: 'Movie or series to watch', required: true, autocomplete: true, max_length: 100 }, - { type: INTEGER, name: 'season', description: 'Season (series only)', min_value: 1, max_value: 500 }, - { type: INTEGER, name: 'episode', description: 'Episode (series only)', min_value: 1, max_value: 5000 }, - ], - }, - { name: 'np', description: 'Repost the player controls for your voice channel', contexts: [0], integration_types: [0] }, - { name: 'stop', description: 'Stop the watch session in your voice channel', contexts: [0], integration_types: [0] }, -]; - -const ephemeral = (content) => ({ content, flags: MessageFlags.Ephemeral, allowedMentions: { parse: [] } }); - -// the caller's voice channel: gateway cache first, then ask Discord (the cache can miss -// users who joined before the bot connected, or right after a reconnect) -async function userVoiceChannel(interaction) { - const g = interaction.guild; - if (!g) return null; - const cached = g.voiceStates.cache.get(interaction.user.id); - if (cached && cached.channelId) return cached.channelId; - try { - const vs = await g.voiceStates.fetch(interaction.user.id, { force: true }); - return (vs && vs.channelId) || null; - } catch { - return null; // 404 = not in voice - } -} - -// "movie:550" / "tv:1399" from autocomplete, else null (free text) -function parsePick(value) { - const m = /^(movie|tv):(\d+)$/.exec(String(value || '').trim()); - return m ? { type: m[1], id: Number(m[2]) } : null; -} - -async function deleteMessage(client, channelId, messageId) { - if (!channelId || !messageId) return; - try { - const ch = client.channels.cache.get(channelId) || (await client.channels.fetch(channelId)); - await ch.messages.delete(messageId); - } catch { - /* already gone or no access */ - } -} - -// post `payload` as the reply to `interaction` and make it the room's control message -async function adoptReply(ctx, room, interaction, deferred) { - const old = { channelId: room.state.textChannelId, messageId: room.state.messageId }; - room.state.messageId = null; // stop the updater editing the old message - const payload = { ...render(room.state, ctx.ui(room.id)), allowedMentions: { parse: [] } }; - const msg = deferred - ? await interaction.editReply(payload) - : await interaction.reply({ ...payload, withResponse: true }).then((r) => r.resource.message); - room.state.textChannelId = interaction.channelId; - room.state.messageId = msg.id; - ctx.updater.remember(room, interaction, msg.id); - if (old.messageId && old.messageId !== msg.id) deleteMessage(ctx.client, old.channelId, old.messageId); - ctx.updater.schedule(room, false); // catch anything that changed while we were posting -} - -// commands can be installed without the bot user joining the server; then Discord never -// sends it voice states and nothing here can work -function notInGuild(interaction, ctx) { - if (interaction.guild) return false; - const invite = `https://discord.com/oauth2/authorize?client_id=${ctx.cfg.applicationId}&scope=bot%20applications.commands&permissions=84992`; - interaction.reply(ephemeral(`The bot user isn't in this server yet, so it can't see voice channels. Add it with this link: ${invite}`)).catch(() => {}); - return true; -} - -async function watch(interaction, ctx) { - if (notInGuild(interaction, ctx)) return; - const vc = await userVoiceChannel(interaction); - if (!vc) return interaction.reply(ephemeral('Join a voice channel first, then use `/watch` there.')); - const raw = interaction.options.getString('query', true); - const season = interaction.options.getInteger('season'); - const episode = interaction.options.getInteger('episode'); - await interaction.deferReply(); - - let pick = parsePick(raw); - if (!pick) { - const results = await ctx.bugtv.searchMulti(raw).catch(() => []); - if (!results.length) return interaction.editReply({ content: `Nothing found for “${raw.slice(0, 80)}”.`, allowedMentions: { parse: [] } }); - pick = results[0]; - } - - const room = ctx.rooms.create({ id: vc, guildId: interaction.guildId, textChannelId: interaction.channelId }); - ctx.updater.attach(room); - room.setVoiceCount(ctx.voiceMembers(vc).length); - ctx.resetUi(room.id); - await room.load({ type: pick.type, tmdb: pick.id, season: season || undefined, episode: episode || undefined }); - await adoptReply(ctx, room, interaction, true); -} - -async function roomFor(interaction, ctx) { - const vc = await userVoiceChannel(interaction); - return (vc && ctx.rooms.get(vc)) || ctx.rooms.all().find((r) => r.state.textChannelId === interaction.channelId) || null; -} - -async function np(interaction, ctx) { - if (notInGuild(interaction, ctx)) return; - const room = await roomFor(interaction, ctx); - if (!room || !room.state.media) return interaction.reply(ephemeral('Nothing is playing. Use `/watch` in a voice channel.')); - await interaction.deferReply(); - await adoptReply(ctx, room, interaction, true); -} - -async function stop(interaction, ctx) { - if (notInGuild(interaction, ctx)) return; - const room = await roomFor(interaction, ctx); - if (!room) return interaction.reply(ephemeral('Nothing is playing.')); - if (!ctx.isInVoice(room.id, interaction.user.id)) return interaction.reply(ephemeral(`Join <#${room.id}> to control playback.`)); - await room.command('stop', {}, interaction.user.id); - return interaction.reply(ephemeral('Stopped.')); -} - -const handlers = { watch, np, stop }; - -async function handleCommand(interaction, ctx) { - const h = handlers[interaction.commandName]; - if (h) await h(interaction, ctx); -} - -module.exports = { commandDefs, handleCommand, parsePick, userVoiceChannel, ephemeral }; diff --git a/src/bot/controls.js b/src/bot/controls.js deleted file mode 100644 index 9b4fcfa..0000000 --- a/src/bot/controls.js +++ /dev/null @@ -1,175 +0,0 @@ -// Button / select / modal handlers for the control message (custom ids `tv::[:]`). - -const { Routes } = require('discord.js'); -const { render, fmtTime } = require('./render'); -const { ephemeral } = require('./commands'); - -// "1:23:45", "23:45", "83m", "1h20m", "90s", "90", "45%", with optional leading +/- for relative seeks -// → { op: 'seek', t } | { op: 'seekBy', d } | null -function parseSeek(input, duration = 0) { - let s = String(input || '').trim().toLowerCase().replace(/\s+/g, ''); - if (!s) return null; - let sign = 0; - if (s[0] === '+' || s[0] === '-') { - sign = s[0] === '-' ? -1 : 1; - s = s.slice(1); - } - let t = null; - let m; - if ((m = /^(\d+(?:\.\d+)?)%$/.exec(s))) { - if (!(duration > 0)) return null; - t = (Math.min(100, Number(m[1])) / 100) * duration; - } else if (/^\d+(?::[0-5]?\d){1,2}(?:\.\d+)?$/.test(s)) { - t = s.split(':').reduce((acc, p) => acc * 60 + Number(p), 0); - } else if ((m = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m(?:in)?)?(?:(\d+(?:\.\d+)?)s(?:ec)?)?$/.exec(s)) && (m[1] || m[2] || m[3])) { - t = (Number(m[1]) || 0) * 3600 + (Number(m[2]) || 0) * 60 + (Number(m[3]) || 0); - } else if (/^\d+(?:\.\d+)?$/.test(s)) { - t = Number(s); - } - if (t == null || !Number.isFinite(t)) return null; - return sign ? { op: 'seekBy', d: sign * t } : { op: 'seek', t }; -} - -function seekModal(room) { - const dur = room.state.duration; - return { - custom_id: `tv:seekForm:${room.id}`, - title: 'Seek', - components: [ - { - type: 1, - components: [ - { - type: 4, - custom_id: 't', - style: 1, - label: dur ? `Time (now ${fmtTime(room.clock())} of ${fmtTime(dur)})` : `Time (now ${fmtTime(room.clock())})`, - placeholder: '1:23:45, 83m, 45%, 90s, +5m', - required: true, - max_length: 20, - }, - ], - }, - ], - }; -} - -async function launch(interaction) { - try { - if (typeof interaction.launchActivity === 'function') await interaction.launchActivity(); - else { - await interaction.client.rest.post(Routes.interactionCallback(interaction.id, interaction.token), { body: { type: 12 }, auth: false }); - } - } catch (e) { - console.warn(`[bot] launch activity: ${e.message}`); - if (!interaction.replied && !interaction.deferred) { - const hint = /EMBEDDED flag/i.test(e.message) - ? 'Activities are not enabled for this app yet: Developer Portal → your app → Activities → Settings → Enable Activities.' - : `Couldn't start the activity (${e.message}). Open it from the voice channel's Activities menu.`; - await interaction.reply(ephemeral(hint)).catch(() => {}); - } - } -} - -async function loadSeason(ctx, room, n) { - const ui = ctx.ui(room.id); - if (ui.seasonData[n] || !room.state.media) return; - try { - ui.seasonData[n] = await ctx.bugtv.season(room.state.media.tmdb, n); - } catch (e) { - console.warn(`[bot] season ${n}: ${e.message}`); - } -} - -const rerender = (ctx, room, now = Date.now()) => ({ ...render(room.state, ctx.ui(room.id), now), allowedMentions: { parse: [] } }); - -async function run(interaction, room, op, args) { - const res = await room.command(op, args, interaction.user.id); - if (res && !res.ok && res.error) await interaction.followUp(ephemeral(res.error)).catch(() => {}); - return res; -} - -async function handleComponent(interaction, ctx) { - const [ns, action, roomId, ...rest] = String(interaction.customId).split(':'); - if (ns !== 'tv') return; - const arg = rest.join(':'); - const room = ctx.rooms.get(roomId); - if (!room || !room.state.media) { - return interaction.reply(ephemeral('This watch session has ended. Use `/watch` to start a new one.')); - } - if (!ctx.isInVoice(roomId, interaction.user.id)) { - const hint = action === 'launch' ? `Join <#${roomId}> first, then press **Watch in VC**.` : `Join <#${roomId}> to control playback.`; - return interaction.reply(ephemeral(hint)); - } - ctx.updater.remember(room, interaction); - const ui = ctx.ui(room.id); - const value = interaction.isAnySelectMenu && interaction.isAnySelectMenu() ? interaction.values[0] : null; - - switch (action) { - case 'launch': - return launch(interaction); - case 'seekModal': - return interaction.showModal(seekModal(room)); - case 'seekForm': { - const parsed = parseSeek(interaction.fields.getTextInputValue('t'), room.state.duration); - if (!parsed) return interaction.reply(ephemeral('Try `1:23:45`, `83m`, `45%`, `90s` or `+5m`.')); - await interaction.deferUpdate(); - return run(interaction, room, parsed.op, parsed); - } - case 'toggle': - case 'prev': - case 'next': - case 'stop': - await interaction.deferUpdate(); - if (action === 'prev' || action === 'next') Object.assign(ui, { epSeason: null, epPage: null, srcPage: null }); - return run(interaction, room, action, {}); - case 'seekBy': - await interaction.deferUpdate(); - return run(interaction, room, 'seekBy', { d: Number(arg) || 0 }); - case 'episodes': - ui.mode = 'episodes'; - ui.epSeason = room.state.media.season; - ui.epPage = null; - await interaction.deferUpdate(); - await loadSeason(ctx, room, ui.epSeason); - return interaction.editReply(rerender(ctx, room)); - case 'sources': - ui.mode = 'sources'; - ui.srcPage = null; - return interaction.update(rerender(ctx, room)); - case 'src': - if (/^page:\d+$/.test(value)) { - ui.srcPage = Number(value.slice(5)); - return interaction.update(rerender(ctx, room)); - } - await interaction.deferUpdate(); - ui.srcPage = null; - return run(interaction, room, 'source', { id: value }); - case 'sub': - await interaction.deferUpdate(); - return run(interaction, room, 'subtitle', { index: Number(value) }); - case 'q': - await interaction.deferUpdate(); - return run(interaction, room, 'quality', { index: Number(value) }); - case 'season': - ui.epSeason = Number(value); - ui.epPage = null; - await interaction.deferUpdate(); - await loadSeason(ctx, room, ui.epSeason); - return interaction.editReply(rerender(ctx, room)); - case 'ep': { - if (/^page:\d+$/.test(value)) { - ui.epPage = Number(value.slice(5)); - return interaction.update(rerender(ctx, room)); - } - const season = ui.epSeason || room.state.media.season; - Object.assign(ui, { mode: 'sources', srcPage: null, epPage: null }); - await interaction.deferUpdate(); - return run(interaction, room, 'episode', { season, episode: Number(value) }); - } - default: - return interaction.reply(ephemeral('Unknown control.')); - } -} - -module.exports = { handleComponent, parseSeek, seekModal }; diff --git a/src/bot/index.js b/src/bot/index.js deleted file mode 100644 index 0d766da..0000000 --- a/src/bot/index.js +++ /dev/null @@ -1,105 +0,0 @@ -// Discord bot: gateway client, slash commands, control-message components, voice presence. - -const { Client, GatewayIntentBits, Events, MessageFlags, Routes } = require('discord.js'); -const { commandDefs, handleCommand } = require('./commands'); -const { handleComponent } = require('./controls'); -const { handleAutocomplete } = require('./autocomplete'); -const { createUpdater } = require('./updater'); - -async function registerCommands(client, cfg) { - const app = client.application; - if (cfg.guildIds && cfg.guildIds.length) { - for (const g of cfg.guildIds) { - await app.commands.set(commandDefs, g).catch((e) => console.warn(`[bot] register commands in ${g}: ${e.message}`)); - } - console.log(`[bot] registered ${commandDefs.length} commands in ${cfg.guildIds.length} guild(s)`); - } else { - // keep Discord's Activity entry-point command (type 4): a bulk overwrite without it fails - const route = Routes.applicationCommands(app.id); - const existing = await client.rest.get(route).catch(() => []); - await client.rest.put(route, { body: [...commandDefs, ...existing.filter((c) => c.type === 4)] }); - console.log(`[bot] registered ${commandDefs.length} global commands`); - } -} - -function createBotContext(cfg, rooms, client) { - function isInVoice(channelId, userId) { - const ch = client.channels.cache.get(String(channelId)); - if (!ch || !ch.guild) return false; - const vs = ch.guild.voiceStates.cache.get(String(userId)); - return !!vs && vs.channelId === String(channelId); - } - - // non-bot user ids currently in the voice channel - function voiceMembers(channelId) { - const ch = client.channels.cache.get(String(channelId)); - if (!ch || !ch.guild) return []; - return [...ch.guild.voiceStates.cache.values()] - .filter((vs) => vs.channelId === String(channelId)) - .filter((vs) => { - const user = (vs.member && vs.member.user) || client.users.cache.get(vs.id); - return !(user && user.bot); - }) - .map((vs) => vs.id); - } - - const uis = new Map(); - const freshUi = () => ({ mode: 'sources', srcPage: null, epSeason: null, epPage: null, seasonData: {} }); - const ui = (roomId) => { - if (!uis.has(roomId)) uis.set(roomId, freshUi()); - return uis.get(roomId); - }; - const resetUi = (roomId) => uis.set(roomId, freshUi()); - - const ctx = { cfg, client, rooms, bugtv: rooms.bugtv, isInVoice, voiceMembers, ui, resetUi }; - ctx.updater = createUpdater({ client, ui }); - rooms.on('created', (room) => ctx.updater.attach(room)); - rooms.on('deleted', (room) => uis.delete(room.id)); - return ctx; -} - -async function onInteraction(interaction, ctx) { - try { - if (interaction.isAutocomplete()) return await handleAutocomplete(interaction, ctx); - if (interaction.isChatInputCommand()) return await handleCommand(interaction, ctx); - if (interaction.isMessageComponent() || interaction.isModalSubmit()) return await handleComponent(interaction, ctx); - } catch (e) { - console.error('[bot] interaction error:', e); - if (interaction.isAutocomplete()) return; - const msg = { content: `Something went wrong: ${String(e.message).slice(0, 200)}`, flags: MessageFlags.Ephemeral }; - try { - if (interaction.deferred || interaction.replied) await interaction.followUp(msg); - else await interaction.reply(msg); - } catch { - /* interaction expired */ - } - } -} - -async function createBot(cfg, rooms) { - const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] }); - const ctx = createBotContext(cfg, rooms, client); - - client.on(Events.InteractionCreate, (i) => onInteraction(i, ctx)); - client.on(Events.VoiceStateUpdate, (before, after) => { - for (const ch of new Set([before.channelId, after.channelId])) { - const room = ch && rooms.get(ch); - if (room) room.setVoiceCount(ctx.voiceMembers(ch).length); - } - }); - client.on(Events.Error, (e) => console.error('[bot] client error:', e.message)); - - const ready = new Promise((resolve) => client.once(Events.ClientReady, resolve)); - await client.login(cfg.token); - await Promise.race([ready, new Promise((r) => setTimeout(r, 30000).unref())]); - if (client.isReady()) { - console.log(`[bot] logged in as ${client.user.tag}`); - await registerCommands(client, cfg).catch((e) => console.warn(`[bot] register commands: ${e.message}`)); - } else { - client.once(Events.ClientReady, () => registerCommands(client, cfg).catch((e) => console.warn(`[bot] register commands: ${e.message}`))); - } - - return { client, isInVoice: ctx.isInVoice, voiceMembers: ctx.voiceMembers, ctx }; -} - -module.exports = { createBot, createBotContext, registerCommands, commandDefs }; diff --git a/src/bot/render.js b/src/bot/render.js deleted file mode 100644 index 844ddf7..0000000 --- a/src/bot/render.js +++ /dev/null @@ -1,271 +0,0 @@ -// Control message builder: render(state, ui?, now?) → { embeds, components } (raw API JSON). - -const { clockOf, kindOf, qualityLabel } = require('../room'); - -const BUTTON = 2; -const ROW = 1; -const SELECT = 3; -const STYLE = { primary: 1, secondary: 2, success: 3, danger: 4 }; -const PAGE = 24; -const COLOR = 0xe50914; - -const clip = (s, n) => { - s = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); - return s.length > n ? `${s.slice(0, n - 1)}…` : s; -}; - -function fmtTime(sec) { - sec = Math.max(0, Math.floor(Number(sec) || 0)); - const h = Math.floor(sec / 3600); - const m = Math.floor((sec % 3600) / 60); - const s = String(sec % 60).padStart(2, '0'); - return h ? `${h}:${String(m).padStart(2, '0')}:${s}` : `${m}:${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}↑` : 'Torrent'; - return 'HLS'; -} - -function sourceLabel(s) { - return [qualityLabel(s), kindBadge(s), s.provider, fmtSize(s)].filter(Boolean).join(' · '); -} - -function sourceName(s) { - const n = String(s.title || s.name || '').trim(); - return n.toLowerCase() === String(s.provider || '').toLowerCase() ? '' : n; -} - -function progressBar(t, d, cells = 11) { - if (!(d > 0)) return `🔘${'▬'.repeat(cells - 1)}`; - const i = Math.min(cells - 1, Math.max(0, Math.round((t / d) * (cells - 1)))); - return `${'▬'.repeat(i)}🔘${'▬'.repeat(cells - 1 - i)}`; -} - -function epCode(m) { - return `S${m.season}E${m.episode}`; -} - -const button = (custom_id, label, opts = {}) => ({ - type: BUTTON, - style: opts.style || STYLE.secondary, - custom_id, - ...(label ? { label: clip(label, 80) } : {}), - ...(opts.emoji ? { emoji: { name: opts.emoji } } : {}), - ...(opts.disabled ? { disabled: true } : {}), -}); - -const select = (custom_id, placeholder, options, opts = {}) => ({ - type: SELECT, - custom_id, - placeholder: clip(placeholder, 150), - min_values: 1, - max_values: 1, - options: (options.length ? options : [{ label: '—', value: 'none' }]).slice(0, 25), - ...(opts.disabled || !options.length ? { disabled: true } : {}), -}); - -const opt = (label, value, extra = {}) => { - const o = { label: clip(label, 100) || '—', value: String(value).slice(0, 100) }; - if (extra.description) o.description = clip(extra.description, 100); - if (extra.default) o.default = true; - if (extra.emoji) o.emoji = { name: extra.emoji }; - return o; -}; - -const row = (...components) => ({ type: ROW, components }); - -function currentStream(state) { - return state.sourceId ? state.sources.find((x) => x.id === state.sourceId) || null : null; -} - -// window [start, start+size) of `total` items around `center` -function windowAround(total, center, size) { - if (total <= size) return 0; - return Math.max(0, Math.min(total - size, center - Math.floor(size / 2))); -} - -function sourceSelect(state, ui, id) { - const list = state.sources; - const pages = Math.max(1, Math.ceil(list.length / PAGE)); - let page = ui.srcPage; - if (page == null) { - const i = list.findIndex((x) => x.id === state.sourceId); - page = i >= 0 ? Math.floor(i / PAGE) : 0; - } - page = Math.min(Math.max(0, page), pages - 1); - const slice = list.slice(page * PAGE, page * PAGE + PAGE); - const options = slice.map((s) => - opt(sourceLabel(s), s.id, { - description: sourceName(s) || (s.language ? `lang ${s.language}` : ''), - default: s.id === state.sourceId, - emoji: state.failed.includes(s.id) ? '❌' : undefined, - }), - ); - if (pages > 1) { - const next = (page + 1) % pages; - options.push( - opt(next ? `More… (${next * PAGE + 1}–${Math.min(list.length, next * PAGE + PAGE)} of ${list.length})` : 'Back to top', `page:${next}`, { - emoji: next ? '➡️' : '⬆️', - }), - ); - } - const ph = list.length - ? `Source (${list.length}${state.scraping ? ', scraping…' : ''})` - : state.scraping - ? 'Finding sources…' - : 'No sources'; - return select(`tv:src:${id}`, ph, options); -} - -function subtitleSelect(state, id) { - const cur = currentStream(state); - const subs = (cur && cur.subtitles) || []; - const options = [opt('Subtitles off', -1, { default: state.subtitle < 0 })]; - subs.slice(0, 24).forEach((t, i) => - options.push(opt(t.label || t.lang || `Track ${i + 1}`, i, { description: t.lang && t.label ? t.lang : '', default: state.subtitle === i })), - ); - return select(`tv:sub:${id}`, subs.length ? 'Subtitles' : 'No subtitles', options, { disabled: !subs.length }); -} - -function qualitySelect(state, id) { - const levels = (state.levels || []).slice().sort((a, b) => b.height - a.height || b.bitrate - a.bitrate); - const options = [opt('Auto quality', -1, { default: state.quality < 0 })]; - for (const l of levels.slice(0, 24)) { - const label = [l.height ? `${l.height}p` : `Level ${l.index}`, l.bitrate ? `${(l.bitrate / 1e6).toFixed(1)} Mbps` : ''].filter(Boolean).join(' · '); - options.push(opt(label, l.index, { default: state.quality === l.index })); - } - return select(`tv:q:${id}`, levels.length ? 'Quality' : 'Quality (waiting for player)', options, { disabled: !levels.length }); -} - -function seasonSelect(state, ui, id) { - const m = state.media; - const seasons = m.seasons && m.seasons.length ? m.seasons : [{ n: m.season, count: 0 }]; - const sel = ui.epSeason || m.season; - const ci = Math.max(0, seasons.findIndex((x) => x.n === sel)); - const start = windowAround(seasons.length, ci, 25); - const options = seasons - .slice(start, start + 25) - .map((x) => opt(`Season ${x.n}`, x.n, { description: x.count ? `${x.count} episodes` : '', default: x.n === sel })); - return select(`tv:season:${id}`, 'Season', options); -} - -function episodeSelect(state, ui, id) { - const m = state.media; - const sel = ui.epSeason || m.season; - const data = ui.seasonData && ui.seasonData[sel]; - let eps = data && data.episodes ? data.episodes.map((e) => ({ n: e.episode_number, name: e.name, air: e.air_date })) : null; - if (!eps) { - const count = ((m.seasons || []).find((x) => x.n === sel) || {}).count || (sel === m.season ? Math.max(m.episode, 1) : 1); - eps = Array.from({ length: count }, (_, i) => ({ n: i + 1, name: '' })); - } - eps.sort((a, b) => a.n - b.n); - const size = eps.length > 25 ? 23 : 25; - let start = ui.epPage; - if (start == null) { - const ci = eps.findIndex((e) => sel === m.season && e.n === m.episode); - start = windowAround(eps.length, ci < 0 ? 0 : ci, size); - } - start = Math.max(0, Math.min(start, Math.max(0, eps.length - size))); - const options = []; - if (start > 0) options.push(opt('Earlier episodes…', `page:${Math.max(0, start - size)}`, { emoji: '⬆️' })); - for (const e of eps.slice(start, start + size)) { - options.push( - opt(`${e.n}. ${e.name || `Episode ${e.n}`}`, e.n, { - description: e.air ? `aired ${e.air}` : '', - default: sel === m.season && e.n === m.episode, - }), - ); - } - if (start + size < eps.length) options.push(opt('Later episodes…', `page:${start + size}`, { emoji: '⬇️' })); - return select(`tv:ep:${id}`, `Season ${sel} episode`, options); -} - -function embed(state, now, opts) { - const m = state.media || {}; - const cur = currentStream(state); - const lines = []; - if (m.type === 'tv' && m.season) lines.push(`**${epCode(m)}${m.episodeTitle ? ` · ${clip(m.episodeTitle, 120)}` : ''}**`); - if (m.overview) lines.push(clip(m.overview, 300)); - lines.push(''); - if (opts.closed) { - lines.push('⏹ **Stopped.** Use `/watch` to start something new.'); - } else { - const t = clockOf(state, now); - const d = state.duration || 0; - lines.push(`${state.playing ? '▶️' : '⏸️'} ${progressBar(t, d)} \`${fmtTime(t)} / ${d ? fmtTime(d) : '--:--'}\`${state.buffering ? ' ⏳' : ''}`); - if (cur) lines.push(`📺 ${clip(sourceLabel(cur), 200)}`); - if (state.scraping) lines.push(`🔎 Scraping ${state.providers.done}/${state.providers.total || '?'} providers…`); - else if (state.sources.length) lines.push(`🔎 ${state.sources.length} sources`); - lines.push( - state.viewers.length - ? `👥 ${state.viewers.length} watching${state.leader ? ` · host <@${state.leader}>` : ''}` - : 'No one watching yet — press **Watch in VC**', - ); - if (state.notice) lines.push(`⚠️ ${clip(state.notice, 300)}`); - } - const e = { - title: clip(`${m.title || 'Loading…'}${m.year ? ` (${m.year})` : ''}`, 256), - description: lines.join('\n').slice(0, 4096), - color: opts.closed ? 0x555555 : COLOR, - footer: { text: 'bug.tv' }, - }; - if (m.tmdb) e.url = `https://www.themoviedb.org/${m.type}/${m.tmdb}`; - if (!opts.closed && (m.backdrop || m.still)) e.image = { url: m.backdrop || m.still }; - if (m.poster) e.thumbnail = { url: m.poster }; - return e; -} - -function render(state, ui = {}, now = Date.now(), opts = {}) { - ui = ui || {}; - const embeds = [embed(state, now, opts)]; - if (opts.closed || !state.media) return { embeds, components: [] }; - const id = state.id; - const m = state.media; - const isTv = m.type === 'tv'; - const mode = isTv && ui.mode === 'episodes' ? 'episodes' : 'sources'; - const firstEp = isTv && m.episode <= 1 && (!m.seasons || !m.seasons.length || m.season <= m.seasons[0].n); - - const row1 = row( - button(`tv:seekBy:${id}:-30`, '30s', { emoji: '⏪' }), - button(`tv:toggle:${id}`, state.playing ? 'Pause' : 'Play', { emoji: state.playing ? '⏸️' : '▶️', style: STYLE.success }), - button(`tv:seekBy:${id}:30`, '30s', { emoji: '⏩' }), - button(`tv:seekBy:${id}:120`, '2m', { emoji: '⏭️' }), - button(`tv:seekModal:${id}`, 'Seek', { emoji: '🕐' }), - ); - const row2 = [ - button(`tv:prev:${id}`, 'Prev', { emoji: '⏮️', disabled: !isTv || firstEp }), - button(`tv:next:${id}`, 'Next', { emoji: '⏭️', disabled: !isTv }), - button(`tv:launch:${id}`, 'Watch in VC', { emoji: '▶️', style: STYLE.primary }), - ]; - if (isTv) { - row2.push( - mode === 'episodes' - ? button(`tv:sources:${id}`, 'Sources', { emoji: '📡' }) - : button(`tv:episodes:${id}`, 'Episodes', { emoji: '📜' }), - ); - } - row2.push(button(`tv:stop:${id}`, 'Stop', { emoji: '⏹️', style: STYLE.danger })); - - const components = [row1, row(...row2)]; - if (mode === 'episodes') { - components.push(row(seasonSelect(state, ui, id)), row(episodeSelect(state, ui, id))); - } else { - components.push(row(sourceSelect(state, ui, id)), row(subtitleSelect(state, id)), row(qualitySelect(state, id))); - } - return { embeds, components }; -} - -module.exports = { render, fmtTime, progressBar, sourceLabel, clip }; diff --git a/src/bot/updater.js b/src/bot/updater.js deleted file mode 100644 index 39247af..0000000 --- a/src/bot/updater.js +++ /dev/null @@ -1,110 +0,0 @@ -// Keeps each room's control message in sync with room state: at most one edit every 3s, -// immediate on source/episode/play/pause/stop, plus a slow tick so the progress bar moves. - -const { render } = require('./render'); - -const THROTTLE_MS = 3000; -const TICK_MS = 15000; -const IMMEDIATE = new Set(['load', 'source', 'episode', 'play', 'pause', 'stop', 'idle', 'ended']); -const WEBHOOK_TTL = 14 * 60e3; - -function createUpdater({ client, ui }) { - const entries = new Map(); // roomId → { room, last, timer, busy, dirty, closed } - const interactions = new Map(); // roomId → { interaction, messageId, at } - - const entry = (room) => { - let e = entries.get(room.id); - if (!e || e.room !== room) { - e = { room, last: 0, timer: null, busy: null, dirty: false, closed: false }; - entries.set(room.id, e); - } - return e; - }; - - function attach(room) { - if (room._botAttached) return; - room._botAttached = true; - entry(room); - room.on('change', (state, reason) => schedule(room, IMMEDIATE.has(reason))); - room.on('closed', () => finish(room)); - } - - // remember a component/command interaction: its webhook can edit the message if channel edits fail - function remember(room, interaction, messageId) { - const mid = messageId || (interaction.message && interaction.message.id); - if (mid) interactions.set(room.id, { interaction, messageId: mid, at: Date.now() }); - } - - function schedule(room, immediate = false) { - const e = entry(room); - if (e.closed) return; - e.dirty = true; - if (e.busy) return; // re-scheduled when the in-flight edit finishes - const wait = immediate ? 0 : Math.max(0, e.last + THROTTLE_MS - Date.now()); - if (e.timer) { - if (!immediate) return; - clearTimeout(e.timer); - } - e.timer = setTimeout(() => flush(room), wait); - } - - async function edit(state, payload) { - const it = interactions.get(state.id); - try { - const ch = client.channels.cache.get(state.textChannelId) || (await client.channels.fetch(state.textChannelId)); - await ch.messages.edit(state.messageId, payload); - } catch (err) { - if (err && err.code === 10008) { - state.messageId = null; // control message was deleted - return; - } - if (it && it.messageId === state.messageId && Date.now() - it.at < WEBHOOK_TTL) { - await it.interaction.webhook.editMessage(state.messageId, payload); - return; - } - throw err; - } - } - - async function flush(room) { - const e = entry(room); - e.timer = null; - if (e.closed || !e.dirty) return; - e.dirty = false; - const state = room.state; - if (!state.messageId || !state.textChannelId) return; - e.last = Date.now(); - e.busy = edit(state, render(state, ui(room.id))) - .catch((err) => console.warn(`[bot] edit control message ${state.messageId}: ${err.message}`)) - .finally(() => { - e.busy = null; - if (e.dirty && !e.closed) schedule(room, false); - }); - await e.busy; - } - - async function finish(room) { - const e = entry(room); - e.closed = true; - if (e.timer) clearTimeout(e.timer); - e.timer = null; - if (e.busy) await e.busy; - const state = room.state; - if (state.messageId && state.textChannelId) { - await edit(state, render(state, ui(room.id), Date.now(), { closed: true })).catch((err) => - console.warn(`[bot] final edit ${state.messageId}: ${err.message}`), - ); - } - entries.delete(room.id); - interactions.delete(room.id); - } - - const tick = setInterval(() => { - for (const e of entries.values()) if (e.room.state.playing && !e.closed) schedule(e.room, false); - }, TICK_MS); - if (tick.unref) tick.unref(); - - return { attach, remember, schedule, flush, stop: () => clearInterval(tick) }; -} - -module.exports = { createUpdater, IMMEDIATE, THROTTLE_MS }; diff --git a/src/bugtv.js b/src/bugtv.js deleted file mode 100644 index a6d6331..0000000 --- a/src/bugtv.js +++ /dev/null @@ -1,176 +0,0 @@ -// bug-tv API client (SSE /v1/streams, /v1/prefetch) and a small TMDB client. -// Node 22+ global fetch; the SSE stream is parsed by hand. - -const TMDB = 'https://api.themoviedb.org/3'; -const IMG = 'https://image.tmdb.org/t/p'; - -function img(path, size = 'w500') { - return path ? `${IMG}/${size}${path}` : null; -} - -function cache(ttlMs, max = 500) { - const m = new Map(); - return { - get(k) { - const e = m.get(k); - if (!e) return undefined; - if (Date.now() > e.exp) { - m.delete(k); - return undefined; - } - return e.v; - }, - set(k, v) { - if (m.size >= max) m.delete(m.keys().next().value); - m.set(k, { v, exp: Date.now() + ttlMs }); - return v; - }, - }; -} - -function query(params) { - const q = new URLSearchParams(); - for (const [k, v] of Object.entries(params)) { - if (v == null || v === '') continue; - q.set(k, Array.isArray(v) ? v.join(',') : String(v)); - } - return q.toString(); -} - -// Parse a text/event-stream body. Calls onEvent(name, data) per event; returns when the body ends. -async function readSse(body, onEvent) { - const decoder = new TextDecoder(); - let buf = ''; - const flush = (block) => { - let name = 'message'; - const data = []; - for (const line of block.split('\n')) { - if (!line || line.startsWith(':')) continue; - const i = line.indexOf(':'); - const field = i < 0 ? line : line.slice(0, i); - let val = i < 0 ? '' : line.slice(i + 1); - if (val.startsWith(' ')) val = val.slice(1); - if (field === 'event') name = val; - else if (field === 'data') data.push(val); - } - if (!data.length) return; - let parsed; - try { - parsed = JSON.parse(data.join('\n')); - } catch { - parsed = data.join('\n'); - } - onEvent(name, parsed); - }; - for await (const chunk of body) { - buf += decoder.decode(chunk, { stream: true }).replace(/\r\n?/g, '\n'); - let idx; - while ((idx = buf.indexOf('\n\n')) >= 0) { - const block = buf.slice(0, idx); - buf = buf.slice(idx + 2); - flush(block); - } - } - buf += decoder.decode(); - if (buf.trim()) flush(buf); -} - -function createBugtv(cfg = {}) { - const apiUrl = String(cfg.apiUrl || 'http://127.0.0.1:8789').replace(/\/+$/, ''); - const providers = cfg.providers && cfg.providers.length ? cfg.providers : null; - const tmdbCache = cache(6 * 3600e3); - const searchCache = cache(10 * 60e3, 200); - - function streamParams(p) { - const out = { tmdb: p.tmdb, type: p.type }; - if (p.type === 'tv') { - out.season = p.season; - out.episode = p.episode; - } - const list = p.providers || providers; - if (list) out.providers = list; - return out; - } - - // Resolves when the scrape finishes (or the stream drops, which counts as done). - async function streams(params, h = {}) { - const url = `${apiUrl}/v1/streams?${query(streamParams(params))}`; - let gotDone = false; - const t0 = Date.now(); - let total = 0; - try { - const res = await fetch(url, { headers: { accept: 'text/event-stream' }, signal: h.signal }); - if (!res.ok) throw new Error(`bug-tv ${res.status} ${res.statusText}`); - await readSse(res.body, (name, data) => { - if (h.signal && h.signal.aborted) return; - if (name === 'meta') h.onMeta && h.onMeta(data); - else if (name === 'streams') { - total += (data.streams || []).length; - h.onStreams && h.onStreams(data); - } else if (name === 'provider') h.onProvider && h.onProvider(data); - else if (name === 'done') { - gotDone = true; - h.onDone && h.onDone(data); - } - }); - } catch (e) { - if (h.signal && h.signal.aborted) return; - if (h.onError) h.onError(e); - else console.warn('[bugtv] streams error:', e.message); - } - if (!gotDone && !(h.signal && h.signal.aborted)) h.onDone && h.onDone({ total, ms: Date.now() - t0, dropped: true }); - } - - async function prefetch(params) { - try { - const res = await fetch(`${apiUrl}/v1/prefetch?${query(streamParams(params))}`); - return res.ok ? await res.json() : null; - } catch (e) { - console.warn('[bugtv] prefetch error:', e.message); - return null; - } - } - - async function tmdb(path, params = {}, store = tmdbCache) { - const key = `${path}?${query(params)}`; - const hit = store.get(key); - if (hit) return hit; - const res = await fetch(`${TMDB}${path}?${query({ ...params, api_key: cfg.tmdbKey })}`); - if (!res.ok) throw new Error(`TMDB ${res.status} ${path}`); - return store.set(key, await res.json()); - } - - // → [{ type, id, title, year, poster, overview, popularity }] (movies and series only) - async function searchMulti(q) { - q = String(q || '').trim(); - if (!q) return []; - const data = await tmdb('/search/multi', { query: q, include_adult: 'false' }, searchCache); - return (data.results || []) - .filter((r) => r.media_type === 'movie' || r.media_type === 'tv') - .map((r) => ({ - type: r.media_type, - id: r.id, - title: r.title || r.name || '', - year: String(r.release_date || r.first_air_date || '').slice(0, 4), - poster: img(r.poster_path, 'w342'), - overview: r.overview || '', - popularity: r.popularity || 0, - })); - } - - // Raw TMDB details (+images, external_ids); tv includes `seasons`. - function details(type, id) { - return tmdb(`/${type === 'tv' ? 'tv' : 'movie'}/${id}`, { - append_to_response: 'images,external_ids', - include_image_language: 'en,null', - }); - } - - function season(tvId, n) { - return tmdb(`/tv/${tvId}/season/${n}`); - } - - return { apiUrl, streams, prefetch, searchMulti, details, season, img }; -} - -module.exports = { createBugtv, readSse, img }; diff --git a/src/config.js b/src/config.js index 78f0dd9..872a46e 100644 --- a/src/config.js +++ b/src/config.js @@ -6,17 +6,16 @@ const CONFIG_PATH = process.env.BUG_TV_DISCORD_CONFIG || path.join(__dirname, '. const DEFAULTS = { host: '0.0.0.0', port: 8791, - apiUrl: 'http://127.0.0.1:8789', applicationId: '', - guildIds: [], token: '', tokenFile: '', clientSecret: '', clientSecretFile: '', - tmdbKey: '', - tmdbKeyFile: '', - activityDir: path.join(__dirname, '..', 'activity'), - providers: [], + // the built Activity (bug.tv site + overlay): scripts/build-activity.sh output or nix packages.activity + activityDir: path.join(__dirname, '..', 'site'), + // dev only: accept {dev:true} hellos and reverse-proxy /tv/v1 → devApiUrl, /tmdb, /img (mirrors Discord's URL mappings) + dev: false, + devApiUrl: 'http://127.0.0.1:8789', }; const readFile = (file) => (file ? fs.readFileSync(file, 'utf8').trim() : ''); @@ -28,11 +27,13 @@ function loadConfig() { cfg.token = cfg.token || readFile(cfg.tokenFile) || env.DISCORD_TOKEN || ''; cfg.clientSecret = cfg.clientSecret || readFile(cfg.clientSecretFile) || env.DISCORD_CLIENT_SECRET || ''; - cfg.tmdbKey = cfg.tmdbKey || readFile(cfg.tmdbKeyFile) || env.TMDB_API_KEY || ''; if (env.BUG_TV_DISCORD_PORT) cfg.port = parseInt(env.BUG_TV_DISCORD_PORT, 10); - cfg.apiUrl = cfg.apiUrl.replace(/\/+$/, ''); + if (env.BUG_TV_DISCORD_DEV === '1') cfg.dev = true; + cfg.dev = cfg.dev === true; + cfg.devApiUrl = String(cfg.devApiUrl || '').replace(/\/+$/, ''); - const missing = ['applicationId', 'token', 'clientSecret', 'tmdbKey'].filter((k) => !cfg[k]); + // dev mode can run without Discord credentials (only dev hellos work then) + const missing = cfg.dev ? [] : ['applicationId', 'token', 'clientSecret'].filter((k) => !cfg[k]); if (missing.length) { console.error(`tv-discord: missing config: ${missing.join(', ')} (see config.example.json)`); process.exit(1); diff --git a/src/index.js b/src/index.js index 01ba6c2..46eb815 100644 --- a/src/index.js +++ b/src/index.js @@ -1,25 +1,16 @@ const { loadConfig } = require('./config'); -const { createRooms } = require('./room'); -const { createBot } = require('./bot'); const { createServer } = require('./server'); -async function main() { - const cfg = loadConfig(); - const rooms = createRooms(cfg); - const bot = await createBot(cfg, rooms); - const server = createServer(cfg, rooms, { isInVoice: bot.isInVoice }); - server.listen(cfg.port, cfg.host, () => console.log(`tv-discord: activity + ws on http://${cfg.host}:${cfg.port}`)); +const cfg = loadConfig(); +const server = createServer(cfg); +server.listen(cfg.port, cfg.host, () => console.log(`tv-discord: activity + ws on http://${cfg.host}:${cfg.port}${cfg.dev ? ' (dev)' : ''}`)); - const shutdown = () => { - server.close(); - bot.client.destroy(); - process.exit(0); - }; - process.on('SIGTERM', shutdown); - process.on('SIGINT', shutdown); +let closing = false; +function shutdown() { + if (closing) return; + closing = true; + server.close(() => process.exit(0)); + setTimeout(() => process.exit(0), 3000).unref(); } - -main().catch((e) => { - console.error(e); - process.exit(1); -}); +process.on('SIGTERM', shutdown); +process.on('SIGINT', shutdown); diff --git a/src/room.js b/src/room.js deleted file mode 100644 index e088919..0000000 --- a/src/room.js +++ /dev/null @@ -1,698 +0,0 @@ -// Per-voice-channel watch room: shared playback state, source ranking/auto-pick -// (ported from bug-tv web/js/views/watch.js), failover, episodes, prefetch, idle close. - -const { EventEmitter } = require('events'); -const { createBugtv, img } = require('./bugtv'); - -const GRACE_MS = 1500; -const IDLE_MS = 2 * 60e3; -const DRIFT_S = 1; -const KINDS = new Set(['hls', 'file', 'remux', 'torrent']); -const KIND_LABEL = { hls: 'HLS', file: 'MP4', remux: 'Remux', torrent: 'Torrent' }; - -/* ---- ranking (same rules as the web player) ---- */ - -function kindOf(s) { - return (s && s.playback && s.playback.kind) || 'file'; -} - -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 && KINDS.has(kindOf(s))); -} - -function rank(streams, lastProvider) { - return streams - .filter(isPlayable) - .map((s) => ({ s, score: scoreStream(s, lastProvider) })) - .sort((a, b) => b.score - a.score) // stable: ties keep arrival order - .map((x) => x.s); -} - -function qualityLabel(s) { - const px = Number(s.pixels) || 0; - if (px >= 2160) return '4K'; - if (px) return `${px}p`; - return s.quality || 'SD?'; -} - -// position + elapsed while playing, clamped to [0, duration || ∞] -function clockOf(state, now = Date.now()) { - let t = (Number(state.position) || 0) + (state.playing ? (now - (state.updatedAt == null ? now : state.updatedAt)) / 1000 : 0); - if (t < 0) t = 0; - if (state.duration > 0 && t > state.duration) t = state.duration; - return t; -} - -/* ---- Room ---- */ - -class Room extends EventEmitter { - constructor(rooms, { id, guildId, textChannelId }) { - super(); - this.rooms = rooms; - this.bugtv = rooms.bugtv; - this.now = rooms.now; - this._setTimeout = rooms.setTimeout; - this._clearTimeout = rooms.clearTimeout; - this._gen = 0; - this._ac = null; - this._streams = new Map(); - this._grace = null; - this._idle = null; - this._conns = new Map(); // userId → open connection count - this._autoplay = false; // start playing when the first viewer joins - this._seasonsMeta = []; - this.closed = false; - this.voiceCount = null; - this.state = { - id, - guildId: guildId || null, - textChannelId: textChannelId || null, - messageId: null, - media: null, - sources: [], - scraping: false, - providers: { done: 0, total: 0 }, - sourceId: null, - failed: [], - notice: null, - subtitle: -1, - quality: -1, - levels: [], - playing: false, - position: 0, - updatedAt: this.now(), - duration: 0, - buffering: false, - viewers: [], - leader: null, - rev: 0, - }; - } - - get id() { - return this.state.id; - } - - clock(now = this.now()) { - return clockOf(this.state, now); - } - - current() { - const s = this.state; - return s.sourceId ? s.sources.find((x) => x.id === s.sourceId) || this._streams.get(s.sourceId) || null : null; - } - - publicState(now = this.now()) { - const s = this.state; - return { - media: s.media, - stream: this.current(), - subtitle: s.subtitle, - quality: s.quality, - playing: s.playing, - position: s.position, - updatedAt: s.updatedAt, - now, - duration: s.duration, - viewers: s.viewers.slice(), - leader: s.leader, - rev: s.rev, - notice: s.notice, - buffering: s.buffering, - }; - } - - _emit(reason) { - if (this.closed && reason !== 'stop' && reason !== 'idle') return; - this.state.rev++; - this.emit('change', this.state, reason); - } - - _setClock(position, playing, user = true) { - const s = this.state; - if (user) this._clockSetAt = this.now(); - s.position = Math.max(0, s.duration > 0 ? Math.min(position, s.duration) : position); - s.updatedAt = this.now(); - s.playing = !!playing; - } - - _timer(fn, ms) { - return this._setTimeout(fn, ms); - } - - /* ---- loading ---- */ - - async load({ type, tmdb, season, episode } = {}) { - if (this.closed) return; - type = type === 'tv' ? 'tv' : 'movie'; - tmdb = Number(tmdb); - if (!tmdb) throw new Error('load: tmdb id required'); - const s = this.state; - const gen = ++this._gen; - const prev = s.media && s.media.type === type && s.media.tmdb === tmdb ? s.media : null; - if (type === 'tv') { - season = Number(season) || 1; - episode = Number(episode) || 1; - } else { - season = null; - episode = null; - } - this._abortScrape(); - this._streams.clear(); - this._started = false; - this._eager = false; - this._done = false; - this._resumeAt = 0; - this._prefetched = false; - this._autoplay = false; - Object.assign(s, { - media: { - type, - tmdb, - title: prev ? prev.title : '', - year: prev ? prev.year : '', - poster: prev ? prev.poster : null, - backdrop: prev ? prev.backdrop : null, - logo: prev ? prev.logo : null, - overview: prev && type === 'movie' ? prev.overview : '', - season, - episode, - episodeTitle: '', - still: null, - seasons: prev ? prev.seasons : [], - }, - sources: [], - scraping: true, - providers: { done: 0, total: 0 }, - sourceId: null, - failed: [], - notice: null, - subtitle: -1, - quality: -1, - levels: [], - duration: 0, - buffering: false, - }); - this._setClock(0, false); - this._emit('load'); - this._startScrape(gen); - await this._fetchMeta(gen); - } - - async _fetchMeta(gen) { - const m = this.state.media; - try { - const d = await this.bugtv.details(m.type, m.tmdb); - if (gen !== this._gen) return; - m.title = d.title || d.name || ''; - m.year = String(d.release_date || d.first_air_date || '').slice(0, 4); - m.poster = img(d.poster_path, 'w500'); - m.backdrop = img(d.backdrop_path, 'w1280'); - const logos = (d.images && d.images.logos) || []; - const logo = logos.find((l) => l.iso_639_1 === 'en') || logos[0]; - m.logo = logo ? img(logo.file_path, 'w500') : null; - m.overview = d.overview || ''; - if (m.type === 'tv') { - this._seasonsMeta = (d.seasons || []) - .filter((x) => x.season_number > 0 && (x.episode_count || 0) > 0) - .sort((a, b) => a.season_number - b.season_number); - m.seasons = this._seasonsMeta.map((x) => ({ n: x.season_number, count: x.episode_count })); - const sd = await this._season(m.season); - if (gen !== this._gen) return; - const ep = sd && (sd.episodes || []).find((e) => e.episode_number === m.episode); - if (ep) { - m.episodeTitle = ep.name || ''; - m.still = img(ep.still_path, 'w780'); - if (ep.overview) m.overview = ep.overview; - } - } - this._emit('meta'); - } catch (e) { - if (gen !== this._gen) return; - console.warn(`[room ${this.id}] tmdb: ${e.message}`); - } - } - - async _season(n) { - try { - return await this.bugtv.season(this.state.media.tmdb, n); - } catch { - return null; - } - } - - _abortScrape() { - if (this._ac) this._ac.abort(); - this._ac = null; - if (this._grace) this._clearTimeout(this._grace); - this._grace = null; - } - - _lastProviderKey() { - const m = this.state.media; - return m ? `${m.type}:${m.tmdb}` : ''; - } - - _rerank() { - const lp = this.rooms.lastProvider.get(this._lastProviderKey()) || ''; - this.state.sources = rank([...this._streams.values()], lp); - } - - _startScrape(gen) { - const m = this.state.media; - const ac = new AbortController(); - this._ac = ac; - const live = () => gen === this._gen && !ac.signal.aborted && !this.closed; - const params = { tmdb: m.tmdb, type: m.type }; - if (m.type === 'tv') { - params.season = m.season; - params.episode = m.episode; - } - const s = this.state; - const p = this.bugtv.streams(params, { - signal: ac.signal, - onMeta: (meta) => { - if (!live()) return; - s.providers = { done: s.providers.done, total: (meta.providers || []).length }; - this._emit('providers'); - }, - onStreams: (ev) => { - if (!live()) return; - let best = null; - for (const x of ev.streams || []) { - if (!x) continue; - if (!x.provider) x.provider = ev.provider; - if (!x.id) x.id = `${ev.provider}:${x.playback && x.playback.url}`; - if (this._streams.has(x.id)) continue; - this._streams.set(x.id, x); - if (isPlayable(x) && (!best || (x.pixels || 0) > (best.pixels || 0))) best = x; - } - this._rerank(); - this._emit('sources'); - if (!best || this._started) return; - if (this._eager) return this._begin('eager'); - const k = kindOf(best); - if ((best.pixels || 0) >= 1080 && (k === 'hls' || k === 'file')) this._begin('fast'); - else if (!this._grace) this._grace = this._timer(() => live() && this._begin('grace'), GRACE_MS); - }, - onProvider: () => { - if (!live()) return; - s.providers = { done: s.providers.done + 1, total: Math.max(s.providers.total, s.providers.done + 1) }; - this._emit('providers'); - }, - onDone: () => { - if (!live()) return; - this._done = true; - s.scraping = false; - s.providers = { done: s.providers.total, total: s.providers.total }; - if (!this._started) this._begin('done'); - else if (!s.sourceId) this._noSources(); - this._emit('scrape-done'); - }, - onError: (e) => { - if (!live()) return; - console.warn(`[room ${this.id}] streams: ${e.message}`); - s.notice = `bug-tv error: ${e.message}`; - }, - }); - if (p && p.catch) p.catch((e) => console.warn(`[room ${this.id}] streams: ${e.message}`)); - } - - _noSources() { - const s = this.state; - s.notice = s.failed.length ? 'None of the sources would play.' : 'No sources found for this title.'; - s.sourceId = null; - this._setClock(this.clock(), false); - } - - // auto-pick the best unfailed source - _begin(why) { - if (this._started || this.closed) return; - if (this._grace) this._clearTimeout(this._grace); - this._grace = null; - const s = this.state; - const first = s.sources.find((x) => !s.failed.includes(x.id)); - if (!first) { - if (this._done) { - this._noSources(); - this._emit('notice'); - } - return; - } - this._started = true; - this._eager = false; - this._why = why; - const playing = s.viewers.length > 0; - if (!playing) this._autoplay = true; - this._select(first, this._resumeAt || 0, playing); - this._emit('source'); - } - - _select(stream, position, playing) { - const s = this.state; - const prev = this.current(); - const prevLang = prev && s.subtitle >= 0 && prev.subtitles && prev.subtitles[s.subtitle] ? prev.subtitles[s.subtitle].lang : null; - s.sourceId = stream.id; - s.subtitle = prevLang ? (stream.subtitles || []).findIndex((x) => x.lang === prevLang) : -1; - s.quality = -1; - s.levels = []; - s.buffering = false; - this._started = true; - this._setClock(position, playing); - } - - _failover(message) { - const s = this.state; - const cur = this.current(); - if (!cur) return; - if (!s.failed.includes(cur.id)) s.failed.push(cur.id); - const pos = this.clock(); - const next = s.sources.find((x) => !s.failed.includes(x.id)); - const what = `${cur.provider} ${qualityLabel(cur)}`; - if (next) { - s.notice = `${what} failed${message ? ` (${String(message).slice(0, 80)})` : ''}, trying ${next.provider} ${qualityLabel(next)}`; - this._select(next, pos, s.playing); - } else if (!this._done) { - s.notice = `${what} failed, waiting for more sources…`; - s.sourceId = null; - this._started = false; - this._eager = true; - this._resumeAt = pos; - this._setClock(pos, s.playing); - } else { - this._noSources(); - s.notice = `${what} failed. No more sources to try.`; - } - this._emit('source'); - } - - /* ---- episodes ---- */ - - async episodeRef(dir) { - const m = this.state.media; - if (!m || m.type !== 'tv') return null; - const today = new Date(this.now()).toISOString().slice(0, 10); - const cur = await this._season(m.season); - const eps = ((cur && cur.episodes) || []).slice().sort((a, b) => a.episode_number - b.episode_number); - const seasons = this._seasonsMeta; - if (dir > 0) { - const nxt = eps.find((e) => e.episode_number > m.episode); - if (nxt) return nxt.air_date && nxt.air_date > today ? null : { season: m.season, episode: nxt.episode_number }; - const ns = seasons.find((x) => x.season_number > m.season); - if (ns) return ns.air_date && ns.air_date > today ? null : { season: ns.season_number, episode: 1 }; - if (!cur && !seasons.length) return { season: m.season, episode: m.episode + 1 }; - return null; - } - const prv = eps.filter((e) => e.episode_number < m.episode).pop(); - if (prv) return { season: m.season, episode: prv.episode_number }; - if (!cur && m.episode > 1) return { season: m.season, episode: m.episode - 1 }; - const ps = seasons.filter((x) => x.season_number < m.season).pop(); - if (ps) { - const pd = await this._season(ps.season_number); - const nums = ((pd && pd.episodes) || []).map((e) => e.episode_number); - return { season: ps.season_number, episode: nums.length ? Math.max(...nums) : ps.episode_count }; - } - return null; - } - - async _gotoEpisode(dir) { - const ref = await this.episodeRef(dir); - if (!ref) return { ok: false, error: dir > 0 ? 'No next episode.' : 'No previous episode.' }; - await this.load({ type: 'tv', tmdb: this.state.media.tmdb, ...ref }); - return { ok: true }; - } - - _checkPrefetch() { - const s = this.state; - if (this._prefetched || !s.media || s.media.type !== 'tv' || !(s.duration > 0)) return; - if (this.clock() / s.duration < 0.8) return; - this._prefetched = true; - const tmdb = s.media.tmdb; - this.episodeRef(1) - .then((ref) => ref && this.bugtv.prefetch({ tmdb, type: 'tv', ...ref })) - .catch((e) => console.warn(`[room ${this.id}] prefetch: ${e.message}`)); - } - - /* ---- commands (anyone in the VC) ---- */ - - async command(op, args = {}, userId = null) { - if (this.closed) return { ok: false, error: 'This session has ended.' }; - args = args || {}; - const s = this.state; - try { - switch (op) { - case 'play': - this._autoplay = false; - if (!s.playing) { - // replay from the start when paused at the end - const t = this.clock(); - this._setClock(s.duration > 0 && t >= s.duration - 0.5 ? 0 : t, true); - this._emit('play'); - } - return { ok: true }; - case 'pause': - this._autoplay = false; - if (s.playing) { - this._setClock(this.clock(), false); - this._emit('pause'); - } - return { ok: true }; - case 'toggle': - return this.command(s.playing ? 'pause' : 'play', {}, userId); - case 'seek': - case 'seekBy': { - const t = op === 'seek' ? Number(args.t) : this.clock() + Number(args.d); - if (!Number.isFinite(t)) return { ok: false, error: 'Bad time.' }; - this._setClock(Math.max(0, t), s.playing); - this._emit('seek'); - this._checkPrefetch(); - return { ok: true }; - } - case 'source': { - const x = s.sources.find((v) => v.id === args.id) || this._streams.get(args.id); - if (!x) return { ok: false, error: 'Unknown source.' }; - s.failed = s.failed.filter((f) => f !== x.id); - s.notice = null; - this._eager = false; - this._select(x, this.clock(), s.playing); - this._emit('source'); - return { ok: true }; - } - case 'subtitle': { - const cur = this.current(); - const i = Number(args.index); - const n = (cur && cur.subtitles && cur.subtitles.length) || 0; - if (!(i === -1 || (Number.isInteger(i) && i >= 0 && i < n))) return { ok: false, error: 'Unknown subtitle.' }; - s.subtitle = i; - this._emit('subtitle'); - return { ok: true }; - } - case 'quality': { - const i = Number(args.index); - if (!(i === -1 || s.levels.some((l) => l.index === i))) return { ok: false, error: 'Unknown quality.' }; - s.quality = i; - this._emit('quality'); - return { ok: true }; - } - case 'episode': { - if (!s.media || s.media.type !== 'tv') return { ok: false, error: 'Not a series.' }; - const season = Number(args.season); - const episode = Number(args.episode); - if (!(season > 0 && episode > 0)) return { ok: false, error: 'Bad episode.' }; - await this.load({ type: 'tv', tmdb: s.media.tmdb, season, episode }); - return { ok: true }; - } - case 'next': - return await this._gotoEpisode(1); - case 'prev': - return await this._gotoEpisode(-1); - case 'stop': - this.close('stop'); - return { ok: true }; - default: - return { ok: false, error: `Unknown op ${op}` }; - } - } catch (e) { - console.warn(`[room ${this.id}] command ${op}: ${e.message}`); - return { ok: false, error: e.message }; - } - } - - /* ---- client reports (leader only) ---- */ - - report(data = {}, userId) { - const s = this.state; - if (this.closed || !userId || userId !== s.leader || !data) return false; - if (data.sourceId && data.sourceId !== s.sourceId) return false; // stale report about an old source - const reasons = []; - if (Number(data.duration) > 0 && Math.abs(data.duration - s.duration) > 0.5) { - s.duration = Number(data.duration); - const cur = this.current(); - if (cur) this.rooms.lastProvider.set(this._lastProviderKey(), cur.provider); - reasons.push('duration'); - } - if (Array.isArray(data.levels)) { - const levels = data.levels - .map((l, i) => ({ index: Number.isInteger(l.index) ? l.index : i, height: Number(l.height) || 0, bitrate: Number(l.bitrate) || 0 })) - .slice(0, 50); - if (JSON.stringify(levels) !== JSON.stringify(s.levels)) { - s.levels = levels; - if (s.quality >= 0 && !levels.some((l) => l.index === s.quality)) s.quality = -1; - reasons.push('levels'); - } - } - if (typeof data.buffering === 'boolean' && data.buffering !== s.buffering) { - s.buffering = data.buffering; - reasons.push('buffering'); - } - const settled = this.now() - (this._clockSetAt || 0) > 3000; // heartbeat may predate a seek - if (s.playing && settled && data.position != null && Number.isFinite(Number(data.position))) { - const p = Number(data.position); - if (Math.abs(p - this.clock()) > DRIFT_S) { - this._setClock(p, true, false); - reasons.push('drift'); - } - } - if (reasons.length) this._emit(reasons[0]); - this._checkPrefetch(); - if (data.error && data.error.fatal) { - this._failover(data.error.message); - return true; - } - if (data.ended) this._ended(); - return true; - } - - _ended() { - const s = this.state; - if (s.media && s.media.type === 'tv') { - this.episodeRef(1) - .then((ref) => { - if (this.closed) return; - if (ref) return this.load({ type: 'tv', tmdb: s.media.tmdb, ...ref }); - this._setClock(s.duration || this.clock(), false); - this._emit('ended'); - }) - .catch((e) => console.warn(`[room ${this.id}] next: ${e.message}`)); - } else { - this._setClock(s.duration || this.clock(), false); - this._emit('ended'); - } - } - - /* ---- viewers / leader ---- */ - - join(userId) { - if (this.closed || !userId) return; - const s = this.state; - this._conns.set(userId, (this._conns.get(userId) || 0) + 1); - let reason = null; - if (!s.viewers.includes(userId)) { - s.viewers.push(userId); - reason = 'join'; - } - if (!s.leader) { - s.leader = userId; - reason = reason || 'leader'; - } - if (this._autoplay && s.sourceId) { - this._autoplay = false; - this._setClock(this.clock(), true); - reason = 'play'; - } - if (reason) this._emit(reason); - } - - leave(userId) { - const s = this.state; - const n = (this._conns.get(userId) || 0) - 1; - if (n > 0) return void this._conns.set(userId, n); - this._conns.delete(userId); - if (!s.viewers.includes(userId)) return; - s.viewers = s.viewers.filter((v) => v !== userId); - if (s.leader === userId) { - s.leader = s.viewers[0] || null; - s.buffering = false; - } - // nobody watching: hold the clock, resume when someone opens the Activity again - if (!s.viewers.length && s.playing) { - this._setClock(this.clock(), false); - this._autoplay = true; - } - this._emit('leave'); - } - - /* ---- voice channel presence / lifecycle ---- */ - - setVoiceCount(n) { - this.voiceCount = n; - if (n > 0) { - if (this._idle) this._clearTimeout(this._idle); - this._idle = null; - } else if (!this._idle && !this.closed) { - this._idle = this._timer(() => this.close('idle'), IDLE_MS); - } - } - - close(reason = 'stop') { - if (this.closed) return; - this._gen++; - this._abortScrape(); - if (this._idle) this._clearTimeout(this._idle); - this._idle = null; - this._setClock(this.clock(), false); - this.closed = true; - this._emit(reason); - this.emit('closed', this.state, reason); - this.rooms.delete(this.id, this); - } -} - -function createRooms(cfg = {}, opts = {}) { - const rooms = new EventEmitter(); - const map = new Map(); - rooms.bugtv = opts.bugtv || createBugtv(cfg); - rooms.now = opts.now || (() => Date.now()); - rooms.setTimeout = opts.setTimeout || ((fn, ms) => setTimeout(fn, ms)); - rooms.clearTimeout = opts.clearTimeout || ((t) => clearTimeout(t)); - rooms.lastProvider = new Map(); // ":" → provider that last played - rooms.get = (id) => map.get(String(id)) || null; - rooms.all = () => [...map.values()]; - rooms.create = ({ id, guildId, textChannelId }) => { - id = String(id); - let room = map.get(id); - if (room) { - if (textChannelId) room.state.textChannelId = textChannelId; - return room; - } - room = new Room(rooms, { id, guildId, textChannelId }); - map.set(id, room); - rooms.emit('created', room); - return room; - }; - rooms.delete = (id, which) => { - id = String(id); - const room = map.get(id); - if (!room || (which && room !== which)) return false; - map.delete(id); - if (!room.closed) room.close('stop'); - rooms.emit('deleted', room); - return true; - }; - return rooms; -} - -module.exports = { createRooms, Room, scoreStream, isPlayable, rank, kindOf, qualityLabel, clockOf, KIND_LABEL, GRACE_MS, IDLE_MS }; diff --git a/src/server.js b/src/server.js index 0ac6ecf..9763933 100644 --- a/src/server.js +++ b/src/server.js @@ -1,35 +1,43 @@ /* - HTTP + WebSocket server for the Activity (docs/protocol.md "HTTP + WS server"). + HTTP + WebSocket watch-party relay (docs/protocol.md, v2). - createServer(cfg, rooms, { isInVoice, discordFetch }) → http.Server (not listening) + createServer(cfg, { discordFetch?, now?, log? }) → http.Server (not listening) - GET / static Activity files from cfg.activityDir, SPA fallback to index.html - GET /api/config { applicationId } - POST /api/token {code} { access_token } (Discord OAuth2 code exchange) - GET /healthz { ok: true } - GET /ws WebSocket room sync + GET / static Activity files from cfg.activityDir, SPA fallback to index.html + GET /api/config { applicationId, dev } + POST /api/token {code} { access_token } (Discord OAuth2 code exchange) + GET /api/avatar/:id the user's Discord avatar (64px PNG), proxied: the Activity CSP blocks + cdn.discordapp.com, so avatars come from our own origin + GET /healthz { ok: true } + GET /ws watch-party WebSocket + + cfg.dev === true additionally accepts dev hellos and reverse-proxies the paths Discord's URL + mappings would handle, so dev and prod use the same URLs: + /tv/v1/* → cfg.devApiUrl/v1/* (only /tv/v1: plain /tv is the site's Series route) + /tmdb/* → https://api.themoviedb.org/* + /img/* → https://image.tmdb.org/* A leading "/.proxy" (Discord's legacy URL-mapping prefix) is stripped from every path. - - Sockets for a channel without a room yet wait in `channels` and attach as soon as the room - appears: rooms' 'created' event when it exists, otherwise a 2s poll of rooms.get(). - `discordFetch` (default: global fetch) is injectable for tests. With cfg.dev === true a - `{t:'hello', dev:true, userId, channelId}` is accepted without a Discord token. + `discordFetch` (default: global fetch) and `now` (default Date.now) are injectable for tests. */ const http = require('http'); +const https = require('https'); const fs = require('fs'); const path = require('path'); const { WebSocketServer } = require('ws'); const DISCORD_API = 'https://discord.com/api/v10'; +const DISCORD_CDN = 'https://cdn.discordapp.com'; const USER_CACHE_MS = 10 * 60 * 1000; -const COALESCE_MS = 50; -const POLL_MS = 2000; +const INSTANCE_CACHE_MS = 10 * 1000; +const AVATAR_CACHE_MS = 60 * 60 * 1000; +const HUB_TTL_MS = 10 * 60 * 1000; // empty hubs + original-host reclaim window const HELLO_TIMEOUT_MS = 15000; +const HEARTBEAT_MS = 30000; const MAX_BODY = 8 * 1024; -const MAX_WS_PAYLOAD = 16 * 1024; -const CMD_RATE = 10; // per second, per socket -const REPORT_RATE = 20; +const MAX_WS_PAYLOAD = 256 * 1024; // play snapshots carry a whole bug-tv Stream object +const MSG_RATE = 30; // per second, per socket (burst = rate) +const MAX_PATH = 2048; const MIME = { '.html': 'text/html; charset=utf-8', @@ -47,26 +55,9 @@ const MIME = { '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', '.vtt': 'text/vtt; charset=utf-8', + '.webmanifest': 'application/manifest+json', }; -function emptyState(now = Date.now()) { - return { - media: null, - stream: null, - subtitle: -1, - quality: -1, - playing: false, - position: 0, - updatedAt: now, - now, - duration: 0, - viewers: [], - leader: null, - rev: 0, - notice: null, - }; -} - function sendJson(res, status, body, headers = {}) { const data = JSON.stringify(body); res.writeHead(status, { @@ -101,9 +92,9 @@ function bucket(rate) { let tokens = rate; let last = Date.now(); return () => { - const now = Date.now(); - tokens = Math.min(rate, tokens + ((now - last) / 1000) * rate); - last = now; + const t = Date.now(); + tokens = Math.min(rate, tokens + ((t - last) / 1000) * rate); + last = t; if (tokens < 1) return false; tokens -= 1; return true; @@ -114,19 +105,24 @@ function stripProxy(pathname) { return pathname === '/.proxy' ? '/' : pathname.startsWith('/.proxy/') ? pathname.slice(7) : pathname; } -function createServer(cfg, rooms, opts = {}) { - const isInVoice = opts.isInVoice || (async () => false); +const ID_RE = /^[\w.:-]{1,128}$/; + +function createServer(cfg, opts = {}) { const discordFetch = opts.discordFetch || ((...a) => fetch(...a)); - const activityDir = path.resolve(cfg.activityDir || path.join(__dirname, '..', 'activity')); + const now = opts.now || Date.now; + const activityDir = path.resolve(cfg.activityDir || path.join(__dirname, '..', 'site')); const log = opts.log || ((...a) => console.log('tv-discord:', ...a)); + const dev = cfg.dev === true; + const appId = String(cfg.applicationId || ''); /* ---- Discord HTTP ------------------------------------------------------ */ const userCache = new Map(); // token → { user, exp } + const avatarHash = new Map(); // userId → avatar hash | null (Discord users we have seen) async function exchangeCode(code) { const body = new URLSearchParams({ - client_id: String(cfg.applicationId || ''), + client_id: appId, client_secret: String(cfg.clientSecret || ''), grant_type: 'authorization_code', code, @@ -144,22 +140,103 @@ function createServer(cfg, rooms, opts = {}) { } async function userForToken(token) { - const now = Date.now(); + const t = now(); const hit = userCache.get(token); - if (hit && hit.exp > now) return hit.user; + if (hit && hit.exp > t) return hit.user; const r = await discordFetch(`${DISCORD_API}/users/@me`, { headers: { Authorization: `Bearer ${token}` } }); if (!r.ok) throw new Error(`invalid token (${r.status})`); const u = await r.json(); if (!u || !u.id) throw new Error('invalid token'); - const user = { id: String(u.id), username: u.global_name || u.username || String(u.id) }; + const id = String(u.id); + const user = { id, username: String(u.global_name || u.username || id).slice(0, 64), avatar: `/api/avatar/${id}` }; + avatarHash.set(id, typeof u.avatar === 'string' && /^\w{1,64}$/.test(u.avatar) ? u.avatar : null); if (userCache.size > 5000) { - for (const [k, v] of userCache) if (v.exp <= now) userCache.delete(k); + for (const [k, v] of userCache) if (v.exp <= t) userCache.delete(k); if (userCache.size > 5000) userCache.clear(); } - userCache.set(token, { user, exp: now + USER_CACHE_MS }); + userCache.set(token, { user, exp: t + USER_CACHE_MS }); return user; } + // instanceId → { users:Set, exp } ; inflight: instanceId → Promise + const instanceCache = new Map(); + const instanceInflight = new Map(); + + function loadInstance(instanceId) { + let p = instanceInflight.get(instanceId); + if (p) return p; + p = (async () => { + const r = await discordFetch(`${DISCORD_API}/applications/${appId}/activity-instances/${encodeURIComponent(instanceId)}`, { + headers: { Authorization: `Bot ${cfg.token || ''}` }, + }); + let users = new Set(); + if (r.ok) { + const data = await r.json().catch(() => ({})); + const list = Array.isArray(data && data.users) ? data.users : []; + users = new Set(list.map((u) => String(u && typeof u === 'object' ? u.id : u))); + } else if (r.status !== 404) { + throw new Error(`activity-instances ${r.status}`); + } + const entry = { users, exp: now() + INSTANCE_CACHE_MS }; + if (instanceCache.size > 2000) instanceCache.clear(); + instanceCache.set(instanceId, entry); + return entry; + })().finally(() => instanceInflight.delete(instanceId)); + instanceInflight.set(instanceId, p); + return p; + } + + /** Is `userId` in the Activity instance? Cached 10s; one refetch when a cached list misses. */ + async function isMember(instanceId, userId) { + let e = instanceCache.get(instanceId); + let fresh = false; + if (!e || e.exp <= now()) { + e = await loadInstance(instanceId); + fresh = true; + } + if (e.users.has(userId)) return true; + if (fresh) return false; + e = await loadInstance(instanceId); + return e.users.has(userId); + } + + /* ---- avatars ----------------------------------------------------------- */ + + const avatarCache = new Map(); // userId → { hash, type, body, exp } + + async function serveAvatar(req, res, userId) { + if (!avatarHash.has(userId)) return sendJson(res, 404, { error: 'unknown user' }); + const hash = avatarHash.get(userId); + let hit = avatarCache.get(userId); + if (!hit || hit.hash !== hash || hit.exp <= now()) { + let url; + if (hash) url = `${DISCORD_CDN}/avatars/${userId}/${hash}.png?size=64`; + else { + let idx = 0; + try { + idx = Number((BigInt(userId) >> 22n) % 6n); + } catch (e) { + /* non-numeric id */ + } + url = `${DISCORD_CDN}/embed/avatars/${idx}.png`; + } + const r = await discordFetch(url); + if (!r.ok) return sendJson(res, 502, { error: `avatar ${r.status}` }); + const body = Buffer.from(await r.arrayBuffer()); + const type = (r.headers && r.headers.get && r.headers.get('content-type')) || 'image/png'; + hit = { hash, type: /^image\//.test(type) ? type : 'image/png', body, exp: now() + AVATAR_CACHE_MS }; + if (avatarCache.size > 1000) avatarCache.clear(); + avatarCache.set(userId, hit); + } + res.writeHead(200, { + 'Content-Type': hit.type, + 'Content-Length': hit.body.length, + 'Cache-Control': 'public, max-age=600', + 'X-Content-Type-Options': 'nosniff', + }); + res.end(req.method === 'HEAD' ? undefined : hit.body); + } + /* ---- static ------------------------------------------------------------ */ function cacheControl(ext) { @@ -208,6 +285,37 @@ function createServer(cfg, rooms, opts = {}) { }); } + /* ---- dev reverse proxy (mirrors Discord's URL mappings) --------------- */ + + function devTarget(p, search) { + if (!dev) return null; + if (p.startsWith('/tv/v1/') && cfg.devApiUrl) return cfg.devApiUrl + p.slice(3) + search; + if (p.startsWith('/tmdb/')) return `https://api.themoviedb.org${p.slice(5)}${search}`; + if (p.startsWith('/img/')) return `https://image.tmdb.org${p.slice(4)}${search}`; + return null; + } + + function proxy(req, res, target) { + const u = new URL(target); + const headers = { ...req.headers, host: u.host }; + delete headers.origin; + delete headers.referer; + delete headers.cookie; + const mod = u.protocol === 'https:' ? https : http; + const up = mod.request(u, { method: req.method, headers }, (ur) => { + const h = { ...ur.headers }; + delete h['set-cookie']; + res.writeHead(ur.statusCode || 502, h); + ur.pipe(res); + }); + up.on('error', (e) => { + if (!res.headersSent) sendJson(res, 502, { error: `proxy: ${e.message}` }); + else res.destroy(); + }); + res.on('close', () => !res.writableFinished && up.destroy()); + req.pipe(up); + } + /* ---- http -------------------------------------------------------------- */ async function onRequest(req, res) { @@ -219,10 +327,12 @@ function createServer(cfg, rooms, opts = {}) { } const p = stripProxy(url.pathname); try { + const target = devTarget(p, url.search); + if (target) return proxy(req, res, target); if (p === '/healthz') return sendJson(res, 200, { ok: true }); if (p === '/api/config') { if (req.method !== 'GET' && req.method !== 'HEAD') return sendJson(res, 405, { error: 'method not allowed' }); - return sendJson(res, 200, { applicationId: String(cfg.applicationId || ''), dev: cfg.dev === true }); + return sendJson(res, 200, { applicationId: appId, dev }); } if (p === '/api/token') { if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' }); @@ -237,6 +347,11 @@ function createServer(cfg, rooms, opts = {}) { const access_token = await exchangeCode(code); return sendJson(res, 200, { access_token }); } + const av = /^\/api\/avatar\/(\d{1,25})$/.exec(p); + if (av) { + if (req.method !== 'GET' && req.method !== 'HEAD') return sendJson(res, 405, { error: 'method not allowed' }); + return await serveAvatar(req, res, av[1]); + } if (p.startsWith('/api/')) return sendJson(res, 404, { error: 'not found' }); if (req.method !== 'GET' && req.method !== 'HEAD') return sendJson(res, 405, { error: 'method not allowed' }); return serveStatic(req, res, p); @@ -251,118 +366,97 @@ function createServer(cfg, rooms, opts = {}) { onRequest(req, res); }); - /* ---- channels ---------------------------------------------------------- */ + /* ---- hubs -------------------------------------------------------------- */ - // channelId → { id, room, sockets:Set, users: Map, timer, detach } - const channels = new Map(); - const deadRooms = new WeakSet(); + // instanceId → { id, members: Map}> (join order), host, owner, + // ownerLeftAt, route, play, emptySince } + // owner = the first user ever in the hub (the one who started the instance). + const hubs = new Map(); - function getChannel(id) { - let ch = channels.get(id); - if (!ch) { - ch = { id, room: null, sockets: new Set(), users: new Map(), timer: null, detach: null }; - channels.set(id, ch); + function getHub(id) { + let hub = hubs.get(id); + if (hub && !hub.members.size && now() - hub.emptySince > HUB_TTL_MS) { + hubs.delete(id); + hub = null; } - return ch; - } - - function stateOf(ch) { - return ch.room ? ch.room.publicState(Date.now()) : emptyState(); + if (!hub) { + hub = { id, members: new Map(), host: null, owner: null, ownerLeftAt: 0, route: null, play: null, emptySince: now() }; + hubs.set(id, hub); + } + return hub; } function send(ws, msg) { - if (ws.readyState === 1) ws.send(JSON.stringify(msg)); + if (ws.readyState === 1) ws.send(typeof msg === 'string' ? msg : JSON.stringify(msg)); } - function broadcast(ch) { - ch.timer = null; - if (!ch.sockets.size) return; - const data = JSON.stringify({ t: 'state', state: stateOf(ch) }); - for (const ws of ch.sockets) if (ws.readyState === 1) ws.send(data); + function broadcast(hub, msg, exceptUser = null) { + const data = JSON.stringify(msg); + for (const [uid, m] of hub.members) { + if (uid === exceptUser) continue; + for (const ws of m.sockets) send(ws, data); + } } - function scheduleBroadcast(ch) { - if (!ch.timer) ch.timer = setTimeout(() => broadcast(ch), COALESCE_MS); + const membersOf = (hub) => [...hub.members.values()].map((m) => m.user); + + function join(hub, user, ws) { + let m = hub.members.get(user.id); + const isNew = !m; + if (!m) { + m = { user, sockets: new Set() }; + hub.members.set(user.id, m); + } else m.user = user; + m.sockets.add(ws); + + const before = hub.host; + if (!hub.owner) hub.owner = user.id; + if (!hub.host || !hub.members.has(hub.host)) hub.host = user.id; + else if (user.id === hub.owner && hub.host !== user.id && now() - hub.ownerLeftAt <= HUB_TTL_MS) { + hub.host = user.id; // the original host is back within the window: reclaim + } + + send(ws, { t: 'welcome', you: user, host: hub.host, members: membersOf(hub), route: hub.route, play: hub.play, now: now() }); + if (isNew) broadcast(hub, { t: 'members', members: membersOf(hub) }, user.id); + if (hub.host !== before && before) broadcast(hub, { t: 'host', host: hub.host }, user.id); } - function joinUser(ch, userId) { - const n = ch.users.get(userId) || 0; - ch.users.set(userId, n + 1); - if (n === 0 && ch.room) ch.room.join(userId); + function leave(hub, userId, ws) { + const m = hub.members.get(userId); + if (!m) return; + m.sockets.delete(ws); + if (m.sockets.size) return; + hub.members.delete(userId); + if (userId === hub.owner) hub.ownerLeftAt = now(); + if (!hub.members.size) { + hub.emptySince = now(); // keep host/route/play for the TTL so a rejoin resumes + return; + } + const wasHost = hub.host === userId; + if (wasHost) hub.host = hub.members.keys().next().value; // earliest remaining member + broadcast(hub, { t: 'members', members: membersOf(hub) }); + if (wasHost) broadcast(hub, { t: 'host', host: hub.host }); } - function leaveUser(ch, userId) { - const n = ch.users.get(userId) || 0; - if (n <= 1) { - ch.users.delete(userId); - if (n === 1 && ch.room) ch.room.leave(userId); - } else ch.users.set(userId, n - 1); + function onRoute(hub, msg) { + const p = msg.path; + if (typeof p !== 'string' || !p.startsWith('/') || p.length > MAX_PATH) return; + hub.route = p; + // a snapshot for another page is stale for late joiners + if (hub.play && typeof hub.play.path === 'string' && hub.play.path !== p) hub.play = null; + broadcast(hub, { t: 'route', path: p }, hub.host); } - function attach(ch, room) { - if (ch.room === room || deadRooms.has(room)) return; - if (ch.detach) ch.detach(); - ch.room = room; - const onChange = () => scheduleBroadcast(ch); - const onClosed = () => { - deadRooms.add(room); - if (ch.room !== room) return; - ch.detach(); - ch.room = null; - if (ch.timer) clearTimeout(ch.timer); - ch.timer = null; - broadcast(ch); // room gone → empty state, sockets keep waiting for the next room - ensurePoll(); - }; - room.on('change', onChange); - room.on('closed', onClosed); - ch.detach = () => { - room.removeListener('change', onChange); - room.removeListener('closed', onClosed); - ch.detach = null; - }; - for (const userId of ch.users.keys()) room.join(userId); - scheduleBroadcast(ch); - } - - function lookup(ch) { - if (ch.room) return; - const room = rooms.get(ch.id); - if (room && !deadRooms.has(room)) attach(ch, room); - } - - function dropChannelIfEmpty(ch) { - if (ch.sockets.size) return; - if (ch.detach) ch.detach(); - if (ch.timer) clearTimeout(ch.timer); - channels.delete(ch.id); - } - - // room creation: event if rooms emits one, plus a poll for waiting channels as a fallback - let pollTimer = null; - function ensurePoll() { - if (pollTimer) return; - pollTimer = setInterval(() => { - let waiting = 0; - for (const ch of channels.values()) { - if (ch.room) continue; - lookup(ch); - if (!ch.room) waiting++; - } - if (!waiting) { - clearInterval(pollTimer); - pollTimer = null; - } - }, POLL_MS); - if (pollTimer.unref) pollTimer.unref(); - } - - if (rooms && typeof rooms.on === 'function') { - rooms.on('created', (room) => { - const id = room && (room.id || (room.state && room.state.id)); - const ch = id != null && channels.get(String(id)); - if (ch && !ch.room) attach(ch, room); - }); + function onPlay(hub, msg) { + const s = msg.snapshot; + if (s === null) { + hub.play = null; + return broadcast(hub, { t: 'play', snapshot: null }, hub.host); + } + if (!s || typeof s !== 'object' || Array.isArray(s)) return; + const snapshot = { ...s, at: now() }; + hub.play = snapshot; + broadcast(hub, { t: 'play', snapshot }, hub.host); } /* ---- websocket --------------------------------------------------------- */ @@ -384,72 +478,74 @@ function createServer(cfg, rooms, opts = {}) { wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req)); }); + // half-open sockets (host's network dropped) must close so the host hands over + const heartbeat = setInterval(() => { + for (const ws of wss.clients) { + if (ws.alive === false) { + ws.terminate(); + continue; + } + ws.alive = false; + try { + ws.ping(); + } catch (e) { + /* closing */ + } + } + }, HEARTBEAT_MS); + if (heartbeat.unref) heartbeat.unref(); + wss.on('connection', (ws) => { let user = null; - let ch = null; + let hub = null; let authing = false; - const cmdOk = bucket(CMD_RATE); - const reportOk = bucket(REPORT_RATE); - const msgOk = bucket(50); + const msgOk = bucket(MSG_RATE); + ws.alive = true; + ws.on('pong', () => (ws.alive = true)); const fatal = (message) => { send(ws, { t: 'error', message }); ws.close(4001, message.slice(0, 100)); }; const helloTimer = setTimeout(() => !user && fatal('hello timeout'), HELLO_TIMEOUT_MS); + if (helloTimer.unref) helloTimer.unref(); async function hello(msg) { if (user || authing) return; authing = true; - const channelId = String(msg.channelId || ''); - if (!/^\d{1,25}$/.test(channelId)) return fatal('missing channelId'); + const instanceId = String(msg.instanceId || ''); + if (!ID_RE.test(instanceId)) return fatal('missing instanceId'); let u; - try { - if (msg.dev && cfg.dev === true) { - const id = String(msg.userId || msg.user || ''); - if (!/^[\w-]{1,32}$/.test(id)) return fatal('missing userId'); - u = { id, username: String(msg.username || `dev-${id}`).slice(0, 32) }; - } else { - if (typeof msg.token !== 'string' || !msg.token) return fatal('missing token'); + if (msg.dev) { + if (!dev) return fatal('dev mode is off'); + const id = String(msg.userId || ''); + if (!/^[\w-]{1,32}$/.test(id)) return fatal('missing userId'); + u = { id, username: String(msg.username || `dev-${id}`).slice(0, 32), avatar: null }; + } else { + if (typeof msg.token !== 'string' || !msg.token || msg.token.length > 512) return fatal('missing token'); + try { u = await userForToken(msg.token); + } catch (e) { + return fatal('authentication failed'); } - } catch (e) { - return fatal('authentication failed'); - } - let ok = false; - try { - ok = await isInVoice(channelId, u.id); - } catch (e) { - ok = false; + let ok = false; + try { + ok = await isMember(instanceId, u.id); + } catch (e) { + log('membership check failed', instanceId, e.message); + return fatal('membership check failed'); + } + if (!ok) return fatal('not in this activity'); } if (ws.readyState !== 1) return; - if (!ok) return fatal('join the voice channel first'); clearTimeout(helloTimer); user = u; - ch = getChannel(channelId); - ch.sockets.add(ws); - lookup(ch); - joinUser(ch, user.id); - if (!ch.room) ensurePoll(); - send(ws, { t: 'welcome', user, state: stateOf(ch) }); - } - - function run(fn) { - try { - const r = fn(); - if (r && typeof r.then === 'function') { - r.then( - (res) => res && res.ok === false && res.error && send(ws, { t: 'error', message: String(res.error) }), - (e) => send(ws, { t: 'error', message: String(e.message || e) }), - ); - } - } catch (e) { - send(ws, { t: 'error', message: String(e.message || e) }); - } + hub = getHub(instanceId); + join(hub, user, ws); } ws.on('message', (raw, isBinary) => { - if (isBinary || !msgOk()) return; + if (isBinary) return; let msg; try { msg = JSON.parse(raw.toString('utf8')); @@ -457,52 +553,48 @@ function createServer(cfg, rooms, opts = {}) { return; } if (!msg || typeof msg !== 'object') return; + if (!msgOk()) { + if (msg.t !== 'ping') send(ws, { t: 'error', message: 'slow down' }); + return; + } switch (msg.t) { case 'ping': - return send(ws, { t: 'pong', at: msg.at, now: Date.now() }); + return send(ws, { t: 'pong', at: msg.at, now: now() }); case 'hello': return void hello(msg); - case 'cmd': { - if (!user) return; - if (!cmdOk()) return send(ws, { t: 'error', message: 'slow down' }); - if (typeof msg.op !== 'string') return; - if (!ch.room) return send(ws, { t: 'error', message: 'nothing is playing' }); - const args = msg.args && typeof msg.args === 'object' ? msg.args : {}; - return run(() => ch.room.command(msg.op, args, user.id)); - } - case 'report': { - if (!user || !ch.room || !reportOk()) return; - const { t, ...data } = msg; - return run(() => ch.room.report(data, user.id)); - } + case 'route': + if (user && hub && hub.host === user.id) onRoute(hub, msg); + return; + case 'play': + if (user && hub && hub.host === user.id) onPlay(hub, msg); + return; default: } }); ws.on('close', () => { clearTimeout(helloTimer); - if (!user || !ch) return; - ch.sockets.delete(ws); - leaveUser(ch, user.id); - dropChannelIfEmpty(ch); + if (user && hub) leave(hub, user.id, ws); }); ws.on('error', () => {}); }); + // drop long-empty hubs + const sweep = setInterval(() => { + for (const [id, hub] of hubs) if (!hub.members.size && now() - hub.emptySince > HUB_TTL_MS) hubs.delete(id); + }, 60 * 1000); + if (sweep.unref) sweep.unref(); + server.on('close', () => { - if (pollTimer) clearInterval(pollTimer); - pollTimer = null; + clearInterval(heartbeat); + clearInterval(sweep); for (const ws of wss.clients) ws.terminate(); wss.close(); - for (const ch of channels.values()) { - if (ch.timer) clearTimeout(ch.timer); - if (ch.detach) ch.detach(); - } }); server.wss = wss; - server.channels = channels; + server.hubs = hubs; return server; } -module.exports = { createServer, emptyState }; +module.exports = { createServer }; diff --git a/test/bot.test.js b/test/bot.test.js deleted file mode 100644 index 0d73c1f..0000000 --- a/test/bot.test.js +++ /dev/null @@ -1,99 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const { createRooms } = require('../src/room'); -const { createBotContext } = require('../src/bot'); -const { handleCommand } = require('../src/bot/commands'); -const { handleComponent } = require('../src/bot/controls'); -const { fakeBugtv, stream } = require('./helpers'); - -function fakeDiscord() { - const edits = []; - const voice = new Map([['u1', { id: 'u1', channelId: 'vc', member: { user: { bot: false } } }]]); - const guild = { id: 'g', voiceStates: { cache: voice } }; - const text = { id: 't', guild, messages: { edit: async (id, p) => edits.push({ id, p }), delete: async () => {} } }; - const vc = { id: 'vc', guild }; - const channels = new Map([['vc', vc], ['t', text]]); - const client = { channels: { cache: channels, fetch: async (id) => channels.get(id) }, users: { cache: new Map() } }; - return { client, guild, edits, voice }; -} - -function interaction(guild, extra) { - const calls = []; - const rec = (name, ret) => async (arg) => { - calls.push([name, arg]); - return ret; - }; - return { - calls, - guild, - guildId: 'g', - channelId: 't', - user: { id: 'u1' }, - deferReply: rec('deferReply'), - deferUpdate: rec('deferUpdate'), - editReply: rec('editReply', { id: 'm1' }), - reply: rec('reply'), - update: rec('update'), - followUp: rec('followUp'), - showModal: rec('showModal'), - isAnySelectMenu: () => false, - ...extra, - }; -} - -test('/watch creates the room, posts the control message; buttons drive the room', async () => { - const bugtv = fakeBugtv(); - const rooms = createRooms({}, { bugtv }); - const d = fakeDiscord(); - const ctx = createBotContext({}, rooms, d.client); - ctx.updater.stop(); - - const w = interaction(d.guild, { - commandName: 'watch', - options: { getString: () => 'movie:550', getInteger: () => null }, - }); - await handleCommand(w, ctx); - const room = rooms.get('vc'); - assert.ok(room); - assert.equal(room.state.messageId, 'm1'); - assert.equal(room.voiceCount, 1); - const payload = w.calls.find((c) => c[0] === 'editReply')[1]; - assert.equal(payload.embeds[0].title, 'Fight Club (1999)'); - assert.equal(payload.components.length, 5); - - bugtv.last().h.onStreams({ provider: 'a', streams: [stream('a1'), stream('a2', { pixels: 720 })] }); - assert.equal(room.state.sourceId, 'a1'); - - const click = interaction(d.guild, { customId: 'tv:toggle:vc', message: { id: 'm1' } }); - await handleComponent(click, ctx); - assert.equal(click.calls[0][0], 'deferUpdate'); - assert.equal(room.state.playing, true); - - const sel = interaction(d.guild, { customId: 'tv:src:vc', message: { id: 'm1' }, values: ['a2'], isAnySelectMenu: () => true }); - await handleComponent(sel, ctx); - assert.equal(room.state.sourceId, 'a2'); - - // user not in the VC → ephemeral error, no change - d.voice.delete('u1'); - const out = interaction(d.guild, { customId: 'tv:toggle:vc', message: { id: 'm1' } }); - await handleComponent(out, ctx); - assert.equal(out.calls[0][0], 'reply'); - assert.match(out.calls[0][1].content, /Join <#vc>/); - assert.equal(room.state.playing, true); - d.voice.set('u1', { id: 'u1', channelId: 'vc', member: { user: { bot: false } } }); - - // seek modal submit - room.report({ duration: 1000 }, null); - const form = interaction(d.guild, { customId: 'tv:seekForm:vc', fields: { getTextInputValue: () => '1:00' } }); - await handleComponent(form, ctx); - assert.ok(Math.abs(room.clock() - 60) < 1); - - // updater edits the message, then the final "Stopped" edit drops components - await ctx.updater.flush(room); - assert.ok(d.edits.length >= 1); - await room.command('stop', {}, 'u1'); - await new Promise((r) => setTimeout(r, 10)); - const last = d.edits[d.edits.length - 1]; - assert.deepEqual(last.p.components, []); - assert.match(last.p.embeds[0].description, /Stopped/); -}); diff --git a/test/helpers.js b/test/helpers.js deleted file mode 100644 index cd7f088..0000000 --- a/test/helpers.js +++ /dev/null @@ -1,91 +0,0 @@ -// Fake bug-tv client + controllable clock for room tests. - -function fakeClock(start = Date.parse('2026-01-01T00:00:00Z')) { - let now = start; - let seq = 0; - const timers = new Map(); - return { - now: () => now, - setTimeout(fn, ms) { - const id = ++seq; - timers.set(id, { at: now + ms, fn }); - return id; - }, - clearTimeout(id) { - timers.delete(id); - }, - advance(ms) { - const end = now + ms; - for (;;) { - let next = null; - for (const [id, t] of timers) if (t.at <= end && (!next || t.at < next[1].at)) next = [id, t]; - if (!next) break; - timers.delete(next[0]); - now = next[1].at; - next[1].fn(); - } - now = end; - }, - pending: () => timers.size, - }; -} - -function stream(id, o = {}) { - return { - id, - provider: o.provider || 'p', - name: o.name || `${id} name`, - title: o.title || '', - quality: o.pixels ? `${o.pixels}p` : '', - pixels: o.pixels == null ? 1080 : o.pixels, - type: o.type || 'm3u8', - size: o.size || 0, - seeds: o.seeds == null ? null : o.seeds, - subtitles: o.subtitles || [], - playback: { kind: o.kind || 'hls', url: `/v1/p/${id}/x.m3u8`, ...(o.fallback ? { fallback: `/v1/p/${id}/f` } : {}) }, - }; -} - -const SHOW = { - id: 1399, - name: 'Show', - first_air_date: '2011-04-17', - poster_path: '/p.jpg', - backdrop_path: '/b.jpg', - overview: 'A show.', - seasons: [ - { season_number: 0, episode_count: 5, name: 'Specials' }, - { season_number: 1, episode_count: 3, air_date: '2011-04-17' }, - { season_number: 2, episode_count: 2, air_date: '2012-04-01' }, - ], -}; -const MOVIE = { id: 550, title: 'Fight Club', release_date: '1999-10-15', poster_path: '/fc.jpg', backdrop_path: '/fcb.jpg', overview: 'Soap.' }; -const ep = (n, air = '2011-01-01') => ({ episode_number: n, name: `Ep ${n}`, air_date: air, still_path: `/s${n}.jpg`, overview: `ep ${n}` }); -const SEASONS = { 0: [ep(1)], 1: [ep(1), ep(2), ep(3)], 2: [ep(1), ep(2)] }; - -function fakeBugtv() { - const calls = { streams: [], prefetch: [] }; - return { - calls, - last: () => calls.streams[calls.streams.length - 1], - streams(params, h) { - calls.streams.push({ params, h }); - return new Promise(() => {}); // the test drives the handlers - }, - async prefetch(params) { - calls.prefetch.push(params); - return { queued: [] }; - }, - async searchMulti() { - return []; - }, - async details(type) { - return type === 'tv' ? SHOW : MOVIE; - }, - async season(id, n) { - return { season_number: n, episodes: SEASONS[n] || [] }; - }, - }; -} - -module.exports = { fakeClock, fakeBugtv, stream, SHOW, MOVIE }; diff --git a/test/render.test.js b/test/render.test.js deleted file mode 100644 index f00f250..0000000 --- a/test/render.test.js +++ /dev/null @@ -1,152 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const { createRooms } = require('../src/room'); -const { render, progressBar } = require('../src/bot/render'); -const { parseSeek } = require('../src/bot/controls'); -const { choiceFor } = require('../src/bot/autocomplete'); -const { fakeClock, fakeBugtv, stream } = require('./helpers'); - -async function bigRoom(media) { - const clock = fakeClock(); - const bugtv = fakeBugtv(); - const rooms = createRooms({}, { bugtv, now: clock.now, setTimeout: clock.setTimeout, clearTimeout: clock.clearTimeout }); - const room = rooms.create({ id: '123456789012345678', guildId: 'g', textChannelId: 't' }); - await room.load(media); - const h = bugtv.last().h; - const streams = Array.from({ length: 60 }, (_, i) => - stream(`id${String(i).padStart(10, '0')}`, { - pixels: [2160, 1080, 720, 480][i % 4], - kind: ['hls', 'file', 'remux', 'torrent'][i % 4], - provider: `provider-with-a-pretty-long-name-${i}`, - name: 'X'.repeat(300), - size: 2.1e9, - seeds: 12, - subtitles: Array.from({ length: 40 }, (_, j) => ({ url: `/v1/subs/${j}`, lang: 'en', label: `English ${'y'.repeat(150)} ${j}` })), - }), - ); - h.onStreams({ provider: 'p', streams }); - room.join('u1'); - room.report({ duration: 3500, levels: Array.from({ length: 30 }, (_, i) => ({ height: 144 + i * 40, bitrate: i * 1e5 })) }, 'u1'); - return { room, clock }; -} - -function checkLimits(out) { - assert.ok(out.components.length <= 5, 'max 5 rows'); - const ids = new Set(); - for (const row of out.components) { - assert.equal(row.type, 1); - assert.ok(row.components.length >= 1 && row.components.length <= 5); - const selects = row.components.filter((c) => c.type === 3); - if (selects.length) assert.equal(row.components.length, 1, 'select alone in its row'); - for (const c of row.components) { - assert.ok(c.custom_id.length <= 100); - assert.ok(!ids.has(c.custom_id), `duplicate ${c.custom_id}`); - ids.add(c.custom_id); - if (c.type === 2 && c.label) assert.ok(c.label.length <= 80); - if (c.type === 3) { - assert.ok(c.options.length >= 1 && c.options.length <= 25, `${c.custom_id} has ${c.options.length}`); - assert.ok(c.placeholder.length <= 150); - const values = new Set(); - let defaults = 0; - for (const o of c.options) { - assert.ok(o.label.length >= 1 && o.label.length <= 100); - assert.ok(o.value.length <= 100); - if (o.description) assert.ok(o.description.length <= 100); - assert.ok(!values.has(o.value), 'unique values'); - values.add(o.value); - if (o.default) defaults++; - } - assert.ok(defaults <= 1); - } - } - } - const e = out.embeds[0]; - assert.ok(e.title.length <= 256); - assert.ok(e.description.length <= 4096); -} - -test('render: movie with 60 sources stays within Discord limits, pages sources', async () => { - const { room, clock } = await bigRoom({ type: 'movie', tmdb: 550 }); - const out = render(room.state, {}, clock.now()); - checkLimits(out); - assert.equal(out.components.length, 5); - const src = out.components[2].components[0]; - assert.equal(src.custom_id, `tv:src:${room.id}`); - assert.equal(src.options.length, 25); - assert.equal(src.options[24].value, 'page:1'); - assert.ok(src.options.some((o) => o.default && o.value === room.state.sourceId)); - assert.match(src.options[0].label, /^4K · HLS · provider-with-a-pretty-long-name-0 · 2\.1 GB$/); - const page2 = render(room.state, { srcPage: 2 }, clock.now()); - checkLimits(page2); - const last = page2.components[2].components[0].options; - assert.equal(last.length, 13); - assert.equal(last[12].value, 'page:0'); - // buttons: row1 has 5, row2 movie has 4 (no episodes button), prev/next disabled - assert.equal(out.components[0].components.length, 5); - const row2 = out.components[1].components; - assert.deepEqual( - row2.map((c) => c.custom_id.split(':')[1]), - ['prev', 'next', 'launch', 'stop'], - ); - assert.equal(row2[2].style, 1); - assert.equal(row2[3].style, 4); - assert.equal(out.components[3].components[0].options.length, 25, 'subtitles capped'); - assert.equal(out.components[4].components[0].disabled, undefined, 'quality enabled once levels reported'); - assert.match(out.embeds[0].description, /🔘.*0:00 \/ 58:20/); - assert.ok(out.embeds[0].image.url.includes('/w1280/')); -}); - -test('render: series episodes mode swaps in season/episode selects', async () => { - const { room, clock } = await bigRoom({ type: 'tv', tmdb: 1399, season: 1, episode: 2 }); - const out = render(room.state, { mode: 'sources' }, clock.now()); - checkLimits(out); - assert.ok(out.components[1].components.some((c) => c.custom_id === `tv:episodes:${room.id}`)); - const ep = render(room.state, { mode: 'episodes', seasonData: {} }, clock.now()); - checkLimits(ep); - assert.equal(ep.components.length, 4); - assert.equal(ep.components[2].components[0].custom_id, `tv:season:${room.id}`); - assert.equal(ep.components[3].components[0].custom_id, `tv:ep:${room.id}`); - assert.ok(ep.components[1].components.some((c) => c.custom_id === `tv:sources:${room.id}`)); - assert.match(out.embeds[0].description, /\*\*S1E2 · Ep 2\*\*/); - // a long season pages around the current episode - room.state.media.seasons = [{ n: 1, count: 200 }]; - room.state.media.episode = 100; - const long = render(room.state, { mode: 'episodes', seasonData: {} }, clock.now()); - checkLimits(long); - const opts = long.components[3].components[0].options; - assert.equal(opts.length, 25); - assert.match(opts[0].value, /^page:/); - assert.match(opts[24].value, /^page:/); - assert.ok(opts.some((o) => o.value === '100' && o.default)); -}); - -test('render: closed state has no components; empty room is fine', async () => { - const { room, clock } = await bigRoom({ type: 'movie', tmdb: 550 }); - const out = render(room.state, {}, clock.now(), { closed: true }); - assert.deepEqual(out.components, []); - assert.match(out.embeds[0].description, /Stopped/); - const rooms = createRooms({}, { bugtv: fakeBugtv() }); - const empty = rooms.create({ id: 'x' }); - assert.deepEqual(render(empty.state).components, []); -}); - -test('progress bar and seek parsing', () => { - assert.equal(progressBar(50, 100), '▬▬▬▬▬🔘▬▬▬▬▬'); - assert.equal(progressBar(0, 0), '🔘▬▬▬▬▬▬▬▬▬▬'); - assert.deepEqual(parseSeek('1:23:45'), { op: 'seek', t: 5025 }); - assert.deepEqual(parseSeek('83m'), { op: 'seek', t: 4980 }); - assert.deepEqual(parseSeek('45%', 1000), { op: 'seek', t: 450 }); - assert.equal(parseSeek('45%', 0), null); - assert.deepEqual(parseSeek('90s'), { op: 'seek', t: 90 }); - assert.deepEqual(parseSeek('90'), { op: 'seek', t: 90 }); - assert.deepEqual(parseSeek('-30'), { op: 'seekBy', d: -30 }); - assert.equal(parseSeek('soon'), null); -}); - -test('autocomplete choice format', () => { - assert.deepEqual(choiceFor({ type: 'tv', id: 1399, title: 'Game of Thrones', year: '2011' }), { - name: 'Game of Thrones (2011) · Series', - value: 'tv:1399', - }); - assert.equal(choiceFor({ type: 'movie', id: 1, title: 'x'.repeat(200), year: '' }).name.length, 100); -}); diff --git a/test/room.test.js b/test/room.test.js deleted file mode 100644 index acfe953..0000000 --- a/test/room.test.js +++ /dev/null @@ -1,273 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const { createRooms, rank, scoreStream, clockOf, GRACE_MS, IDLE_MS } = require('../src/room'); -const { fakeClock, fakeBugtv, stream } = require('./helpers'); - -function setup() { - const clock = fakeClock(); - const bugtv = fakeBugtv(); - const rooms = createRooms({}, { bugtv, now: clock.now, setTimeout: clock.setTimeout, clearTimeout: clock.clearTimeout }); - const room = rooms.create({ id: 'vc1', guildId: 'g1', textChannelId: 't1' }); - const events = []; - room.on('change', (state, reason) => events.push(reason)); - return { clock, bugtv, rooms, room, events }; -} - -const flush = () => new Promise((r) => setImmediate(r)); - -async function loaded(media = { type: 'movie', tmdb: 550 }) { - const ctx = setup(); - await ctx.room.load(media); - ctx.h = ctx.bugtv.last().h; - ctx.h.onMeta({ providers: ['a', 'b', 'c'] }); - return ctx; -} - -test('ranking: 4K compressed, remux/torrent penalties, direct bonus, last provider', () => { - const s4kTorrent = stream('t', { pixels: 2160, kind: 'torrent', seeds: 50 }); - const s1080hls = stream('h', { pixels: 1080 }); - const s1080remux = stream('r', { pixels: 1080, kind: 'remux' }); - const s720direct = stream('d', { pixels: 720, fallback: true }); - const sNoPx = stream('n', { pixels: 0 }); - const bad = { id: 'x', playback: { kind: 'weird', url: 'u' } }; - assert.equal(scoreStream(s4kTorrent), 1150 - 270); - assert.equal(scoreStream(sNoPx), 400); - assert.equal(scoreStream(s720direct), 760); - assert.deepEqual( - rank([sNoPx, s720direct, s1080remux, s4kTorrent, bad, s1080hls]).map((s) => s.id), - ['h', 'r', 't', 'd', 'n'], - ); - assert.equal(rank([s1080hls, stream('h2', { pixels: 1080, provider: 'fav' })], 'fav')[0].id, 'h2'); -}); - -test('auto-pick: ≥1080p hls picks at once', async () => { - const { h, room, events } = await loaded(); - h.onStreams({ provider: 'a', streams: [stream('a1', { pixels: 1080, provider: 'a' })] }); - assert.equal(room.state.sourceId, 'a1'); - assert.ok(events.includes('source')); -}); - -test('auto-pick: lower quality waits the 1.5s grace window and takes the best by then', async () => { - const { h, room, clock } = await loaded(); - h.onStreams({ provider: 'a', streams: [stream('a1', { pixels: 720, provider: 'a' })] }); - assert.equal(room.state.sourceId, null); - clock.advance(GRACE_MS - 100); - h.onStreams({ provider: 'b', streams: [stream('b1', { pixels: 1080, kind: 'remux', provider: 'b' })] }); - assert.equal(room.state.sourceId, null, '1080p remux is not a fast pick'); - clock.advance(100); - assert.equal(room.state.sourceId, 'b1'); - // later better sources don't steal the pick - h.onStreams({ provider: 'c', streams: [stream('c1', { pixels: 2160, provider: 'c' })] }); - assert.equal(room.state.sourceId, 'b1'); - assert.equal(room.state.sources[0].id, 'c1'); -}); - -test('auto-pick: nothing playable until done → picks on done, or notice when empty', async () => { - const a = await loaded(); - a.h.onDone({ total: 0 }); - assert.equal(a.room.state.sourceId, null); - assert.equal(a.room.state.scraping, false); - assert.match(a.room.state.notice, /No sources/); -}); - -test('clock math: play / pause / seek / seekBy / clamp', async () => { - const { h, room, clock } = await loaded(); - h.onStreams({ provider: 'a', streams: [stream('a1')] }); - assert.equal(room.state.playing, false, 'no viewers yet → paused'); - room.join('u1'); - assert.equal(room.state.playing, true, 'first viewer starts autoplay'); - clock.advance(10_000); - assert.equal(room.clock(), 10); - await room.command('pause', {}, 'u1'); - clock.advance(5000); - assert.equal(room.clock(), 10); - await room.command('seek', { t: 100 }, 'u1'); - assert.equal(room.clock(), 100); - await room.command('seekBy', { d: -30 }, 'u1'); - assert.equal(room.clock(), 70); - await room.command('seekBy', { d: -300 }, 'u1'); - assert.equal(room.clock(), 0); - await room.command('toggle', {}, 'u1'); - clock.advance(2500); - assert.equal(room.clock(), 2.5); - room.report({ duration: 60 }, 'u1'); - clock.advance(120_000); - assert.equal(room.clock(), 60, 'clamped to duration'); - assert.equal(clockOf({ position: 5, playing: true, updatedAt: 0, duration: 0 }, 3000), 8); -}); - -test('failover on fatal error from the leader only, with notice', async () => { - const { h, room } = await loaded(); - h.onStreams({ provider: 'a', streams: [stream('a1', { provider: 'a' }), stream('a2', { pixels: 720, provider: 'a' })] }); - room.join('leader'); - room.join('other'); - assert.equal(room.state.leader, 'leader'); - assert.equal(room.report({ error: { fatal: true, message: 'boom' } }, 'other'), false); - assert.equal(room.state.sourceId, 'a1'); - room.report({ error: { fatal: false, message: 'meh' } }, 'leader'); - assert.equal(room.state.sourceId, 'a1'); - room.report({ error: { fatal: true, message: 'boom' } }, 'leader'); - assert.equal(room.state.sourceId, 'a2'); - assert.deepEqual(room.state.failed, ['a1']); - assert.match(room.state.notice, /a 1080p failed.*trying a 720p/); - // stale report about the old source is ignored - assert.equal(room.report({ sourceId: 'a1', error: { fatal: true } }, 'leader'), false); - // last one fails while scraping → waits, then the next arriving stream is taken at once - room.report({ error: { fatal: true } }, 'leader'); - assert.equal(room.state.sourceId, null); - assert.match(room.state.notice, /waiting/); - h.onStreams({ provider: 'b', streams: [stream('b1', { pixels: 480, provider: 'b' })] }); - assert.equal(room.state.sourceId, 'b1'); -}); - -test('leader re-election on leave; multiple connections per user', async () => { - const { room } = setup(); - room.join('u1'); - room.join('u2'); - room.join('u1'); // second device - assert.deepEqual(room.state.viewers, ['u1', 'u2']); - room.leave('u1'); - assert.equal(room.state.leader, 'u1', 'still connected once'); - room.leave('u1'); - assert.equal(room.state.leader, 'u2'); - assert.deepEqual(room.state.viewers, ['u2']); - room.leave('u2'); - assert.equal(room.state.leader, null); - room.join('u3'); - assert.equal(room.state.leader, 'u3'); -}); - -test('next / prev across seasons, skipping season 0', async () => { - const { room, bugtv } = await loaded({ type: 'tv', tmdb: 1399, season: 1, episode: 3 }); - assert.deepEqual(room.state.media.seasons, [{ n: 1, count: 3 }, { n: 2, count: 2 }]); - assert.equal(room.state.media.episodeTitle, 'Ep 3'); - let r = await room.command('next', {}, 'u'); - assert.ok(r.ok); - assert.deepEqual([room.state.media.season, room.state.media.episode], [2, 1]); - assert.deepEqual(bugtv.last().params, { tmdb: 1399, type: 'tv', season: 2, episode: 1 }); - await room.command('prev', {}, 'u'); - assert.deepEqual([room.state.media.season, room.state.media.episode], [1, 3]); - await room.command('episode', { season: 1, episode: 1 }, 'u'); - r = await room.command('prev', {}, 'u'); - assert.equal(r.ok, false, 'S1E1 has no previous (season 0 skipped)'); - await room.command('episode', { season: 2, episode: 2 }, 'u'); - r = await room.command('next', {}, 'u'); - assert.equal(r.ok, false); -}); - -test('prefetch next episode once at 80%; ended → next episode', async () => { - const { h, room, bugtv, clock } = await loaded({ type: 'tv', tmdb: 1399, season: 1, episode: 2 }); - h.onStreams({ provider: 'a', streams: [stream('a1')] }); - room.join('u1'); - room.report({ duration: 100 }, 'u1'); - clock.advance(79_000); - room.report({ position: 79 }, 'u1'); - await flush(); - assert.equal(bugtv.calls.prefetch.length, 0); - clock.advance(2000); - room.report({ position: 81 }, 'u1'); - await flush(); - clock.advance(5000); - room.report({ position: 86 }, 'u1'); - await flush(); - assert.deepEqual(bugtv.calls.prefetch, [{ tmdb: 1399, type: 'tv', season: 1, episode: 3 }]); - room.report({ ended: true }, 'u1'); - await flush(); - await flush(); - assert.equal(room.state.media.episode, 3); - assert.equal(room.state.sourceId, null); - bugtv.last().h.onStreams({ provider: 'a', streams: [stream('e3')] }); - assert.equal(room.state.sourceId, 'e3'); - assert.equal(room.state.playing, true, 'keeps playing into the next episode'); - assert.equal(room.clock(), 0); -}); - -test('movie ended pauses at the end', async () => { - const { h, room } = await loaded(); - h.onStreams({ provider: 'a', streams: [stream('a1')] }); - room.join('u1'); - room.report({ duration: 50 }, 'u1'); - room.report({ ended: true }, 'u1'); - assert.equal(room.state.playing, false); - assert.equal(room.clock(), 50); -}); - -test('drift correction from leader heartbeat, ignored right after a seek', async () => { - const { h, room, clock } = await loaded(); - h.onStreams({ provider: 'a', streams: [stream('a1')] }); - room.join('u1'); - clock.advance(20_000); - room.report({ position: 15 }, 'u1'); // leader buffered for 5s - assert.equal(room.clock(), 15); - await room.command('seek', { t: 500 }, 'u1'); - clock.advance(1000); - room.report({ position: 16 }, 'u1'); // heartbeat sent before the seek landed - assert.equal(room.clock(), 501); -}); - -test('idle close after 2 minutes at zero voice members', async () => { - const { room, rooms, clock } = await loaded(); - let closed = null; - room.on('closed', (state, reason) => (closed = reason)); - room.setVoiceCount(0); - clock.advance(IDLE_MS - 1000); - room.setVoiceCount(1); - clock.advance(IDLE_MS); - assert.equal(closed, null); - room.setVoiceCount(0); - clock.advance(IDLE_MS); - assert.equal(closed, 'idle'); - assert.equal(rooms.get('vc1'), null); - const r = await room.command('play', {}, 'u'); - assert.equal(r.ok, false); -}); - -test('stop closes the room and aborts the scrape', async () => { - const { room, rooms, bugtv } = await loaded(); - let closed = null; - room.on('closed', (s, reason) => (closed = reason)); - await room.command('stop', {}, 'u'); - assert.equal(closed, 'stop'); - assert.equal(bugtv.last().h.signal.aborted, true); - assert.equal(rooms.get('vc1'), null); -}); - -test('subtitle / quality validation and rev increments', async () => { - const { h, room } = await loaded(); - h.onStreams({ provider: 'a', streams: [stream('a1', { subtitles: [{ url: '/v1/subs/x', lang: 'en', label: 'English' }] })] }); - room.join('u1'); - const rev = room.state.rev; - assert.equal((await room.command('subtitle', { index: 0 }, 'u1')).ok, true); - assert.equal((await room.command('subtitle', { index: 3 }, 'u1')).ok, false); - assert.equal((await room.command('quality', { index: 1 }, 'u1')).ok, false); - room.report({ levels: [{ height: 720, bitrate: 3e6 }, { height: 1080, bitrate: 6e6 }] }, 'u1'); - assert.equal((await room.command('quality', { index: 1 }, 'u1')).ok, true); - assert.ok(room.state.rev > rev); -}); - -test('publicState shape', async () => { - const { h, room, clock } = await loaded(); - h.onStreams({ provider: 'a', streams: [stream('a1')] }); - room.join('u1'); - const ps = room.publicState(clock.now()); - for (const k of ['media', 'stream', 'subtitle', 'quality', 'playing', 'position', 'updatedAt', 'now', 'duration', 'viewers', 'leader', 'rev', 'notice']) { - assert.ok(k in ps, k); - } - assert.equal(ps.stream.id, 'a1'); - assert.equal(ps.now, clock.now()); - assert.equal(ps.media.title, 'Fight Club'); - assert.equal(ps.media.poster, 'https://image.tmdb.org/t/p/w500/fc.jpg'); - assert.deepEqual(ps.viewers, ['u1']); - assert.equal(ps.leader, 'u1'); -}); - -test('rooms registry emits create and reuses rooms', () => { - const { rooms, room } = setup(); - let created = 0; - rooms.on('created', () => created++); - assert.equal(rooms.create({ id: 'vc1', textChannelId: 't2' }), room); - assert.equal(room.state.textChannelId, 't2'); - rooms.create({ id: 'vc2' }); - assert.equal(created, 1); - assert.equal(rooms.all().length, 2); -}); diff --git a/test/server.test.js b/test/server.test.js index d3f5397..95601f1 100644 --- a/test/server.test.js +++ b/test/server.test.js @@ -3,68 +3,35 @@ const assert = require('node:assert/strict'); const fs = require('fs'); const os = require('os'); const path = require('path'); -const { EventEmitter } = require('events'); const WebSocket = require('ws'); const { createServer } = require('../src/server'); /* ---- fakes ----------------------------------------------------------------- */ -class FakeRoom extends EventEmitter { - constructor(id) { - super(); - this.id = id; - this.calls = []; - this.viewers = new Set(); - this.rev = 0; - this.media = { type: 'movie', tmdb: 550, title: 'Fight Club' }; - } - join(u) { - this.calls.push(['join', u]); - this.viewers.add(u); - } - leave(u) { - this.calls.push(['leave', u]); - this.viewers.delete(u); - } - command(op, args, u) { - this.calls.push(['command', op, args, u]); - this.rev++; - this.emit('change', {}, op); - } - report(data, u) { - this.calls.push(['report', data, u]); - } - publicState(now = Date.now()) { - return { media: this.media, stream: null, playing: false, position: 0, updatedAt: now, now, viewers: [...this.viewers], leader: null, rev: this.rev, notice: null }; - } -} +const USERS = { + alice: { id: '111', username: 'alice', global_name: 'Alice', avatar: 'abc123' }, + bob: { id: '222', username: 'bob', avatar: null }, + carol: { id: '333', username: 'carol', avatar: 'c0ffee' }, + mallory: { id: '999', username: 'mallory', avatar: null }, +}; -function fakeRooms({ events = false } = {}) { - const map = new Map(); - const rooms = events ? new EventEmitter() : {}; - rooms.get = (id) => map.get(id); - rooms.create = ({ id }) => { - const r = new FakeRoom(id); - map.set(id, r); - if (events) rooms.emit('created', r); - return r; - }; - rooms.delete = (id) => map.delete(id); - rooms.all = () => [...map.values()]; - return rooms; -} +const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]); -const USERS = { good: { id: '111', username: 'alice' }, bob: { id: '222', username: 'bob' } }; - -function fakeDiscord() { +function fakeDiscord(instances) { const calls = []; const fn = async (url, init = {}) => { calls.push([url, init]); - const res = (status, body) => ({ ok: status < 300, status, json: async () => body }); + const res = (status, body, type = 'application/json') => ({ + ok: status < 300, + status, + headers: new Headers({ 'content-type': type }), + json: async () => body, + arrayBuffer: async () => (Buffer.isBuffer(body) ? body : Buffer.from(JSON.stringify(body))), + }); if (url.endsWith('/oauth2/token')) { const p = new URLSearchParams(init.body); if (p.get('code') === 'goodcode' && p.get('client_secret') === 'sekrit' && p.get('grant_type') === 'authorization_code') { - return res(200, { access_token: 'good', token_type: 'Bearer' }); + return res(200, { access_token: 'alice', token_type: 'Bearer' }); } return res(400, { error: 'invalid_grant' }); } @@ -72,9 +39,25 @@ function fakeDiscord() { const tok = (init.headers.Authorization || '').replace('Bearer ', ''); return USERS[tok] ? res(200, USERS[tok]) : res(401, { message: '401: Unauthorized' }); } + const m = /\/applications\/(\w+)\/activity-instances\/([^/?]+)$/.exec(url); + if (m) { + assert.equal(init.headers.Authorization, 'Bot bot-token'); + const users = instances[decodeURIComponent(m[2])]; + if (!users) return res(404, { message: 'Unknown' }); + if (users === 'boom') return res(500, {}); + return res(200, { + application_id: m[1], + instance_id: m[2], + launch_id: '1', + location: { id: 'gc-1', kind: 'gc', channel_id: '42', guild_id: '7' }, + users: [...users], + }); + } + if (url.startsWith('https://cdn.discordapp.com/')) return res(200, PNG, 'image/png'); return res(404, {}); }; fn.calls = calls; + fn.count = (re) => calls.filter(([u]) => re.test(u)).length; return fn; } @@ -82,19 +65,14 @@ function fakeDiscord() { const activityDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tvd-act-')); fs.writeFileSync(path.join(activityDir, 'index.html'), 'x'); -fs.mkdirSync(path.join(activityDir, 'dist')); -fs.writeFileSync(path.join(activityDir, 'dist', 'main.js'), 'console.log(1)'); +fs.writeFileSync(path.join(activityDir, 'discord.js'), 'console.log(1)'); async function start(opts = {}) { - const rooms = opts.rooms || fakeRooms(); - const discordFetch = fakeDiscord(); - const voice = opts.voice || { '42': new Set(['111', '222']) }; - const cfg = { applicationId: 'app1', clientSecret: 'sekrit', activityDir, dev: !!opts.dev }; - const server = createServer(cfg, rooms, { - isInVoice: async (c, u) => !!(voice[c] && voice[c].has(u)), - discordFetch, - log: () => {}, - }); + const instances = opts.instances || { 'i-1': new Set(['111', '222', '333']) }; + const discordFetch = fakeDiscord(instances); + const clock = { t: 1_000_000 }; + const cfg = { applicationId: 'app1', clientSecret: 'sekrit', token: 'bot-token', activityDir, dev: !!opts.dev, devApiUrl: opts.devApiUrl }; + const server = createServer(cfg, { discordFetch, now: () => clock.t, log: () => {} }); await new Promise((r) => server.listen(0, '127.0.0.1', r)); const base = `http://127.0.0.1:${server.address().port}`; const sockets = []; @@ -109,7 +87,11 @@ async function start(opts = {}) { if (i >= 0) waiters.splice(i, 1)[0].resolve(m); else queue.push(m); }); - ws.next = (pred = () => true, ms = 3000) => { + ws.next = (pred = () => true, ms = 2000) => { + if (typeof pred === 'string') { + const t = pred; + pred = (m) => m.t === t; + } const i = queue.findIndex(pred); if (i >= 0) return Promise.resolve(queue.splice(i, 1)[0]); return new Promise((resolve, reject) => { @@ -123,6 +105,10 @@ async function start(opts = {}) { }, ms).unref(); }); }; + ws.none = async (t, ms = 150) => { + await assert.rejects(ws.next(t, ms), /timeout/, `unexpected ${t}`); + }; + ws.drain = () => queue.splice(0); ws.closed = new Promise((r) => ws.on('close', (code) => r(code))); ws.opened = new Promise((r, j) => { ws.on('open', r); @@ -131,14 +117,36 @@ async function start(opts = {}) { ws.json = (m) => ws.send(JSON.stringify(m)); return ws; }; + /** open + hello + welcome */ + const joinAs = async (token, instanceId = 'i-1') => { + const ws = open(); + await ws.opened; + ws.json({ t: 'hello', token, instanceId, channelId: '42' }); + ws.welcome = await ws.next('welcome'); + return ws; + }; + const devJoin = async (userId, instanceId = 'x') => { + const ws = open(); + await ws.opened; + ws.json({ t: 'hello', dev: true, userId, username: `u${userId}`, instanceId }); + ws.welcome = await ws.next('welcome'); + return ws; + }; const stop = async () => { for (const ws of sockets) ws.terminate(); - await new Promise((r) => server.close(r)); + const closed = new Promise((r) => server.close(r)); + server.closeAllConnections(); + await closed; }; - return { server, rooms, discordFetch, base, open, stop }; + return { server, discordFetch, clock, base, open, joinAs, devJoin, stop }; } const tick = (ms) => new Promise((r) => setTimeout(r, ms)); +const closeAndWait = async (ws) => { + ws.close(); + await ws.closed; + await tick(50); +}; /* ---- http ------------------------------------------------------------------ */ @@ -149,12 +157,12 @@ test('static files, SPA fallback, config, healthz', async () => { assert.equal(r.status, 200); assert.match(r.headers.get('content-type'), /text\/html/); assert.equal(r.headers.get('cache-control'), 'no-cache'); - r = await fetch(`${h.base}/dist/main.js`); + r = await fetch(`${h.base}/discord.js`); assert.match(r.headers.get('content-type'), /javascript/); assert.match(r.headers.get('cache-control'), /max-age/); - r = await fetch(`${h.base}/.proxy/dist/main.js`); + r = await fetch(`${h.base}/.proxy/discord.js`); assert.equal(r.status, 200); - r = await fetch(`${h.base}/some/route`); + r = await fetch(`${h.base}/title/tv/1399`); assert.equal(r.status, 200); assert.match(await r.text(), /x/); r = await fetch(`${h.base}/missing.js`); @@ -163,8 +171,13 @@ test('static files, SPA fallback, config, healthz', async () => { assert.notEqual(await r.text(), fs.readFileSync('/etc/passwd', 'utf8')); r = await fetch(`${h.base}/api/config`); assert.deepEqual(await r.json(), { applicationId: 'app1', dev: false }); + r = await fetch(`${h.base}/api/nope`); + assert.equal(r.status, 404); r = await fetch(`${h.base}/healthz`); assert.deepEqual(await r.json(), { ok: true }); + // no dev proxy unless cfg.dev: /tv/v1 is just an SPA route + r = await fetch(`${h.base}/tv/v1/streams`); + assert.match(await r.text(), /<title>x/); } finally { await h.stop(); } @@ -175,11 +188,10 @@ test('POST /api/token exchanges the code with Discord', async () => { try { let r = await fetch(`${h.base}/api/token`, { method: 'POST', body: JSON.stringify({ code: 'goodcode' }) }); assert.equal(r.status, 200); - assert.deepEqual(await r.json(), { access_token: 'good' }); + assert.deepEqual(await r.json(), { access_token: 'alice' }); const [url, init] = h.discordFetch.calls[0]; assert.equal(url, 'https://discord.com/api/oauth2/token'); - const p = new URLSearchParams(init.body); - assert.equal(p.get('client_id'), 'app1'); + assert.equal(new URLSearchParams(init.body).get('client_id'), 'app1'); r = await fetch(`${h.base}/api/token`, { method: 'POST', body: JSON.stringify({ code: 'bad' }) }); assert.equal(r.status, 502); r = await fetch(`${h.base}/api/token`, { method: 'POST', body: '{}' }); @@ -193,186 +205,311 @@ test('POST /api/token exchanges the code with Discord', async () => { } }); -/* ---- websocket ------------------------------------------------------------- */ - -test('hello: bad token → error + close; not in voice → error + close', async () => { +test('avatar endpoint proxies known users from the CDN and caches', async () => { const h = await start(); try { - const a = h.open(); - await a.opened; - a.json({ t: 'hello', token: 'nope', channelId: '42' }); - assert.equal((await a.next((m) => m.t === 'error')).message, 'authentication failed'); - assert.equal(await a.closed, 4001); - - const b = h.open(); - await b.opened; - b.json({ t: 'hello', token: 'good', channelId: '99' }); - assert.match((await b.next((m) => m.t === 'error')).message, /voice/); - assert.equal(await b.closed, 4001); - - // dev hello is refused unless cfg.dev - const c = h.open(); - await c.opened; - c.json({ t: 'hello', dev: true, userId: '111', channelId: '42' }); - await c.next((m) => m.t === 'error'); - assert.equal(await c.closed, 4001); - } finally { - await h.stop(); - } -}); - -test('hello success joins the room; users/@me is cached; leave on close', async () => { - const h = await start(); - const room = h.rooms.create({ id: '42' }); - try { - const a = h.open(); - await a.opened; - a.json({ t: 'hello', token: 'good', channelId: '42' }); - const w = await a.next((m) => m.t === 'welcome'); - assert.deepEqual(w.user, { id: '111', username: 'alice' }); - assert.equal(w.state.media.title, 'Fight Club'); - assert.deepEqual(room.calls, [['join', '111']]); - - // second socket for the same user: no second join, cached /users/@me - const a2 = h.open(); - await a2.opened; - a2.json({ t: 'hello', token: 'good', channelId: '42' }); - await a2.next((m) => m.t === 'welcome'); - assert.equal(h.discordFetch.calls.filter(([u]) => u.endsWith('/users/@me')).length, 1); - assert.equal(room.calls.length, 1); - + let r = await fetch(`${h.base}/api/avatar/111`); + assert.equal(r.status, 404, 'unknown until the user said hello'); + const a = await h.joinAs('alice'); + const b = await h.joinAs('bob'); + assert.equal(a.welcome.you.avatar, '/api/avatar/111'); + r = await fetch(`${h.base}/api/avatar/111`); + assert.equal(r.status, 200); + assert.equal(r.headers.get('content-type'), 'image/png'); + assert.deepEqual(Buffer.from(await r.arrayBuffer()), PNG); + await fetch(`${h.base}/api/avatar/111`); + const cdn = h.discordFetch.calls.filter(([u]) => u.startsWith('https://cdn.discordapp.com/')).map(([u]) => u); + assert.deepEqual(cdn, ['https://cdn.discordapp.com/avatars/111/abc123.png?size=64'], 'second request served from cache'); + // no avatar hash → default embed avatar + r = await fetch(`${h.base}/api/avatar/222`); + assert.equal(r.status, 200); + assert.match(h.discordFetch.calls.at(-1)[0], /^https:\/\/cdn\.discordapp\.com\/embed\/avatars\/\d\.png$/); + r = await fetch(`${h.base}/api/avatar/abc`); + assert.equal(r.status, 404); a.close(); - await tick(100); - assert.equal(room.calls.length, 1, 'still one socket open for the user'); - a2.close(); - await tick(100); - assert.deepEqual(room.calls.at(-1), ['leave', '111']); + b.close(); } finally { await h.stop(); } }); -test('ping → pong with server time', async () => { +/* ---- hello / membership ---------------------------------------------------- */ + +test('hello: bad token, missing instance, not a member, dev refused → error + 4001', async () => { const h = await start(); + try { + const cases = [ + [{ t: 'hello', token: 'nope', instanceId: 'i-1' }, /authentication failed/], + [{ t: 'hello', token: 'alice' }, /instanceId/], + [{ t: 'hello', token: 'mallory', instanceId: 'i-1' }, /not in this activity/], + [{ t: 'hello', token: 'alice', instanceId: 'i-unknown' }, /not in this activity/], + [{ t: 'hello', dev: true, userId: '111', instanceId: 'i-1' }, /dev mode is off/], + ]; + for (const [hello, re] of cases) { + const ws = h.open(); + await ws.opened; + ws.json(hello); + assert.match((await ws.next('error')).message, re); + assert.equal(await ws.closed, 4001); + } + } finally { + await h.stop(); + } +}); + +test('membership: checked with the bot token, cached 10s, one refetch on a miss', async () => { + const instances = { 'i-1': new Set(['111']) }; + const h = await start({ instances }); + const inst = /activity-instances/; + try { + const a = await h.joinAs('alice'); + assert.equal(h.discordFetch.count(inst), 1); + const a2 = await h.joinAs('alice'); + assert.equal(h.discordFetch.count(inst), 1, 'cached'); + assert.equal(h.discordFetch.count(/users\/@me/), 1, 'users/@me cached'); + + // bob joined the instance after the cache was filled → miss → one refetch → ok + instances['i-1'].add('222'); + const b = await h.joinAs('bob'); + assert.equal(h.discordFetch.count(inst), 2); + assert.equal(b.welcome.you.id, '222'); + + // mallory: cached miss → refetch → still missing → rejected (exactly one refetch) + const m = h.open(); + await m.opened; + m.json({ t: 'hello', token: 'mallory', instanceId: 'i-1' }); + await m.next('error'); + assert.equal(h.discordFetch.count(inst), 3); + + // cache expires after 10s + h.clock.t += 10_001; + instances['i-1'].delete('111'); + const a3 = h.open(); + await a3.opened; + a3.json({ t: 'hello', token: 'alice', instanceId: 'i-1' }); + assert.match((await a3.next('error')).message, /not in this activity/); + assert.equal(h.discordFetch.count(inst), 4, 'fresh fetch that misses is not refetched'); + + // Discord failure → error, not a crash + instances['i-2'] = 'boom'; + const e = h.open(); + await e.opened; + e.json({ t: 'hello', token: 'alice', instanceId: 'i-2' }); + assert.match((await e.next('error')).message, /membership check failed/); + for (const ws of [a, a2, b]) ws.close(); + } finally { + await h.stop(); + } +}); + +/* ---- hubs ------------------------------------------------------------------ */ + +test('first member is host; welcome lists members; joins and leaves broadcast members', async () => { + const h = await start(); + try { + const a = await h.joinAs('alice'); + assert.equal(a.welcome.host, '111'); + assert.deepEqual(a.welcome.you, { id: '111', username: 'Alice', avatar: '/api/avatar/111' }); + assert.equal(a.welcome.route, null); + assert.equal(a.welcome.play, null); + assert.equal(typeof a.welcome.now, 'number'); + + const b = await h.joinAs('bob'); + assert.equal(b.welcome.host, '111'); + assert.deepEqual(b.welcome.members.map((m) => m.id), ['111', '222']); + assert.deepEqual((await a.next('members')).members.map((m) => m.id), ['111', '222']); + + // a second socket for bob counts once + const b2 = await h.joinAs('bob'); + assert.equal(b2.welcome.members.length, 2); + await a.none('members'); + await closeAndWait(b2); + await a.none('members'); + await closeAndWait(b); + assert.deepEqual((await a.next('members')).members.map((m) => m.id), ['111']); + await a.none('host'); + } finally { + await h.stop(); + } +}); + +test('host handover to the earliest remaining member, and reclaim within 10 min', async () => { + const h = await start(); + try { + const a = await h.joinAs('alice'); + const b = await h.joinAs('bob'); + const c = await h.joinAs('carol'); + await closeAndWait(a); + assert.equal((await b.next('host')).host, '222'); + assert.equal((await c.next('host')).host, '222'); + assert.deepEqual((await c.next((m) => m.t === 'members' && m.members.length === 2)).members.map((m) => m.id), ['222', '333']); + + // alice is back within 10 min → host again + h.clock.t += 5 * 60 * 1000; + const a2 = await h.joinAs('alice'); + assert.equal(a2.welcome.host, '111'); + assert.equal((await b.next('host')).host, '111'); + assert.equal((await c.next('host')).host, '111'); + + // gone longer than 10 min → no reclaim + await closeAndWait(a2); + assert.equal((await b.next('host')).host, '222'); + h.clock.t += 10 * 60 * 1000 + 1; + const a3 = await h.joinAs('alice'); + assert.equal(a3.welcome.host, '222'); + await b.none('host'); + } finally { + await h.stop(); + } +}); + +test('an emptied hub keeps route/play for 10 min, then starts fresh', async () => { + const h = await start({ dev: true }); + try { + const a = await h.devJoin('1'); + a.json({ t: 'route', path: '/title/movie/550' }); + await tick(50); + await closeAndWait(a); + + h.clock.t += 9 * 60 * 1000; + const b = await h.devJoin('2'); + assert.equal(b.welcome.host, '2', 'nobody left → the joiner is host'); + assert.equal(b.welcome.route, '/title/movie/550'); + const a2 = await h.devJoin('1'); + assert.equal(a2.welcome.host, '1', 'original host reclaims'); + assert.equal((await b.next('host')).host, '1'); + await closeAndWait(a2); + await closeAndWait(b); + + h.clock.t += 10 * 60 * 1000 + 1; + const c = await h.devJoin('3'); + assert.equal(c.welcome.host, '3'); + assert.equal(c.welcome.route, null); + const a3 = await h.devJoin('1'); + assert.equal(a3.welcome.host, '3', 'fresh hub: no reclaim'); + } finally { + await h.stop(); + } +}); + +/* ---- relay ----------------------------------------------------------------- */ + +test('route/play relay from the host only, play stamped with server time; late joiner gets both', async () => { + const h = await start(); + try { + const a = await h.joinAs('alice'); + const b = await h.joinAs('bob'); + a.drain(); + + a.json({ t: 'route', path: '/watch/movie/550' }); + assert.deepEqual(await b.next('route'), { t: 'route', path: '/watch/movie/550' }); + await a.none('route'); + + h.clock.t = 2_000_000; + const snapshot = { path: '/watch/movie/550', media: { type: 'movie', id: 550 }, stream: { id: 's1', playback: { kind: 'hls', url: '/v1/p/x' } }, playing: true, position: 12.5, duration: 8000, at: 5 }; + a.json({ t: 'play', snapshot }); + const p = await b.next('play'); + assert.deepEqual(p.snapshot, { ...snapshot, at: 2_000_000 }); + await a.none('play'); + + // non-host messages are ignored + b.json({ t: 'route', path: '/evil' }); + b.json({ t: 'play', snapshot: { ...snapshot, position: 0 } }); + await a.none('route'); + await a.none('play'); + // invalid route from the host is ignored + a.json({ t: 'route', path: 'javascript:alert(1)' }); + await b.none('route'); + + const c = await h.joinAs('carol'); + assert.equal(c.welcome.route, '/watch/movie/550'); + assert.deepEqual(c.welcome.play, { ...snapshot, at: 2_000_000 }); + + // navigating elsewhere drops the stale snapshot for late joiners + a.json({ t: 'route', path: '/' }); + await b.next('route'); + await closeAndWait(c); + const c2 = await h.joinAs('carol'); + assert.equal(c2.welcome.route, '/'); + assert.equal(c2.welcome.play, null); + + // explicit play:null is relayed + a.json({ t: 'play', snapshot: null }); + assert.equal((await b.next('play')).snapshot, null); + + // after handover the new host relays + await closeAndWait(a); + await c2.next('host'); + b.json({ t: 'route', path: '/movies' }); + assert.equal((await c2.next('route')).path, '/movies'); + } finally { + await h.stop(); + } +}); + +test('large snapshots up to ~256KB are accepted', async () => { + const h = await start({ dev: true }); + try { + const a = await h.devJoin('1'); + const b = await h.devJoin('2'); + a.json({ t: 'play', snapshot: { path: '/watch/movie/1', stream: { blob: 'x'.repeat(200 * 1024) }, playing: false, position: 0 } }); + assert.equal((await b.next('play')).snapshot.stream.blob.length, 200 * 1024); + } finally { + await h.stop(); + } +}); + +test('ping → pong with server time; messages are rate limited per socket', async () => { + const h = await start({ dev: true }); try { const a = h.open(); await a.opened; a.json({ t: 'ping', at: 123 }); - const p = await a.next((m) => m.t === 'pong'); - assert.equal(p.at, 123); - assert.ok(Math.abs(p.now - Date.now()) < 1000); - } finally { - await h.stop(); - } -}); + assert.deepEqual(await a.next('pong'), { t: 'pong', at: 123, now: 1_000_000 }); -test('cmd and report are forwarded; change broadcasts are coalesced', async () => { - const h = await start(); - const room = h.rooms.create({ id: '42' }); - try { - const a = h.open(); - const b = h.open(); - await Promise.all([a.opened, b.opened]); - a.json({ t: 'hello', token: 'good', channelId: '42' }); - b.json({ t: 'hello', token: 'bob', channelId: '42' }); - await a.next((m) => m.t === 'welcome'); - await b.next((m) => m.t === 'welcome'); + const host = await h.devJoin('1'); + const v = await h.devJoin('2'); + for (let i = 0; i < 60; i++) host.json({ t: 'route', path: `/p${i}` }); + await host.next((m) => m.t === 'error' && /slow/.test(m.message)); await tick(100); - // drain anything queued so far - while (await a.next((m) => m.t === 'state', 120).catch(() => null)); - while (await b.next((m) => m.t === 'state', 120).catch(() => null)); - - a.json({ t: 'cmd', op: 'seek', args: { t: 90 } }); - a.json({ t: 'cmd', op: 'play', args: {} }); - a.json({ t: 'report', duration: 5000 }); - const s = await b.next((m) => m.t === 'state'); - assert.equal(s.state.rev, 2, 'two changes → one broadcast with the latest state'); - await assert.rejects(b.next((m) => m.t === 'state', 200)); - assert.deepEqual( - room.calls.filter((c) => c[0] !== 'join'), - [ - ['command', 'seek', { t: 90 }, '111'], - ['command', 'play', {}, '111'], - ['report', { duration: 5000 }, '111'], - ], - ); + let n = 0; + while (await v.next('route', 50).catch(() => null)) n++; + assert.ok(n >= 25 && n <= 40, `got ${n} routes through`); } finally { await h.stop(); } }); -test('cmds are rate limited per socket', async () => { - const h = await start(); - const room = h.rooms.create({ id: '42' }); +test('dev hello with cfg.dev; unknown ws path is refused', async () => { + const h = await start({ dev: true }); try { - const a = h.open(); - await a.opened; - a.json({ t: 'hello', token: 'good', channelId: '42' }); - await a.next((m) => m.t === 'welcome'); - for (let i = 0; i < 25; i++) a.json({ t: 'cmd', op: 'toggle' }); - await a.next((m) => m.t === 'error' && /slow/.test(m.message)); - const n = room.calls.filter((c) => c[0] === 'command').length; - assert.ok(n >= 10 && n < 15, `got ${n} commands through`); - } finally { - await h.stop(); - } -}); - -for (const events of [true, false]) { - test(`waiting socket attaches when the room appears (${events ? "rooms 'created' event" : 'poll'})`, async () => { - const h = await start({ rooms: fakeRooms({ events }) }); - try { - const a = h.open(); - await a.opened; - a.json({ t: 'hello', token: 'good', channelId: '42' }); - const w = await a.next((m) => m.t === 'welcome'); - assert.equal(w.state.media, null); - const room = h.rooms.create({ id: '42' }); - const s = await a.next((m) => m.t === 'state', 4000); - assert.equal(s.state.media.title, 'Fight Club'); - assert.deepEqual(room.calls, [['join', '111']]); - a.json({ t: 'cmd', op: 'play' }); - await a.next((m) => m.t === 'state'); - assert.equal(room.calls.at(-1)[1], 'play'); - } finally { - await h.stop(); - } - }); -} - -test("room 'closed' → empty state, then a new room re-attaches", async () => { - const h = await start({ rooms: fakeRooms({ events: true }) }); - const room = h.rooms.create({ id: '42' }); - try { - const a = h.open(); - await a.opened; - a.json({ t: 'hello', token: 'good', channelId: '42' }); - await a.next((m) => m.t === 'welcome'); - room.emit('closed'); - h.rooms.delete('42'); - const s = await a.next((m) => m.t === 'state' && m.state.media === null); - assert.equal(s.state.stream, null); - room.emit('change'); // a dead room must not broadcast anymore - await assert.rejects(a.next((m) => m.t === 'state', 200)); - const room2 = h.rooms.create({ id: '42' }); - await a.next((m) => m.t === 'state' && m.state.media); - assert.deepEqual(room2.calls, [['join', '111']]); - } finally { - await h.stop(); - } -}); - -test('dev hello works with cfg.dev; unknown ws path is refused', async () => { - const h = await start({ dev: true, voice: { '7': new Set(['5']) } }); - try { - const a = h.open(); - await a.opened; - a.json({ t: 'hello', dev: true, userId: '5', channelId: '7' }); - const w = await a.next((m) => m.t === 'welcome'); - assert.equal(w.user.id, '5'); + const a = await h.devJoin('5', 'x'); + assert.deepEqual(a.welcome.you, { id: '5', username: 'u5', avatar: null }); + assert.equal(a.welcome.host, '5'); + const r = await fetch(`${h.base}/api/config`); + assert.equal((await r.json()).dev, true); const b = h.open('/nope'); await assert.rejects(b.opened); } finally { await h.stop(); } }); + +test('dev mode reverse-proxies /tv/v1 to devApiUrl', async () => { + const http = require('http'); + const upstream = http.createServer((req, res) => { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ url: req.url, method: req.method })); + }); + await new Promise((r) => upstream.listen(0, '127.0.0.1', r)); + const h = await start({ dev: true, devApiUrl: `http://127.0.0.1:${upstream.address().port}` }); + try { + let r = await fetch(`${h.base}/tv/v1/streams?type=movie&id=550`); + assert.deepEqual(await r.json(), { url: '/v1/streams?type=movie&id=550', method: 'GET' }); + r = await fetch(`${h.base}/tv`); + assert.match(await r.text(), /<title>x/, 'the Series route is not proxied'); + } finally { + await h.stop(); + upstream.close(); + } +}); diff --git a/test/sync.test.js b/test/sync.test.js deleted file mode 100644 index ce41e3f..0000000 --- a/test/sync.test.js +++ /dev/null @@ -1,73 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('path'); -const { pathToFileURL } = require('url'); - -const load = () => import(pathToFileURL(path.join(__dirname, '..', 'activity', 'js', 'sync.js')).href); - -test('targetTime extrapolates while playing, clamps to duration', async () => { - const S = await load(); - const st = { position: 100, playing: true, updatedAt: 1_000_000, duration: 0 }; - assert.equal(S.targetTime(st, 0, 1_005_000), 105); - // local clock 2s behind the server → offset +2000 - assert.equal(S.targetTime(st, 2000, 1_003_000), 105); - assert.equal(S.targetTime({ ...st, playing: false }, 0, 1_005_000), 100); - assert.equal(S.targetTime({ ...st, duration: 103 }, 0, 1_005_000), 103); - // updatedAt in the future (clock skew) never rewinds - assert.equal(S.targetTime(st, 0, 999_000), 100); - assert.equal(S.targetTime(null), 0); -}); - -test('driftAction thresholds', async () => { - const S = await load(); - assert.equal(S.driftAction(10, 10).action, 'none'); - assert.equal(S.driftAction(10.2, 10).action, 'none'); - let a = S.driftAction(10.5, 10); - assert.equal(a.action, 'rate'); - assert.equal(a.rate, S.RATE_SLOW); - a = S.driftAction(9, 10); - assert.equal(a.action, 'rate'); - assert.equal(a.rate, S.RATE_FAST); - assert.equal(S.driftAction(12, 10).action, 'seek'); - assert.equal(S.driftAction(7, 10).action, 'seek'); - // cooldown: no seek, nudge instead - assert.equal(S.driftAction(7, 10, { canSeek: false }).action, 'rate'); - // paused: seek once noticeably off, never rate - assert.equal(S.driftAction(10.5, 10, { playing: false }).action, 'seek'); - assert.equal(S.driftAction(10.1, 10, { playing: false }).action, 'none'); - assert.equal(S.driftAction(10.5, 10, { playing: false, canSeek: false }).action, 'none'); -}); - -test('isJump detects explicit seeks but not ticks', async () => { - const S = await load(); - const now = 2_000_000; - const a = { position: 50, playing: true, updatedAt: now - 10_000 }; - const tickState = { position: 60, playing: true, updatedAt: now }; - assert.equal(S.isJump(a, tickState, 0, now), false); - assert.equal(S.isJump(a, { position: 200, playing: true, updatedAt: now }, 0, now), true); - assert.equal(S.isJump(a, { position: 60, playing: false, updatedAt: now }, 0, now), false); - assert.equal(S.isJump(null, a, 0, now), true); -}); - -test('clock offset: sample math and rolling median', async () => { - const S = await load(); - // sent at 1000 (local), server stamped 5100, received at 1200 → rtt 200, offset 5100 - 1100 - assert.deepEqual(S.offsetSample(1000, 5100, 1200), { offset: 4000, rtt: 200 }); - assert.equal(S.median([3, 1, 2]), 2); - assert.equal(S.median([4, 1, 3, 2]), 2.5); - assert.equal(S.median([]), 0); - const c = S.createClock(5); - assert.equal(c.offset(), 0); - for (const o of [100, 105, 9999, 98, 102, 101]) c.add({ offset: o }); - assert.equal(c.count, 5); - assert.equal(c.offset(), 102); // outlier ignored, oldest (100) dropped - c.add(NaN); - assert.equal(c.count, 5); -}); - -test('formatTime', async () => { - const S = await load(); - assert.equal(S.formatTime(0), '0:00'); - assert.equal(S.formatTime(65.9), '1:05'); - assert.equal(S.formatTime(3725), '1:02:05'); -});