From bdc582a4383596681f2d0c6cabd229f9202a8a24 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Tue, 27 Oct 2026 08:54:57 -0500 Subject: [PATCH] tv-discord: Discord bot + Activity for watching bug.tv together --- .gitignore | 5 + activity/css/activity.css | 146 ++++++ activity/img/bug.svg | 1 + activity/index.html | 64 +++ activity/js/main.js | 635 +++++++++++++++++++++++++ activity/js/sync.js | 88 ++++ activity/js/urls.js | 52 +++ activity/package.json | 1 + config.example.json | 9 + docs/protocol.md | 104 +++++ flake.lock | 48 ++ flake.nix | 102 ++++ nix/activity.nix | 67 +++ nix/module.nix | 178 +++++++ nix/package.nix | 69 +++ package-lock.json | 881 +++++++++++++++++++++++++++++++++++ package.json | 21 + scripts/register-commands.js | 31 ++ scripts/vendor-bugtv.sh | 28 ++ src/bot/autocomplete.js | 26 ++ src/bot/commands.js | 114 +++++ src/bot/controls.js | 172 +++++++ src/bot/index.js | 102 ++++ src/bot/render.js | 271 +++++++++++ src/bot/updater.js | 110 +++++ src/bugtv.js | 176 +++++++ src/config.js | 43 ++ src/index.js | 25 + src/room.js | 698 +++++++++++++++++++++++++++ src/server.js | 508 ++++++++++++++++++++ test/bot.test.js | 99 ++++ test/helpers.js | 91 ++++ test/render.test.js | 152 ++++++ test/room.test.js | 273 +++++++++++ test/server.test.js | 378 +++++++++++++++ test/sync.test.js | 73 +++ 36 files changed, 5841 insertions(+) create mode 100644 .gitignore create mode 100644 activity/css/activity.css create mode 100644 activity/img/bug.svg create mode 100644 activity/index.html create mode 100644 activity/js/main.js create mode 100644 activity/js/sync.js create mode 100644 activity/js/urls.js create mode 100644 activity/package.json create mode 100644 config.example.json create mode 100644 docs/protocol.md create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 nix/activity.nix create mode 100644 nix/module.nix create mode 100644 nix/package.nix create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 scripts/register-commands.js create mode 100755 scripts/vendor-bugtv.sh create mode 100644 src/bot/autocomplete.js create mode 100644 src/bot/commands.js create mode 100644 src/bot/controls.js create mode 100644 src/bot/index.js create mode 100644 src/bot/render.js create mode 100644 src/bot/updater.js create mode 100644 src/bugtv.js create mode 100644 src/config.js create mode 100644 src/index.js create mode 100644 src/room.js create mode 100644 src/server.js create mode 100644 test/bot.test.js create mode 100644 test/helpers.js create mode 100644 test/render.test.js create mode 100644 test/room.test.js create mode 100644 test/server.test.js create mode 100644 test/sync.test.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..04ec903 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +result* +activity/dist/ +config.json +activity/vendor/bugtv/ diff --git a/activity/css/activity.css b/activity/css/activity.css new file mode 100644 index 0000000..790dc80 --- /dev/null +++ b/activity/css/activity.css @@ -0,0 +1,146 @@ +: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 new file mode 100644 index 0000000..f8986dd --- /dev/null +++ b/activity/img/bug.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/activity/index.html b/activity/index.html new file mode 100644 index 0000000..4743a62 --- /dev/null +++ b/activity/index.html @@ -0,0 +1,64 @@ + + + + + + bug.tv + + + + + +
+ + + +
+ +

bug.tv

+

Connecting…

+
+ +
+ +

+

Finding sources…

