v2: watch-party Activity

The Activity is now the full bug.tv site plus a small Discord overlay. Whoever
starts the instance hosts and controls everything; everyone else mirrors the
host's page and playback. The server is a relay keyed by activity instance and
checks membership through Discord's activity-instances API, so it works in DM
and group calls. The bot gateway, slash commands and control message are gone.
This commit is contained in:
4DBug committed 2026-10-27 10:00:34 -05:00
1 parent 4d900c5b56
commit 7de90b5b7c
39 files changed
+1620 -4372

No files matched your search

+1 -2
View File
@@ -1,5 +1,4 @@
node_modules/
result*
activity/dist/
site/
config.json
activity/vendor/bugtv/
+33
View File
@@ -0,0 +1,33 @@
# tv-discord
A Discord Activity for watching [bug.tv](https://tv.bug.tools) together. The Activity is the whole bug.tv site with a small watch-party overlay on top. Whoever starts the Activity is the **host** and controls everything. Everyone else in the call follows the host's page and playback in sync, and can only change volume and fullscreen. If the host leaves, the next person to have joined takes over.
The contract is in [docs/protocol.md](docs/protocol.md).
## Layout
- `src/server.js`: static files, `/api/config`, `/api/token` (OAuth code exchange), `/api/avatar/:id`, and the `/ws` relay (one hub per Activity instance).
- `activity/js/discord.js`: the overlay. It handles the Discord SDK and auth, the WebSocket transport for bug.tv's `party.js`, the members pill, the viewer banner and input blocking. esbuild bundles it into `discord.js`.
- `activity/overlay.css`: the overlay styles.
- `scripts/build-activity.sh <bug-tv web dir> <out dir> [apiBase=/tv]`: builds the Activity site.
## Run
```sh
npm install
bash scripts/build-activity.sh ../tv/web site # or nix build .#activity
cp config.example.json config.json # applicationId, tokenFile, clientSecretFile
npm start
```
The bot token is only used to check who is in an Activity instance; there is no gateway connection.
**Discord URL mappings:**
- `/` → this server
- `/tv` → api-tv.bug.tools
- `/tmdb` → api.themoviedb.org
- `/img` → image.tmdb.org
**Dev without Discord:** set `"dev": true` and `"devApiUrl": "http://127.0.0.1:8789"` (a local bug-tv API). Build the site with an absolute API base, or use the default `/tv`, which the dev server proxies. Then open `/?user=1&instance=x` and `/?user=2&instance=x` in two browsers.
## Test
```sh
npm test
```
-146
View File
@@ -1,146 +0,0 @@
:root {
--bg: #08080c;
--fg: #f4f2f8;
--muted: #a39fb0;
--accent: #c084fc;
--accent-2: #a855f7;
--glass: rgba(14, 12, 20, 0.72);
--line: rgba(255, 255, 255, 0.16);
color-scheme: dark;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--fg); overflow: hidden; }
button { font: inherit; color: inherit; }
[hidden] { display: none !important; }
.app { position: fixed; inset: 0; user-select: none; -webkit-user-select: none; }
.video { position: absolute; inset: 0; width: 100%; height: 100%; background: #000; object-fit: contain; }
.video::cue { background: rgba(0, 0, 0, 0.62); font-size: clamp(14px, 3.2vh, 30px); }
.backdrop {
position: absolute; inset: 0; background-size: cover; background-position: center;
opacity: 0; transition: opacity 0.6s; filter: blur(2px) brightness(0.35);
}
/* ---- full screens -------------------------------------------------------- */
.screen {
position: absolute; inset: 0; display: none; flex-direction: column; align-items: center; justify-content: center;
gap: 12px; padding: 24px; text-align: center;
background: radial-gradient(ellipse at 50% 35%, rgba(192, 132, 252, 0.14), transparent 60%), var(--bg);
}
.app[data-view="boot"] .idle,
.app[data-view="idle"] .idle,
.app[data-view="error"] .idle { display: flex; }
.app[data-view="finding"] .finding { display: flex; background: transparent; }
.app[data-view="finding"] .backdrop { opacity: 1; }
.app:not([data-view="play"]) .video,
.app:not([data-view="play"]) .top,
.app:not([data-view="play"]) .bottom,
.app:not([data-view="play"]) .spinner,
.app:not([data-view="play"]) .join,
.app:not([data-view="play"]) .unmute { display: none; }
.idle__logo { width: clamp(64px, 16vh, 120px); height: auto; animation: bob 3.2s ease-in-out infinite; filter: drop-shadow(0 8px 24px rgba(192, 132, 252, 0.35)); }
.idle__title { margin: 0; font-size: clamp(28px, 7vh, 52px); font-weight: 800; letter-spacing: -0.03em; }
.idle__title span { color: var(--accent); }
.idle__msg { margin: 0; color: var(--muted); font-size: clamp(14px, 2.6vh, 18px); max-width: 32em; }
.app[data-view="error"] .idle__msg { color: #fca5a5; }
@keyframes bob { 50% { transform: translateY(-8px) rotate(-4deg); } }
.finding__title { margin: 8px 0 0; font-size: clamp(20px, 4.5vh, 34px); font-weight: 700; }
.finding__msg { margin: 0; color: var(--muted); }
.ring {
width: 44px; height: 44px; border-radius: 50%;
border: 3px solid rgba(255, 255, 255, 0.14); border-top-color: var(--accent);
animation: spin 0.9s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.spinner { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; pointer-events: none; }
.spinner p { margin: 0; color: var(--muted); font-size: 14px; text-shadow: 0 1px 4px #000; }
/* ---- overlays ------------------------------------------------------------ */
.top, .bottom { position: absolute; left: 0; right: 0; transition: opacity 0.25s, transform 0.25s; }
.app.is-idle .top, .app.is-idle .bottom { opacity: 0; pointer-events: none; }
.app.is-idle { cursor: none; }
.app.is-idle .top { transform: translateY(-8px); }
.app.is-idle .bottom { transform: translateY(8px); }
.top {
top: 0; display: flex; align-items: flex-start; gap: 16px;
padding: max(14px, env(safe-area-inset-top)) 18px 40px;
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.75), transparent);
}
.top__text { min-width: 0; flex: 1; }
.top__title { font-size: clamp(15px, 2.8vh, 22px); font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.top__sub { color: var(--muted); font-size: 13px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.top__src {
flex: none; font-size: 12px; font-weight: 600; padding: 4px 9px; border-radius: 999px;
background: rgba(192, 132, 252, 0.16); color: var(--accent); border: 1px solid rgba(192, 132, 252, 0.35);
}
.top__src:empty { display: none; }
.bottom {
bottom: 0; padding: 40px 14px max(10px, env(safe-area-inset-bottom));
background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
}
.row { display: flex; align-items: center; gap: 10px; }
.spacer { flex: 1; }
.btn {
width: 40px; height: 40px; display: grid; place-items: center; border: 0; border-radius: 10px;
background: transparent; cursor: pointer;
}
.btn:hover { background: rgba(255, 255, 255, 0.1); }
.btn svg { width: 24px; height: 24px; }
.time { font-variant-numeric: tabular-nums; font-size: 13px; color: #ddd; }
.viewers { display: flex; align-items: center; gap: 6px; font-size: 13px; color: #ddd; }
.viewers svg { width: 18px; height: 18px; color: var(--accent); }
.seek { position: relative; height: 18px; display: flex; align-items: center; cursor: pointer; touch-action: none; }
.seek__track { position: relative; width: 100%; height: 4px; border-radius: 4px; background: rgba(255, 255, 255, 0.2); overflow: hidden; transition: height 0.15s; }
.seek:hover .seek__track { height: 6px; }
.seek__buf, .seek__fill { position: absolute; left: 0; top: 0; bottom: 0; width: 0; }
.seek__buf { background: rgba(255, 255, 255, 0.28); }
.seek__fill { background: var(--accent); }
.seek__tip {
position: absolute; bottom: 22px; transform: translateX(-50%); padding: 3px 7px; border-radius: 6px;
background: var(--glass); font-size: 12px; font-variant-numeric: tabular-nums; pointer-events: none;
}
.join {
position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
display: flex; align-items: center; gap: 12px; padding: 18px 26px; border: 0; border-radius: 16px;
background: var(--accent); color: #1a0b2e; font-weight: 800; font-size: clamp(15px, 2.8vh, 20px);
box-shadow: 0 10px 40px rgba(192, 132, 252, 0.45); cursor: pointer;
}
.join svg { width: 26px; height: 26px; }
.join:hover { background: #d0a2fd; }
.unmute {
position: absolute; right: 16px; top: 64px; display: flex; align-items: center; gap: 8px;
padding: 8px 14px; border: 1px solid var(--line); border-radius: 999px; background: var(--glass);
font-weight: 600; font-size: 13px; cursor: pointer;
}
.unmute svg { width: 18px; height: 18px; }
/* ---- toasts -------------------------------------------------------------- */
.toasts { position: absolute; left: 50%; top: 70px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 8px; align-items: center; pointer-events: none; z-index: 5; }
.toast {
padding: 9px 16px; border-radius: 10px; background: var(--glass); border: 1px solid var(--line);
font-size: 14px; max-width: 80vw; opacity: 0; transform: translateY(-6px); transition: opacity 0.25s, transform 0.25s;
}
.toast.is-in { opacity: 1; transform: none; }
@media (max-width: 520px) {
.top { padding-left: 12px; padding-right: 12px; }
.top__src { display: none; }
}
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36"><path fill="#AA8DD8" d="M7.415 4c1-1 .25-4-1.438-4s-1.562 2-.562 2 1 2 1 3 1-1 1-1zM3.232 5.72c1-1 .25-4-1.438-4s-1.562 2-.562 2 1 2 1 3 1-1 1-1z"/><path fill="#744EAA" d="M29.607 32.856c.189.808 1.227 2.28 2.032 2.091.806-.19 1.077-1.971.888-2.777-.189-.808-.998-1.307-1.804-1.117-.805.19-1.306.997-1.116 1.803zm-5.434.649c.003.83.681 2.498 1.509 2.495.828-.004 1.494-1.677 1.491-2.506-.003-.829-.677-1.497-1.505-1.495-.828.004-1.498.677-1.495 1.506zm-5.271-2.446c-.326.764-.365 2.563.396 2.89.763.324 2.037-.947 2.363-1.71.325-.762-.028-1.643-.789-1.97-.762-.325-1.643.027-1.97.79zm-5.031-11.04c-.812.172-2.308 1.173-2.139 1.983.173.81 1.945 1.124 2.757.953.811-.171 1.329-.967 1.16-1.777-.172-.81-.965-1.33-1.778-1.159zm-2.037-5c-.812.172-2.308 1.173-2.139 1.983.173.81 1.945 1.124 2.757.953.811-.171 1.329-.967 1.16-1.777-.172-.81-.966-1.33-1.778-1.159z"/><path fill="#9266CC" d="M27.244 34c2.831 0 4.926-.877 5.266-1.027 2.271-1.01 3.293-3.669 2.284-5.939-.999-2.25-3.616-3.275-5.872-2.314-.133.05-1.793.649-3.343-.072-1.851-.861-2.995-3.309-3.628-5.209-.144-.43-.385-1.274-.686-2.316-1.866-6.471-2.832-8.285-3.983-9.82C13.571 2.352 7.69 2.007 4.799 2.587c-2.437.487-4.018 2.858-3.53 5.295.488 2.438 2.86 4.02 5.296 3.53.162-.026 2.204-.306 3.424 1.169.643 1.287 2.08 5.128 2.63 7.034.346 1.199.629 2.171.794 2.667 1.773 5.317 4.666 8.893 8.603 10.629C23.868 33.729 25.67 34 27.244 34z"/><circle fill="#FFF" cx="6.682" cy="5" r="1"/><path d="M30.923 32.964c-.089 0-.18-.012-.269-.036-.532-.148-.844-.699-.696-1.231.757-2.722-.77-4.542-.785-4.56-.359-.419-.312-1.051.107-1.41.418-.359 1.051-.312 1.41.107.092.107 2.234 2.66 1.195 6.397-.122.443-.525.733-.962.733zm-7.199-.563c-.245 0-.49-.089-.684-.27-.403-.378-.424-1.011-.047-1.414 1.485-1.587 1.453-4.193 1.452-4.22-.016-.552.419-1.012.972-1.028.542-.005 1.013.419 1.028.972.004.139.073 3.437-1.991 5.644-.197.21-.464.316-.73.316zm-8.542-8.696c-.48 0-.904-.347-.985-.837-.09-.544.278-1.06.823-1.149 3.074-.51 4.774-2.377 4.791-2.396.365-.41.998-.449 1.409-.084.412.365.453.993.091 1.406-.087.099-2.156 2.415-5.964 3.046-.056.01-.111.014-.165.014zm2.921 4.857c-.425 0-.819-.272-.954-.698-.166-.526.126-1.089.652-1.255 2.693-.853 3.88-2.83 3.892-2.85.28-.477.892-.637 1.368-.357.477.279.636.893.357 1.368-.063.108-1.595 2.663-5.013 3.744-.101.033-.203.048-.302.048zm-4.619-10.67c-.496 0-.927-.369-.991-.875-.069-.548.319-1.048.867-1.118 2.689-.34 4.657-1.971 4.676-1.988.422-.354 1.053-.303 1.408.119.356.421.305 1.05-.115 1.407-.097.083-2.42 2.029-5.718 2.446-.043.006-.085.009-.127.009zm-1.821-4.767c-.425 0-.819-.273-.954-.701-.165-.527.127-1.088.654-1.254 3.13-.983 4.253-2.692 4.299-2.764.295-.462.911-.605 1.375-.312.465.292.611.899.324 1.366-.06.097-1.506 2.396-5.399 3.619-.099.031-.2.046-.299.046z" fill="#744EAA"/></svg>

Before

Width:  |  Height:  |  Size: 2.8 KiB

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