+
+ + + + + +
+
+
+
+
+
+
+ + + +
+
+
+ +
+
+ +
0:00 / 0:00
+
+
+
+
+ +
+
+ + diff --git a/activity/js/main.js b/activity/js/main.js new file mode 100644 index 0000000..ac2d294 --- /dev/null +++ b/activity/js/main.js @@ -0,0 +1,635 @@ +/* + 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 new file mode 100644 index 0000000..2c7dace --- /dev/null +++ b/activity/js/sync.js @@ -0,0 +1,88 @@ +/* + 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 new file mode 100644 index 0000000..23e7f71 --- /dev/null +++ b/activity/js/urls.js @@ -0,0 +1,52 @@ +/* + 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/package.json b/activity/package.json new file mode 100644 index 0000000..5ffd980 --- /dev/null +++ b/activity/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/config.example.json b/config.example.json new file mode 100644 index 0000000..3c41086 --- /dev/null +++ b/config.example.json @@ -0,0 +1,9 @@ +{ + "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" +} diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..4f973fe --- /dev/null +++ b/docs/protocol.md @@ -0,0 +1,104 @@ +# tv-discord: module and protocol contract + +Every workstream codes against this file. If you need to deviate, keep it backwards compatible and record it under "Deviations" at the bottom. + +## 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). + +## Config (`src/config.js`, already written) +`loadConfig()` reads JSON from `$BUG_TV_DISCORD_CONFIG` (default `./config.json`): +``` +{ 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) } +``` +`*File` values are read and trimmed into `token`, `clientSecret` and `tmdbKey`. + +## 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 +``` + +## Rooms (`src/room.js`, workstream A) +`createRooms(cfg)` → `{ get(id), create({ id, guildId, textChannelId }), delete(id), all() }`. `id` is the **voice channel id**. + +A room is an EventEmitter: +- `room.state` holds the full server state: + ``` + { id, guildId, textChannelId, messageId, + media: { type, tmdb, title, year, poster, backdrop, overview, season, episode, episodeTitle, still, seasons: [{n, count}] } | null, + sources: [Stream] (ranked), scraping: bool, providers: { done, total }, + sourceId, failed: [ids], notice: string|null (shown in the embed, e.g. "vidrock failed, trying castle"), + subtitle: -1|index, quality: -1|levelIndex, levels: [{ index, height, bitrate }], + playing: bool, position: seconds, updatedAt: ms (server clock), duration: seconds|0, buffering: bool, + viewers: [userId], leader: userId|null, rev: int } + ``` +- `room.load({ type, tmdb, season?, episode? })` fetches TMDB metadata, starts the bug-tv SSE scrape, ranks sources and auto-picks one using the web player's rule (≥1080p hls/file at once, else 1.5s after the first playable, else on done). It resets the playback clock. +- `room.command(op, args, userId)` handles these ops: + `play`, `pause`, `toggle`, `seek {t}` (absolute), `seekBy {d}`, `source {id}`, `subtitle {index}`, `quality {index}`, `episode {season, episode}`, `next`, `prev`, `stop`. +- `room.report(data, userId)` takes client reports. Only the leader's `duration`, `levels`, `buffering`, `ended` and `error {fatal, message}` are used, plus a `position` heartbeat every 5s that corrects server drift while playing. A fatal error moves to the next unfailed source and sets `notice`. +- `room.join(userId)` / `room.leave(userId)` keep `viewers` and leader election (first joiner; re-elected on leave). +- `room.publicState(now = Date.now())` returns the state sent to Activity clients: `{ media, stream (selected Stream object or null), subtitle, quality, playing, position, updatedAt, now, duration, viewers, leader, rev, notice }`. +- Events: `'change'` (`state`, `reason`) on every mutation, so the bot re-renders (throttled) and the server broadcasts. `'closed'` fires on stop or idle close. +- Clock: the current time is `position + (playing ? (now - updatedAt) / 1000 : 0)`, clamped to `[0, duration || ∞]`. +- Prefetch: at ≥80% of `duration` it calls `/v1/prefetch` for the next episode once. On the leader's `ended` it moves to the next episode (TV) or pauses at the end (movie). +- Idle: when the bot reports the voice channel empty (`rooms.get(id).setVoiceCount(n)`), the room closes after 2 minutes at 0. + +## Bot (`src/bot/*`, workstream A) +- `src/bot/index.js` exports `createBot(cfg, rooms)`. It logs in with intents `Guilds` and `GuildVoiceStates`, registers commands (guild-scoped for `cfg.guildIds`, otherwise global), and handles interactions. It returns `{ client, isInVoice(channelId, userId), voiceMembers(channelId) }`. +- Commands: `/watch query: season: episode:`, `/np`, `/stop`. +- Component custom ids are `tv::[:]`, one action per id: + - Buttons: `tv:toggle`, `tv:seekBy:<±sec>`, `tv:seekModal`, `tv:prev`, `tv:next`, `tv:launch`, `tv:stop`, `tv:episodes`, `tv:sources`. + - Selects: `tv:src` (value = stream id or `page:`), `tv:sub`, `tv:q`, `tv:season`, `tv:ep`. + - Modal: `tv:seekForm` with text input `t` (`1:23:45`, `83m`, `45%`, `90`). +- `tv:launch` answers with interaction response type 12 (`LAUNCH_ACTIVITY`, raw REST `POST /interactions/{id}/{token}/callback` with `{type:12}`) when the clicker is in the room's VC. Otherwise it gives an ephemeral hint. +- The control message is rendered by `src/bot/render.js` `render(room.state) → { embeds, components }` and edited on `'change'`, at most once every 3s plus immediately on source, episode, play or pause changes. + +## HTTP + WS server (`src/server.js`, workstream B) +- Static Activity files come from `cfg.activityDir` (`index.html`, `css/`, `js/`, `dist/`, `vendor/`), with SPA fallback to `index.html`. +- `POST /api/token {code}` → `{ access_token }`. It exchanges the code with Discord (`POST https://discord.com/api/oauth2/token`, client credentials, `grant_type=authorization_code`). No redirect_uri is needed for Activities. +- `GET /ws` is a WebSocket using JSON messages: + - **client → server** + - `{ t: "hello", token, channelId }`: the server checks the token with `GET /users/@me`, then `isInVoice(channelId, user.id)`, then `room.join`. + - `{ t: "cmd", op, args }`: forwarded to `room.command`. + - `{ t: "report", ...data }`: forwarded to `room.report`. + - `{ t: "ping", at }`: the server replies with `pong`. + - **server → client** + - `{ t: "welcome", user: {id, username}, state: publicState }` + - `{ t: "state", state: publicState }`: broadcast on every room `'change'`. + - `{ t: "pong", at, now }`: lets the client estimate its clock offset. + - `{ t: "error", message }`, followed by a close for auth failures. + - When no room exists for the channel yet, the welcome state is empty (`media: null`) and the Activity shows "Use /watch in chat to pick something". A later `room` creation for that channel must attach to waiting sockets. + +## Activity (`activity/`, workstream B) +- `new DiscordSDK(applicationId)` (the id is injected at serve time via `/api/config` → `{ applicationId }`), then `ready()`, `patchUrlMappings([{prefix:'/tv', target:'api-tv.bug.tools'}, {prefix:'/img', target:'image.tmdb.org'}])`, `authorize({client_id, response_type:'code', prompt:'none', scope:['identify']})`, `POST /api/token`, `authenticate`, then WS `hello` with `channelId: sdk.channelId`. +- Playback goes through bug-tv's `player.js` (copied in at build time to `activity/vendor/bugtv/js/ui/player.js`, with `activity/vendor/bugtv/js/config.js` = the shim exporting `resolveUrl(u)` → relative `/v1/...` becomes `/api/v1/...`). It **always plays the proxied URL**: `playback.fallback` when present, otherwise `playback.url`. +- Sync: the target time is computed from publicState plus the server clock offset. Drift over 1.5s means a hard seek; smaller drift sets `playbackRate` to 0.95–1.05 until within 0.3s. +- The leader sends a `report` with `duration`, `levels` (from hls), `buffering`, `ended`, `error`, and a `position` heartbeat every 5s. + +## Deviations + +### Workstream A (rooms, bug-tv client, bot) +- `createRooms(cfg, { bugtv, now, setTimeout, clearTimeout })`: the optional second arg injects the bug-tv client and the clock (for tests). The registry is an EventEmitter that emits `'created'(room)` and `'deleted'(room)`. `create()` returns the existing room for that id and updates its `textChannelId`. `rooms.lastProvider` is an in-memory `"type:tmdb" → provider` map that feeds the web player's +100 ranking bonus. It is set when the leader reports a duration for the current source. +- `room.command()` is async and never throws. It resolves `{ ok: true }` or `{ ok: false, error }`. `room.load()` resolves once TMDB metadata is in, while the scrape keeps running in the background. `room.clock(now?)`, `room.current()` (the selected Stream), `room.episodeRef(±1)` → `{season, episode}|null`, `room.close(reason)` and `room.voiceCount` are also exposed. +- `publicState()` adds `buffering`. `media` adds `logo`. Image URLs are absolute `https://image.tmdb.org/t/p/...` (the Activity's `/img` mapping rewrites them). +- Autoplay: an auto-picked source starts playing only if someone has the Activity open. Otherwise the room stays paused and starts playing on the first `join`. When the last viewer leaves, a playing room pauses and resumes on the next `join`. An explicit `play` with no viewers still plays. +- `report()` also accepts an optional `sourceId`. A report whose `sourceId` differs from the current source is ignored, so a late error from the old source doesn't fail over twice. The `position` heartbeat corrects the clock only when the drift is over 1s, and is ignored for 3s after any clock-changing command so a stale heartbeat can't undo a seek. Reports from anyone except the leader are ignored entirely (return `false`). +- `'change'` reasons: `load meta providers sources scrape-done source play pause seek subtitle quality duration levels buffering drift ended notice join leave leader stop idle`. Failover emits `source`. The bot edits immediately on `load source play pause stop idle ended`, and otherwise at most every 3s. It also refreshes every 15s while playing so the progress bar moves. +- Episodes mode shows 4 rows (two button rows, Season select, Episode select) and hides Subtitles/Quality. The Episode select pages with `page:` values ("Earlier/Later episodes…"). Movies have no Episodes button, and Prev/Next are disabled for them. +- The seek modal also accepts `90s`, `1h20m` and relative `+5m`/`-30` (→ `seekBy`). +- `/watch` with free text (no autocomplete pick) uses the first TMDB `search/multi` result. A new `/watch` or `/np` posts a new control message and deletes the old one. Control-message edits go through `channel.messages.edit`. If that fails, they fall back to the most recent interaction webhook (valid for about 15 minutes). +- `tv:launch` uses discord.js 14.27's `interaction.launchActivity()` (callback type 12), with the raw REST `{type:12}` callback only as a fallback. +- `createBot()` also returns `ctx` (internals for tests). `src/bot/updater.js` is an extra module. `package.json`'s test script became `node --test 'test/**/*.test.js'`, because Node 24 rejects a bare directory argument. + +### Workstream B (server, Activity) +- **URL mapping prefix for bug-tv is `/tv`, not `/api`.** Discord matches the most specific prefix, so `/api → api-tv.bug.tools` would swallow our own `/api/token` and `/api/config`. Portal URL mappings: `/` → `tv-activity.bug.tools`, `/tv` → `api-tv.bug.tools`, `/img` → `image.tmdb.org`. Inside Discord, `resolveUrl('/v1/…')` returns the same-origin `/tv/v1/…`. The legacy `/.proxy/` prefix is not used (SDK 2.5's `patchUrlMappings` doesn't emit it), but the server strips a leading `/.proxy` from HTTP and WS paths anyway. The Activity calls `patchUrlMappings` with `/tv` and `/img`, which only matters for absolute URLs. TMDB images are rewritten to `/img/…` explicitly. +- Dev mode (no `frame_id`): bug-tv base = `?api=` (default `http://127.0.0.1:8789`), and `hello` is `{t:'hello', dev:true, userId, channelId, username?}` from `?channel=&user=&name=`. The server accepts it only when `cfg.dev === true` (a new optional config key, server-only). `isInVoice` is still checked. +- `createServer(cfg, rooms, { isInVoice, discordFetch, log })`: `discordFetch` defaults to global `fetch`. `GET /api/config` also returns `dev`. `GET /healthz` → `{ok:true}`. The returned server has `.wss` and `.channels` for tests. +- Room attach: the server listens for rooms' `'created'` event and also polls `rooms.get()` every 2s for channels with waiting sockets. On a room's `'closed'` it broadcasts an empty state (`media:null`) and the sockets wait for the next room. Several sockets of one user in one channel call `room.join` once and `room.leave` when the last one closes. `'change'` broadcasts are coalesced within 50ms. A `cmd` result of `{ok:false, error}` is sent back to that socket as `{t:'error', message}`. Limits: 10 cmd/s and 20 report/s per socket (excess cmds → `{t:'error', message:'slow down'}`), 16 KB max frame, and a 15s hello timeout. Auth failures close with code 4001. +- Reports carry `sourceId` (the stream the player has loaded). `buffering:true` is sent only after a 1s stall. The position heartbeat is skipped while stalled or seeking. +- Vendoring: `scripts/vendor-bugtv.sh [activity dir]` must run **before** `npm run build:activity`. It creates `activity/vendor/bugtv/{js/ui/player.js, js/config.js (shim → activity/js/urls.js), vendor/hls.min.js}`. esbuild bundles player.js and the shim into `dist/main.js`. Because the bundled `import.meta.url` no longer points at player.js, main.js preloads `window.Hls` from `/vendor/bugtv/vendor/hls.min.js` before loading an HLS stream. `activity/vendor/bugtv/` is generated, so it should be gitignored like `activity/dist/`. `activity/package.json` (`{"type":"module"}`) lets `node --test` import `activity/js/sync.js` without warnings. +- Activity UX: a single click on the video only reveals the controls, so a touch can't pause the room. Double-click, Space or k toggles; ←/→ or j/l → `seekBy ∓10`. When autoplay is refused, the Activity retries muted and shows "Unmute". If that is refused too, it shows "Click to join playback". A follower whose player fails fatally reloads once after 2s and doesn't report. diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..04d0e41 --- /dev/null +++ b/flake.lock @@ -0,0 +1,48 @@ +{ + "nodes": { + "bug-tv": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1793098252, + "narHash": "sha256-QxFuZv15nib8O8fAJ3kdoCmJ+Le6M4ku5Dqq09QHAbs=", + "ref": "refs/heads/main", + "rev": "5ab3683f448a249833a8e164e1e64446381a8c86", + "revCount": 22, + "type": "git", + "url": "https://git.bug.tools/bug/tv" + }, + "original": { + "type": "git", + "url": "https://git.bug.tools/bug/tv" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1792773339, + "narHash": "sha256-rZLrzrC6i+jnTAlvPZHogKDulY7WWDEv9hJeHieO7Zw=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "bug-tv": "bug-tv", + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..8e3015e --- /dev/null +++ b/flake.nix @@ -0,0 +1,102 @@ +{ + description = "bug.tv Discord bot + Activity for watching together in a voice channel"; + + inputs = { + nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; + bug-tv = { + url = "git+https://git.bug.tools/bug/tv"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = + { + self, + nixpkgs, + bug-tv, + ... + }: + let + inherit (nixpkgs) lib; + + systems = [ "x86_64-linux" "aarch64-linux" ]; + forAllSystems = f: lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + in + { + packages = forAllSystems (pkgs: rec { + activity = pkgs.callPackage ./nix/activity.nix { + bugTvWeb = bug-tv.packages.${pkgs.stdenv.hostPlatform.system}.web; + }; + bot = pkgs.callPackage ./nix/package.nix { inherit activity; }; + default = bot; + }); + + apps = forAllSystems (pkgs: { + default = { + type = "app"; + program = lib.getExe self.packages.${pkgs.stdenv.hostPlatform.system}.default; + meta.description = "Run the bot (reads ./config.json or $BUG_TV_DISCORD_CONFIG)"; + }; + }); + + devShells = forAllSystems (pkgs: { + default = pkgs.mkShell { packages = [ pkgs.nodejs_22 pkgs.esbuild ]; }; + }); + + formatter = forAllSystems (pkgs: pkgs.nixfmt); + + checks = forAllSystems ( + pkgs: + let + inherit (self.packages.${pkgs.stdenv.hostPlatform.system}) bot activity; + hasTests = builtins.pathExists ./test && builtins.readDir ./test != { }; + in + { + inherit bot activity; + + lint = + pkgs.runCommand "bug-tv-discord-lint" + { + nativeBuildInputs = [ pkgs.nodejs_22 pkgs.findutils ]; + } + '' + cd ${bot}/lib/bug-tv-discord + find src -name '*.js' -print0 | xargs -0 -n1 node --check + test -f activity/index.html + test -f activity/dist/main.js + touch $out + ''; + } + // lib.optionalAttrs hasTests { + # no network in the sandbox: tests must not need it + test = pkgs.buildNpmPackage { + pname = "bug-tv-discord-test"; + inherit (bot) version npmDeps npmConfigHook npmFlags; + nodejs = pkgs.nodejs_22; + src = lib.fileset.toSource { + root = ./.; + fileset = lib.fileset.unions [ + ./src + ./test + (lib.fileset.difference ./activity (lib.fileset.maybeMissing ./activity/dist)) + ./package.json + ./package-lock.json + ]; + }; + dontNpmBuild = true; + doCheck = true; + checkPhase = '' + runHook preCheck + export HOME=$TMPDIR + node --test + runHook postCheck + ''; + installPhase = "touch $out"; + }; + } + ); + + nixosModules.default = import ./nix/module.nix self; + nixosModules.bug-tv-discord = self.nixosModules.default; + }; +} diff --git a/nix/activity.nix b/nix/activity.nix new file mode 100644 index 0000000..a9c2d26 --- /dev/null +++ b/nix/activity.nix @@ -0,0 +1,67 @@ +{ + lib, + buildNpmPackage, + importNpmLock, + nodejs_22, + esbuild, + # bug-tv's static web package: provides js/ui/player.js and vendor/hls.min.js + bugTvWeb, +}: + +let + src = lib.fileset.toSource { + root = ../.; + fileset = lib.fileset.unions [ + (lib.fileset.difference ../activity ( + lib.fileset.unions [ + (lib.fileset.maybeMissing ../activity/dist) + (lib.fileset.maybeMissing ../activity/vendor/bugtv) + ] + )) + (lib.fileset.maybeMissing ../scripts) + ../package.json + ../package-lock.json + ]; + }; + + pkgJson = lib.importJSON ../package.json; +in + +buildNpmPackage { + pname = "bug-tv-discord-activity"; + inherit (pkgJson) version; + inherit src; + nodejs = nodejs_22; + + # same lockfile as the bot; @discord/embedded-app-sdk is resolved from node_modules by esbuild + npmDeps = importNpmLock { npmRoot = src; }; + npmConfigHook = importNpmLock.npmConfigHook; + npmFlags = [ "--ignore-scripts" ]; + + # npm's esbuild needs its postinstall binary download; use nixpkgs' instead + nativeBuildInputs = [ esbuild ]; + + buildPhase = '' + runHook preBuild + + # same layout as a dev checkout: activity/vendor/bugtv/{js/ui/player.js,js/config.js,vendor/hls.min.js} + bash scripts/vendor-bugtv.sh ${bugTvWeb} activity + + esbuild activity/js/main.js --bundle --format=esm --target=es2022 \ + --minify --sourcemap --outfile=activity/dist/main.js + + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + cp -r activity $out + runHook postInstall + ''; + + meta = { + description = "bug.tv Discord Activity (static files)"; + homepage = "https://git.bug.tools/bug/tv-discord"; + platforms = lib.platforms.all; + }; +} diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 0000000..d322ed4 --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,178 @@ +self: +{ + config, + lib, + pkgs, + ... +}: + +let + inherit (lib) mkOption mkEnableOption types; + + cfg = config.services.bug-tv-discord; + system = pkgs.stdenv.hostPlatform.system; + credDir = "/run/credentials/bug-tv-discord.service"; + + appConfig = lib.recursiveUpdate ( + { + inherit (cfg) host port apiUrl applicationId guildIds providers; + activityDir = "${cfg.activityPackage}"; + tokenFile = "${credDir}/token"; + clientSecretFile = "${credDir}/client-secret"; + } + // ( + if cfg.tmdbApiKeyFile != null then + { tmdbKeyFile = "${credDir}/tmdb"; } + else + { tmdbKey = cfg.tmdbApiKey; } + ) + ) cfg.extraConfig; + + configFile = pkgs.writeText "bug-tv-discord-config.json" (builtins.toJSON appConfig); + + # ordered after the local bug-tv API when it runs on the same host + bugTv = lib.optional (config.systemd.services ? bug-tv) "bug-tv.service"; +in +{ + options.services.bug-tv-discord = { + enable = mkEnableOption "the bug.tv Discord bot and Activity server"; + + package = mkOption { + type = types.package; + default = self.packages.${system}.default; + defaultText = lib.literalExpression "bug-tv-discord.packages.\${system}.default"; + description = "The bot package."; + }; + + activityPackage = mkOption { + type = types.package; + default = self.packages.${system}.activity; + defaultText = lib.literalExpression "bug-tv-discord.packages.\${system}.activity"; + description = "Static Activity files served by the bot's HTTP server."; + }; + + host = mkOption { + type = types.str; + default = "127.0.0.1"; + description = "Interface the HTTP/WS server binds to (cloudflared connects locally)."; + }; + + port = mkOption { + type = types.port; + default = 8791; + description = "HTTP/WS server TCP port."; + }; + + apiUrl = mkOption { + type = types.str; + default = "http://127.0.0.1:8789"; + description = "bug-tv API base URL used server-side."; + }; + + applicationId = mkOption { + type = types.str; + example = "123456789012345678"; + description = "Discord application id (not secret)."; + }; + + guildIds = mkOption { + type = types.listOf types.str; + default = [ ]; + description = "Guilds to register slash commands in (instant). Empty registers them globally."; + }; + + tokenFile = mkOption { + type = types.path; + description = "File holding the Discord bot token (passed via systemd LoadCredential)."; + }; + + clientSecretFile = mkOption { + type = types.path; + description = "File holding the Discord OAuth2 client secret (passed via systemd LoadCredential)."; + }; + + tmdbApiKey = mkOption { + type = types.str; + default = ""; + description = "TMDB API key. Ends up world-readable in the Nix store; prefer tmdbApiKeyFile."; + }; + + tmdbApiKeyFile = mkOption { + type = types.nullOr types.path; + default = null; + description = "File holding the TMDB API key (passed via systemd LoadCredential). Takes precedence over tmdbApiKey."; + }; + + providers = mkOption { + type = types.listOf types.str; + default = [ ]; + description = "bug-tv providers to query. Empty means bug-tv's defaults."; + }; + + extraConfig = mkOption { + type = types.attrsOf types.json; + default = { }; + description = "Extra keys recursively merged last into the generated config JSON."; + }; + }; + + config = lib.mkIf cfg.enable { + assertions = [ + { + assertion = cfg.tmdbApiKey != "" || cfg.tmdbApiKeyFile != null; + message = "services.bug-tv-discord: set tmdbApiKey or tmdbApiKeyFile"; + } + { + assertion = cfg.applicationId != ""; + message = "services.bug-tv-discord: set applicationId"; + } + ]; + + systemd.services.bug-tv-discord = { + description = "bug.tv Discord bot and Activity server"; + wantedBy = [ "multi-user.target" ]; + after = [ "network-online.target" ] ++ bugTv; + wants = [ "network-online.target" ] ++ bugTv; + + environment = { + BUG_TV_DISCORD_CONFIG = toString configFile; + NODE_ENV = "production"; + }; + + serviceConfig = { + ExecStart = lib.getExe cfg.package; + LoadCredential = [ + "token:${toString cfg.tokenFile}" + "client-secret:${toString cfg.clientSecretFile}" + ] + ++ lib.optional (cfg.tmdbApiKeyFile != null) "tmdb:${toString cfg.tmdbApiKeyFile}"; + + DynamicUser = true; + NoNewPrivileges = true; + PrivateTmp = true; + PrivateDevices = true; + ProtectSystem = "strict"; + ProtectHome = true; + ProtectHostname = true; + ProtectClock = true; + ProtectProc = "invisible"; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectKernelLogs = true; + ProtectControlGroups = true; + RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ]; + RestrictNamespaces = true; + RestrictRealtime = true; + RestrictSUIDSGID = true; + LockPersonality = true; + MemoryDenyWriteExecute = false; # node's JIT + SystemCallArchitectures = "native"; + CapabilityBoundingSet = ""; + AmbientCapabilities = ""; + UMask = "0077"; + Restart = "always"; + RestartSec = 5; + }; + }; + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..a1310fc --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,69 @@ +{ + lib, + buildNpmPackage, + importNpmLock, + nodejs_22, + makeWrapper, + # linked to lib/bug-tv-discord/activity, config.js's default activityDir + activity ? null, +}: + +let + nodejs = nodejs_22; + + src = lib.fileset.toSource { + root = ../.; + fileset = lib.fileset.unions [ + ../src + ../package.json + ../package-lock.json + ]; + }; + + pkgJson = lib.importJSON ../package.json; +in + +buildNpmPackage { + pname = "bug-tv-discord"; + inherit (pkgJson) version; + inherit src nodejs; + + # deps are fetched per-package from package-lock.json, no hash to keep in sync + npmDeps = importNpmLock { npmRoot = src; }; + npmConfigHook = importNpmLock.npmConfigHook; + + # esbuild's postinstall is only needed for the activity bundle (built with pkgs.esbuild) + npmFlags = [ "--ignore-scripts" ]; + dontNpmBuild = true; + + nativeBuildInputs = [ makeWrapper ]; + + installPhase = '' + runHook preInstall + + # the activity SDK and esbuild are dev deps; the bot only needs discord.js and ws + npm prune --omit=dev --ignore-scripts --offline --no-audit --no-fund + find node_modules -mindepth 1 -maxdepth 1 -type d -empty -delete + + mkdir -p $out/lib/bug-tv-discord + cp -r src node_modules package.json $out/lib/bug-tv-discord/ + + makeWrapper ${lib.getExe nodejs} $out/bin/bug-tv-discord \ + --add-flags $out/lib/bug-tv-discord/src/index.js \ + --set-default NODE_ENV production + '' + lib.optionalString (activity != null) '' + ln -s ${activity} $out/lib/bug-tv-discord/activity + '' + '' + + runHook postInstall + ''; + + passthru = { inherit activity; }; + + meta = { + inherit (pkgJson) description; + homepage = "https://git.bug.tools/bug/tv-discord"; + mainProgram = "bug-tv-discord"; + platforms = lib.platforms.linux; + }; +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..c5b247f --- /dev/null +++ b/package-lock.json @@ -0,0 +1,881 @@ +{ + "name": "bug-tv-discord", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "bug-tv-discord", + "version": "0.1.0", + "dependencies": { + "discord.js": "^14.16.0", + "ws": "^8.18.0" + }, + "devDependencies": { + "@discord/embedded-app-sdk": "^2.0.0", + "esbuild": "^0.24.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@discord/embedded-app-sdk": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@discord/embedded-app-sdk/-/embedded-app-sdk-2.5.0.tgz", + "integrity": "sha512-FNoe5PbSkoKEbqPubaBmq6tlEMOftMjR3gu55YrdrrKmBfKKM4i9P/Z+Zxl0RZdJcKviBwVcTyYMMPM/aGex/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/lodash.transform": "^4.6.6", + "@types/uuid": "^10.0.0", + "big-integer": "^1.6.48", + "decimal.js-light": "^2.5.0", + "eventemitter3": "^5.0.0", + "lodash.transform": "^4.6.0", + "uuid": "^11.0.0", + "zod": "^3.9.8" + } + }, + "node_modules/@discordjs/builders": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz", + "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/formatters": "^0.6.2", + "@discordjs/util": "^1.2.0", + "@sapphire/shapeshift": "^4.0.0", + "discord-api-types": "^0.38.40", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.4", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/collection": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz", + "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz", + "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==", + "license": "Apache-2.0", + "dependencies": { + "discord-api-types": "^0.38.33" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz", + "integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/collection": "^2.1.1", + "@discordjs/util": "^1.2.0", + "@sapphire/async-queue": "^1.5.3", + "@sapphire/snowflake": "^3.5.5", + "@vladfrangu/async_event_emitter": "^2.4.6", + "discord-api-types": "^0.38.50", + "magic-bytes.js": "^1.13.0", + "tslib": "^2.6.3", + "undici": "^6.27.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", + "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/util": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz", + "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==", + "license": "Apache-2.0", + "dependencies": { + "discord-api-types": "^0.38.33" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz", + "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/collection": "^2.1.0", + "@discordjs/rest": "^2.5.1", + "@discordjs/util": "^1.1.0", + "@sapphire/async-queue": "^1.5.2", + "@types/ws": "^8.5.10", + "@vladfrangu/async_event_emitter": "^2.2.4", + "discord-api-types": "^0.38.1", + "tslib": "^2.6.2", + "ws": "^8.17.0" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", + "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz", + "integrity": "sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.2.tgz", + "integrity": "sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz", + "integrity": "sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.2.tgz", + "integrity": "sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz", + "integrity": "sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz", + "integrity": "sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz", + "integrity": "sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz", + "integrity": "sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz", + "integrity": "sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz", + "integrity": "sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz", + "integrity": "sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz", + "integrity": "sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz", + "integrity": "sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz", + "integrity": "sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz", + "integrity": "sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz", + "integrity": "sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz", + "integrity": "sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz", + "integrity": "sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz", + "integrity": "sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz", + "integrity": "sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz", + "integrity": "sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz", + "integrity": "sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz", + "integrity": "sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz", + "integrity": "sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz", + "integrity": "sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@sapphire/async-queue": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz", + "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/shapeshift": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz", + "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v16" + } + }, + "node_modules/@sapphire/snowflake": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz", + "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@types/lodash": { + "version": "4.17.27", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.27.tgz", + "integrity": "sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash.transform": { + "version": "4.6.9", + "resolved": "https://registry.npmjs.org/@types/lodash.transform/-/lodash.transform-4.6.9.tgz", + "integrity": "sha512-1iIn+l7Vrj8hsr2iZLtxRkcV9AtjTafIyxKO9DX2EEcdOgz3Op5dhwKQFhMJgdfIRbYHBUF+SU97Y6P+zyLXNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@types/node": { + "version": "26.6.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz", + "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==", + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@vladfrangu/async_event_emitter": { + "version": "2.4.7", + "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz", + "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "dev": true, + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/decimal.js-light": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", + "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==", + "dev": true, + "license": "MIT" + }, + "node_modules/discord-api-types": { + "version": "0.38.57", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.57.tgz", + "integrity": "sha512-R1CTSSt4RshqCq23j2Xq2ZscvzB4LzG9OB1CYQdKUGdw8Ti/oF/72EEtK2mNpagG/Vj9NcBT7dw9lKLf+Dacfg==", + "license": "MIT" + }, + "node_modules/discord.js": { + "version": "14.27.0", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.27.0.tgz", + "integrity": "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/builders": "^1.14.1", + "@discordjs/collection": "1.5.3", + "@discordjs/formatters": "^0.6.2", + "@discordjs/rest": "^2.6.2", + "@discordjs/util": "^1.2.0", + "@discordjs/ws": "^1.2.3", + "@sapphire/snowflake": "3.5.5", + "discord-api-types": "^0.38.49", + "fast-deep-equal": "3.1.3", + "lodash.snakecase": "4.1.1", + "magic-bytes.js": "^1.13.0", + "tslib": "^2.6.3", + "undici": "^6.27.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/esbuild": { + "version": "0.24.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz", + "integrity": "sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.24.2", + "@esbuild/android-arm": "0.24.2", + "@esbuild/android-arm64": "0.24.2", + "@esbuild/android-x64": "0.24.2", + "@esbuild/darwin-arm64": "0.24.2", + "@esbuild/darwin-x64": "0.24.2", + "@esbuild/freebsd-arm64": "0.24.2", + "@esbuild/freebsd-x64": "0.24.2", + "@esbuild/linux-arm": "0.24.2", + "@esbuild/linux-arm64": "0.24.2", + "@esbuild/linux-ia32": "0.24.2", + "@esbuild/linux-loong64": "0.24.2", + "@esbuild/linux-mips64el": "0.24.2", + "@esbuild/linux-ppc64": "0.24.2", + "@esbuild/linux-riscv64": "0.24.2", + "@esbuild/linux-s390x": "0.24.2", + "@esbuild/linux-x64": "0.24.2", + "@esbuild/netbsd-arm64": "0.24.2", + "@esbuild/netbsd-x64": "0.24.2", + "@esbuild/openbsd-arm64": "0.24.2", + "@esbuild/openbsd-x64": "0.24.2", + "@esbuild/sunos-x64": "0.24.2", + "@esbuild/win32-arm64": "0.24.2", + "@esbuild/win32-ia32": "0.24.2", + "@esbuild/win32-x64": "0.24.2" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", + "license": "MIT" + }, + "node_modules/lodash.transform": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.transform/-/lodash.transform-4.6.0.tgz", + "integrity": "sha512-LO37ZnhmBVx0GvOU/caQuipEh4GN82TcWv3yHlebGDgOxbxiwwzW5Pcx2AcvpIv2WmvmSMoC492yQFNhy/l/UQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-bytes.js": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz", + "integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==", + "license": "MIT" + }, + "node_modules/ts-mixer": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz", + "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/undici": { + "version": "6.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", + "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", + "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..a1b4e72 --- /dev/null +++ b/package.json @@ -0,0 +1,21 @@ +{ + "name": "bug-tv-discord", + "version": "0.1.0", + "private": true, + "description": "Discord bot + Activity for watching bug.tv together in a voice channel", + "main": "src/index.js", + "engines": { "node": ">=22" }, + "scripts": { + "start": "node src/index.js", + "build:activity": "esbuild activity/js/main.js --bundle --format=esm --target=es2022 --outfile=activity/dist/main.js", + "test": "node --test 'test/**/*.test.js'" + }, + "dependencies": { + "discord.js": "^14.16.0", + "ws": "^8.18.0" + }, + "devDependencies": { + "@discord/embedded-app-sdk": "^2.0.0", + "esbuild": "^0.24.0" + } +} diff --git a/scripts/register-commands.js b/scripts/register-commands.js new file mode 100644 index 0000000..983a8dd --- /dev/null +++ b/scripts/register-commands.js @@ -0,0 +1,31 @@ +#!/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 { + const res = await rest.put(Routes.applicationCommands(cfg.applicationId), { body }); + 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 new file mode 100755 index 0000000..89c4c7d --- /dev/null +++ b/scripts/vendor-bugtv.sh @@ -0,0 +1,28 @@ +#!/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 new file mode 100644 index 0000000..911ce0d --- /dev/null +++ b/src/bot/autocomplete.js @@ -0,0 +1,26 @@ +// /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 new file mode 100644 index 0000000..3cb6dfd --- /dev/null +++ b/src/bot/commands.js @@ -0,0 +1,114 @@ +// 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: [] } }); + +function userVoiceChannel(interaction) { + const g = interaction.guild; + const vs = g && g.voiceStates.cache.get(interaction.user.id); + return (vs && vs.channelId) || null; +} + +// "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 +} + +async function watch(interaction, ctx) { + const vc = 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); +} + +function roomFor(interaction, ctx) { + const vc = userVoiceChannel(interaction); + return (vc && ctx.rooms.get(vc)) || ctx.rooms.all().find((r) => r.state.textChannelId === interaction.channelId) || null; +} + +async function np(interaction, ctx) { + const room = 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) { + const room = 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 new file mode 100644 index 0000000..f3a49b6 --- /dev/null +++ b/src/bot/controls.js @@ -0,0 +1,172 @@ +// 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) { + await interaction.reply(ephemeral(`Couldn't start the activity (${e.message}). Open it from the voice channel's Activities menu.`)).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 new file mode 100644 index 0000000..75006e3 --- /dev/null +++ b/src/bot/index.js @@ -0,0 +1,102 @@ +// Discord bot: gateway client, slash commands, control-message components, voice presence. + +const { Client, GatewayIntentBits, Events, MessageFlags } = 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 { + await app.commands.set(commandDefs); + 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 new file mode 100644 index 0000000..844ddf7 --- /dev/null +++ b/src/bot/render.js @@ -0,0 +1,271 @@ +// 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 new file mode 100644 index 0000000..39247af --- /dev/null +++ b/src/bot/updater.js @@ -0,0 +1,110 @@ +// 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 new file mode 100644 index 0000000..a6d6331 --- /dev/null +++ b/src/bugtv.js @@ -0,0 +1,176 @@ +// 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 new file mode 100644 index 0000000..78f0dd9 --- /dev/null +++ b/src/config.js @@ -0,0 +1,43 @@ +const fs = require('fs'); +const path = require('path'); + +const CONFIG_PATH = process.env.BUG_TV_DISCORD_CONFIG || path.join(__dirname, '..', 'config.json'); + +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: [], +}; + +const readFile = (file) => (file ? fs.readFileSync(file, 'utf8').trim() : ''); + +function loadConfig() { + const saved = fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {}; + const cfg = { ...DEFAULTS, ...saved }; + const env = process.env; + + 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(/\/+$/, ''); + + const missing = ['applicationId', 'token', 'clientSecret', 'tmdbKey'].filter((k) => !cfg[k]); + if (missing.length) { + console.error(`tv-discord: missing config: ${missing.join(', ')} (see config.example.json)`); + process.exit(1); + } + return cfg; +} + +module.exports = { loadConfig, CONFIG_PATH }; diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..01ba6c2 --- /dev/null +++ b/src/index.js @@ -0,0 +1,25 @@ +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 shutdown = () => { + server.close(); + bot.client.destroy(); + process.exit(0); + }; + process.on('SIGTERM', shutdown); + process.on('SIGINT', shutdown); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/src/room.js b/src/room.js new file mode 100644 index 0000000..e088919 --- /dev/null +++ b/src/room.js @@ -0,0 +1,698 @@ +// 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 new file mode 100644 index 0000000..0ac6ecf --- /dev/null +++ b/src/server.js @@ -0,0 +1,508 @@ +/* + HTTP + WebSocket server for the Activity (docs/protocol.md "HTTP + WS server"). + + createServer(cfg, rooms, { isInVoice, discordFetch }) → 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 + + 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. +*/ +const http = require('http'); +const fs = require('fs'); +const path = require('path'); +const { WebSocketServer } = require('ws'); + +const DISCORD_API = 'https://discord.com/api/v10'; +const USER_CACHE_MS = 10 * 60 * 1000; +const COALESCE_MS = 50; +const POLL_MS = 2000; +const HELLO_TIMEOUT_MS = 15000; +const MAX_BODY = 8 * 1024; +const MAX_WS_PAYLOAD = 16 * 1024; +const CMD_RATE = 10; // per second, per socket +const REPORT_RATE = 20; + +const MIME = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.map': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.webp': 'image/webp', + '.ico': 'image/x-icon', + '.woff2': 'font/woff2', + '.txt': 'text/plain; charset=utf-8', + '.vtt': 'text/vtt; charset=utf-8', +}; + +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, { + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': Buffer.byteLength(data), + 'Cache-Control': 'no-store', + ...headers, + }); + res.end(data); +} + +function readBody(req) { + return new Promise((resolve, reject) => { + let size = 0; + const chunks = []; + req.on('data', (c) => { + size += c.length; + if (size > MAX_BODY) { + reject(Object.assign(new Error('body too large'), { status: 413 })); + req.destroy(); + return; + } + chunks.push(c); + }); + req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + req.on('error', reject); + }); +} + +/** Token bucket: `rate` events per second, burst = rate. */ +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; + if (tokens < 1) return false; + tokens -= 1; + return true; + }; +} + +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 discordFetch = opts.discordFetch || ((...a) => fetch(...a)); + const activityDir = path.resolve(cfg.activityDir || path.join(__dirname, '..', 'activity')); + const log = opts.log || ((...a) => console.log('tv-discord:', ...a)); + + /* ---- Discord HTTP ------------------------------------------------------ */ + + const userCache = new Map(); // token → { user, exp } + + async function exchangeCode(code) { + const body = new URLSearchParams({ + client_id: String(cfg.applicationId || ''), + client_secret: String(cfg.clientSecret || ''), + grant_type: 'authorization_code', + code, + }); + const r = await discordFetch('https://discord.com/api/oauth2/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: body.toString(), + }); + const data = await r.json().catch(() => ({})); + if (!r.ok || !data.access_token) { + throw Object.assign(new Error(data.error_description || data.error || `discord ${r.status}`), { status: 502 }); + } + return data.access_token; + } + + async function userForToken(token) { + const now = Date.now(); + const hit = userCache.get(token); + if (hit && hit.exp > now) 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) }; + if (userCache.size > 5000) { + for (const [k, v] of userCache) if (v.exp <= now) userCache.delete(k); + if (userCache.size > 5000) userCache.clear(); + } + userCache.set(token, { user, exp: now + USER_CACHE_MS }); + return user; + } + + /* ---- static ------------------------------------------------------------ */ + + function cacheControl(ext) { + if (ext === '.html') return 'no-cache'; + if (ext === '.js' || ext === '.mjs' || ext === '.css' || ext === '.map') return 'public, max-age=300'; + return 'public, max-age=3600'; + } + + function serveFile(req, res, file, status = 200) { + fs.stat(file, (err, st) => { + if (err || !st.isFile()) return notFound(req, res); + const ext = path.extname(file).toLowerCase(); + res.writeHead(status, { + 'Content-Type': MIME[ext] || 'application/octet-stream', + 'Content-Length': st.size, + 'Cache-Control': cacheControl(ext), + 'X-Content-Type-Options': 'nosniff', + }); + if (req.method === 'HEAD') return res.end(); + fs.createReadStream(file).on('error', () => res.destroy()).pipe(res); + }); + } + + function notFound(req, res) { + res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-cache' }); + res.end(req.method === 'HEAD' ? undefined : 'not found'); + } + + function serveStatic(req, res, pathname) { + let rel; + try { + rel = decodeURIComponent(pathname); + } catch (e) { + return notFound(req, res); + } + if (rel.includes('\0')) return notFound(req, res); + let file = path.join(activityDir, path.normalize(rel)); + if (file !== activityDir && !file.startsWith(activityDir + path.sep)) return notFound(req, res); + if (rel.endsWith('/')) file = path.join(file, 'index.html'); + fs.stat(file, (err, st) => { + if (!err && st.isFile()) return serveFile(req, res, file); + if (!err && st.isDirectory()) return serveFile(req, res, path.join(file, 'index.html')); + // SPA fallback only for extension-less routes; a missing asset is a real 404 + if (path.extname(rel)) return notFound(req, res); + serveFile(req, res, path.join(activityDir, 'index.html')); + }); + } + + /* ---- http -------------------------------------------------------------- */ + + async function onRequest(req, res) { + let url; + try { + url = new URL(req.url, 'http://x'); + } catch (e) { + return sendJson(res, 400, { error: 'bad url' }); + } + const p = stripProxy(url.pathname); + try { + 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 }); + } + if (p === '/api/token') { + if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' }); + let body; + try { + body = JSON.parse((await readBody(req)) || '{}'); + } catch (e) { + return sendJson(res, e.status || 400, { error: e.status ? e.message : 'invalid json' }); + } + const code = body && body.code; + if (typeof code !== 'string' || !code || code.length > 512) return sendJson(res, 400, { error: 'missing code' }); + const access_token = await exchangeCode(code); + return sendJson(res, 200, { access_token }); + } + 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); + } catch (e) { + log('http error', p, e.message); + if (!res.headersSent) sendJson(res, e.status || 500, { error: e.status ? e.message : 'internal error' }); + else res.destroy(); + } + } + + const server = http.createServer((req, res) => { + onRequest(req, res); + }); + + /* ---- channels ---------------------------------------------------------- */ + + // channelId → { id, room, sockets:Set, users: Map, timer, detach } + const channels = new Map(); + const deadRooms = new WeakSet(); + + 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); + } + return ch; + } + + function stateOf(ch) { + return ch.room ? ch.room.publicState(Date.now()) : emptyState(); + } + + function send(ws, msg) { + if (ws.readyState === 1) ws.send(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 scheduleBroadcast(ch) { + if (!ch.timer) ch.timer = setTimeout(() => broadcast(ch), COALESCE_MS); + } + + 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 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 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); + }); + } + + /* ---- websocket --------------------------------------------------------- */ + + const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_WS_PAYLOAD }); + + server.on('upgrade', (req, socket, head) => { + let p = ''; + try { + p = stripProxy(new URL(req.url, 'http://x').pathname); + } catch (e) { + /* bad url */ + } + if (p !== '/ws') { + socket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n'); + socket.destroy(); + return; + } + wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req)); + }); + + wss.on('connection', (ws) => { + let user = null; + let ch = null; + let authing = false; + const cmdOk = bucket(CMD_RATE); + const reportOk = bucket(REPORT_RATE); + const msgOk = bucket(50); + + 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); + + 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'); + 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'); + u = await userForToken(msg.token); + } + } catch (e) { + return fatal('authentication failed'); + } + let ok = false; + try { + ok = await isInVoice(channelId, u.id); + } catch (e) { + ok = false; + } + 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) }); + } + } + + ws.on('message', (raw, isBinary) => { + if (isBinary || !msgOk()) return; + let msg; + try { + msg = JSON.parse(raw.toString('utf8')); + } catch (e) { + return; + } + if (!msg || typeof msg !== 'object') return; + switch (msg.t) { + case 'ping': + return send(ws, { t: 'pong', at: msg.at, now: Date.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)); + } + default: + } + }); + + ws.on('close', () => { + clearTimeout(helloTimer); + if (!user || !ch) return; + ch.sockets.delete(ws); + leaveUser(ch, user.id); + dropChannelIfEmpty(ch); + }); + ws.on('error', () => {}); + }); + + server.on('close', () => { + if (pollTimer) clearInterval(pollTimer); + pollTimer = null; + 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; + return server; +} + +module.exports = { createServer, emptyState }; diff --git a/test/bot.test.js b/test/bot.test.js new file mode 100644 index 0000000..0d73c1f --- /dev/null +++ b/test/bot.test.js @@ -0,0 +1,99 @@ +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 new file mode 100644 index 0000000..cd7f088 --- /dev/null +++ b/test/helpers.js @@ -0,0 +1,91 @@ +// 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 new file mode 100644 index 0000000..f00f250 --- /dev/null +++ b/test/render.test.js @@ -0,0 +1,152 @@ +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 new file mode 100644 index 0000000..acfe953 --- /dev/null +++ b/test/room.test.js @@ -0,0 +1,273 @@ +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 new file mode 100644 index 0000000..d3f5397 --- /dev/null +++ b/test/server.test.js @@ -0,0 +1,378 @@ +const test = require('node:test'); +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 }; + } +} + +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 USERS = { good: { id: '111', username: 'alice' }, bob: { id: '222', username: 'bob' } }; + +function fakeDiscord() { + const calls = []; + const fn = async (url, init = {}) => { + calls.push([url, init]); + const res = (status, body) => ({ ok: status < 300, status, json: async () => 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(400, { error: 'invalid_grant' }); + } + if (url.endsWith('/users/@me')) { + const tok = (init.headers.Authorization || '').replace('Bearer ', ''); + return USERS[tok] ? res(200, USERS[tok]) : res(401, { message: '401: Unauthorized' }); + } + return res(404, {}); + }; + fn.calls = calls; + return fn; +} + +/* ---- harness --------------------------------------------------------------- */ + +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)'); + +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: () => {}, + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + const base = `http://127.0.0.1:${server.address().port}`; + const sockets = []; + const open = (p = '/ws') => { + const ws = new WebSocket(base.replace('http', 'ws') + p); + sockets.push(ws); + const queue = []; + const waiters = []; + ws.on('message', (d) => { + const m = JSON.parse(d); + const i = waiters.findIndex((w) => w.pred(m)); + if (i >= 0) waiters.splice(i, 1)[0].resolve(m); + else queue.push(m); + }); + ws.next = (pred = () => true, ms = 3000) => { + const i = queue.findIndex(pred); + if (i >= 0) return Promise.resolve(queue.splice(i, 1)[0]); + return new Promise((resolve, reject) => { + const w = { pred, resolve }; + waiters.push(w); + setTimeout(() => { + const j = waiters.indexOf(w); + if (j < 0) return; + waiters.splice(j, 1); + reject(new Error('timeout waiting for message')); + }, ms).unref(); + }); + }; + ws.closed = new Promise((r) => ws.on('close', (code) => r(code))); + ws.opened = new Promise((r, j) => { + ws.on('open', r); + ws.on('error', j); + }); + ws.json = (m) => ws.send(JSON.stringify(m)); + return ws; + }; + const stop = async () => { + for (const ws of sockets) ws.terminate(); + await new Promise((r) => server.close(r)); + }; + return { server, rooms, discordFetch, base, open, stop }; +} + +const tick = (ms) => new Promise((r) => setTimeout(r, ms)); + +/* ---- http ------------------------------------------------------------------ */ + +test('static files, SPA fallback, config, healthz', async () => { + const h = await start(); + try { + let r = await fetch(`${h.base}/`); + 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`); + 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`); + assert.equal(r.status, 200); + r = await fetch(`${h.base}/some/route`); + assert.equal(r.status, 200); + assert.match(await r.text(), /x/); + r = await fetch(`${h.base}/missing.js`); + assert.equal(r.status, 404); + r = await fetch(`${h.base}/..%2f..%2fetc%2fpasswd`); + 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}/healthz`); + assert.deepEqual(await r.json(), { ok: true }); + } finally { + await h.stop(); + } +}); + +test('POST /api/token exchanges the code with Discord', async () => { + const h = await start(); + 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' }); + 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'); + 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: '{}' }); + assert.equal(r.status, 400); + r = await fetch(`${h.base}/api/token`, { method: 'POST', body: 'nope' }); + assert.equal(r.status, 400); + r = await fetch(`${h.base}/api/token`); + assert.equal(r.status, 405); + } finally { + await h.stop(); + } +}); + +/* ---- websocket ------------------------------------------------------------- */ + +test('hello: bad token → error + close; not in voice → error + close', 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); + + 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']); + } finally { + await h.stop(); + } +}); + +test('ping → pong with server time', async () => { + const h = await start(); + 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(); + } +}); + +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'); + 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'], + ], + ); + } finally { + await h.stop(); + } +}); + +test('cmds are rate limited per socket', 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' }); + 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 b = h.open('/nope'); + await assert.rejects(b.opened); + } finally { + await h.stop(); + } +}); diff --git a/test/sync.test.js b/test/sync.test.js new file mode 100644 index 0000000..ce41e3f --- /dev/null +++ b/test/sync.test.js @@ -0,0 +1,73 @@ +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'); +});