tv-discord: Discord bot + Activity for watching bug.tv together

This commit is contained in:
4DBug committed 2026-10-27 08:54:57 -05:00
commit bdc582a438
36 files changed
+5841

No files matched your search

+508
View File
@@ -0,0 +1,508 @@
/*
HTTP + WebSocket server for the Activity (docs/protocol.md "HTTP + WS server").
createServer(cfg, rooms, { isInVoice, discordFetch }) → http.Server (not listening)
GET / static Activity files from cfg.activityDir, SPA fallback to index.html
GET /api/config { applicationId }
POST /api/token {code} { access_token } (Discord OAuth2 code exchange)
GET /healthz { ok: true }
GET /ws WebSocket room sync
A leading "/.proxy" (Discord's legacy URL-mapping prefix) is stripped from every path.
Sockets for a channel without a room yet wait in `channels` and attach as soon as the room
appears: rooms' 'created' event when it exists, otherwise a 2s poll of rooms.get().
`discordFetch` (default: global fetch) is injectable for tests. With cfg.dev === true a
`{t:'hello', dev:true, userId, channelId}` is accepted without a Discord token.
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const { WebSocketServer } = require('ws');
const DISCORD_API = 'https://discord.com/api/v10';
const USER_CACHE_MS = 10 * 60 * 1000;
const COALESCE_MS = 50;
const POLL_MS = 2000;
const HELLO_TIMEOUT_MS = 15000;
const MAX_BODY = 8 * 1024;
const MAX_WS_PAYLOAD = 16 * 1024;
const CMD_RATE = 10; // per second, per socket
const REPORT_RATE = 20;
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.map': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
'.vtt': 'text/vtt; charset=utf-8',
};
function emptyState(now = Date.now()) {
return {
media: null,
stream: null,
subtitle: -1,
quality: -1,
playing: false,
position: 0,
updatedAt: now,
now,
duration: 0,
viewers: [],
leader: null,
rev: 0,
notice: null,
};
}
function sendJson(res, status, body, headers = {}) {
const data = JSON.stringify(body);
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(data),
'Cache-Control': 'no-store',
...headers,
});
res.end(data);
}
function readBody(req) {
return new Promise((resolve, reject) => {
let size = 0;
const chunks = [];
req.on('data', (c) => {
size += c.length;
if (size > MAX_BODY) {
reject(Object.assign(new Error('body too large'), { status: 413 }));
req.destroy();
return;
}
chunks.push(c);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
/** Token bucket: `rate` events per second, burst = rate. */
function bucket(rate) {
let tokens = rate;
let last = Date.now();
return () => {
const now = Date.now();
tokens = Math.min(rate, tokens + ((now - last) / 1000) * rate);
last = now;
if (tokens < 1) return false;
tokens -= 1;
return true;
};
}
function stripProxy(pathname) {
return pathname === '/.proxy' ? '/' : pathname.startsWith('/.proxy/') ? pathname.slice(7) : pathname;
}
function createServer(cfg, rooms, opts = {}) {
const isInVoice = opts.isInVoice || (async () => false);
const discordFetch = opts.discordFetch || ((...a) => fetch(...a));
const activityDir = path.resolve(cfg.activityDir || path.join(__dirname, '..', 'activity'));
const log = opts.log || ((...a) => console.log('tv-discord:', ...a));
/* ---- Discord HTTP ------------------------------------------------------ */
const userCache = new Map(); // token → { user, exp }
async function exchangeCode(code) {
const body = new URLSearchParams({
client_id: String(cfg.applicationId || ''),
client_secret: String(cfg.clientSecret || ''),
grant_type: 'authorization_code',
code,
});
const r = await discordFetch('https://discord.com/api/oauth2/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: body.toString(),
});
const data = await r.json().catch(() => ({}));
if (!r.ok || !data.access_token) {
throw Object.assign(new Error(data.error_description || data.error || `discord ${r.status}`), { status: 502 });
}
return data.access_token;
}
async function userForToken(token) {
const now = Date.now();
const hit = userCache.get(token);
if (hit && hit.exp > now) return hit.user;
const r = await discordFetch(`${DISCORD_API}/users/@me`, { headers: { Authorization: `Bearer ${token}` } });
if (!r.ok) throw new Error(`invalid token (${r.status})`);
const u = await r.json();
if (!u || !u.id) throw new Error('invalid token');
const user = { id: String(u.id), username: u.global_name || u.username || String(u.id) };
if (userCache.size > 5000) {
for (const [k, v] of userCache) if (v.exp <= now) userCache.delete(k);
if (userCache.size > 5000) userCache.clear();
}
userCache.set(token, { user, exp: now + USER_CACHE_MS });
return user;
}
/* ---- static ------------------------------------------------------------ */
function cacheControl(ext) {
if (ext === '.html') return 'no-cache';
if (ext === '.js' || ext === '.mjs' || ext === '.css' || ext === '.map') return 'public, max-age=300';
return 'public, max-age=3600';
}
function serveFile(req, res, file, status = 200) {
fs.stat(file, (err, st) => {
if (err || !st.isFile()) return notFound(req, res);
const ext = path.extname(file).toLowerCase();
res.writeHead(status, {
'Content-Type': MIME[ext] || 'application/octet-stream',
'Content-Length': st.size,
'Cache-Control': cacheControl(ext),
'X-Content-Type-Options': 'nosniff',
});
if (req.method === 'HEAD') return res.end();
fs.createReadStream(file).on('error', () => res.destroy()).pipe(res);
});
}
function notFound(req, res) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-cache' });
res.end(req.method === 'HEAD' ? undefined : 'not found');
}
function serveStatic(req, res, pathname) {
let rel;
try {
rel = decodeURIComponent(pathname);
} catch (e) {
return notFound(req, res);
}
if (rel.includes('\0')) return notFound(req, res);
let file = path.join(activityDir, path.normalize(rel));
if (file !== activityDir && !file.startsWith(activityDir + path.sep)) return notFound(req, res);
if (rel.endsWith('/')) file = path.join(file, 'index.html');
fs.stat(file, (err, st) => {
if (!err && st.isFile()) return serveFile(req, res, file);
if (!err && st.isDirectory()) return serveFile(req, res, path.join(file, 'index.html'));
// SPA fallback only for extension-less routes; a missing asset is a real 404
if (path.extname(rel)) return notFound(req, res);
serveFile(req, res, path.join(activityDir, 'index.html'));
});
}
/* ---- http -------------------------------------------------------------- */
async function onRequest(req, res) {
let url;
try {
url = new URL(req.url, 'http://x');
} catch (e) {
return sendJson(res, 400, { error: 'bad url' });
}
const p = stripProxy(url.pathname);
try {
if (p === '/healthz') return sendJson(res, 200, { ok: true });
if (p === '/api/config') {
if (req.method !== 'GET' && req.method !== 'HEAD') return sendJson(res, 405, { error: 'method not allowed' });
return sendJson(res, 200, { applicationId: String(cfg.applicationId || ''), dev: cfg.dev === true });
}
if (p === '/api/token') {
if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' });
let body;
try {
body = JSON.parse((await readBody(req)) || '{}');
} catch (e) {
return sendJson(res, e.status || 400, { error: e.status ? e.message : 'invalid json' });
}
const code = body && body.code;
if (typeof code !== 'string' || !code || code.length > 512) return sendJson(res, 400, { error: 'missing code' });
const access_token = await exchangeCode(code);
return sendJson(res, 200, { access_token });
}
if (p.startsWith('/api/')) return sendJson(res, 404, { error: 'not found' });
if (req.method !== 'GET' && req.method !== 'HEAD') return sendJson(res, 405, { error: 'method not allowed' });
return serveStatic(req, res, p);
} catch (e) {
log('http error', p, e.message);
if (!res.headersSent) sendJson(res, e.status || 500, { error: e.status ? e.message : 'internal error' });
else res.destroy();
}
}
const server = http.createServer((req, res) => {
onRequest(req, res);
});
/* ---- channels ---------------------------------------------------------- */
// channelId → { id, room, sockets:Set<ws>, users: Map<userId,count>, timer, detach }
const channels = new Map();
const deadRooms = new WeakSet();
function getChannel(id) {
let ch = channels.get(id);
if (!ch) {
ch = { id, room: null, sockets: new Set(), users: new Map(), timer: null, detach: null };
channels.set(id, ch);
}
return ch;
}
function stateOf(ch) {
return ch.room ? ch.room.publicState(Date.now()) : emptyState();
}
function send(ws, msg) {
if (ws.readyState === 1) ws.send(JSON.stringify(msg));
}
function broadcast(ch) {
ch.timer = null;
if (!ch.sockets.size) return;
const data = JSON.stringify({ t: 'state', state: stateOf(ch) });
for (const ws of ch.sockets) if (ws.readyState === 1) ws.send(data);
}
function scheduleBroadcast(ch) {
if (!ch.timer) ch.timer = setTimeout(() => broadcast(ch), COALESCE_MS);
}
function joinUser(ch, userId) {
const n = ch.users.get(userId) || 0;
ch.users.set(userId, n + 1);
if (n === 0 && ch.room) ch.room.join(userId);
}
function leaveUser(ch, userId) {
const n = ch.users.get(userId) || 0;
if (n <= 1) {
ch.users.delete(userId);
if (n === 1 && ch.room) ch.room.leave(userId);
} else ch.users.set(userId, n - 1);
}
function attach(ch, room) {
if (ch.room === room || deadRooms.has(room)) return;
if (ch.detach) ch.detach();
ch.room = room;
const onChange = () => scheduleBroadcast(ch);
const onClosed = () => {
deadRooms.add(room);
if (ch.room !== room) return;
ch.detach();
ch.room = null;
if (ch.timer) clearTimeout(ch.timer);
ch.timer = null;
broadcast(ch); // room gone → empty state, sockets keep waiting for the next room
ensurePoll();
};
room.on('change', onChange);
room.on('closed', onClosed);
ch.detach = () => {
room.removeListener('change', onChange);
room.removeListener('closed', onClosed);
ch.detach = null;
};
for (const userId of ch.users.keys()) room.join(userId);
scheduleBroadcast(ch);
}
function lookup(ch) {
if (ch.room) return;
const room = rooms.get(ch.id);
if (room && !deadRooms.has(room)) attach(ch, room);
}
function dropChannelIfEmpty(ch) {
if (ch.sockets.size) return;
if (ch.detach) ch.detach();
if (ch.timer) clearTimeout(ch.timer);
channels.delete(ch.id);
}
// room creation: event if rooms emits one, plus a poll for waiting channels as a fallback
let pollTimer = null;
function ensurePoll() {
if (pollTimer) return;
pollTimer = setInterval(() => {
let waiting = 0;
for (const ch of channels.values()) {
if (ch.room) continue;
lookup(ch);
if (!ch.room) waiting++;
}
if (!waiting) {
clearInterval(pollTimer);
pollTimer = null;
}
}, POLL_MS);
if (pollTimer.unref) pollTimer.unref();
}
if (rooms && typeof rooms.on === 'function') {
rooms.on('created', (room) => {
const id = room && (room.id || (room.state && room.state.id));
const ch = id != null && channels.get(String(id));
if (ch && !ch.room) attach(ch, room);
});
}
/* ---- websocket --------------------------------------------------------- */
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_WS_PAYLOAD });
server.on('upgrade', (req, socket, head) => {
let p = '';
try {
p = stripProxy(new URL(req.url, 'http://x').pathname);
} catch (e) {
/* bad url */
}
if (p !== '/ws') {
socket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));
});
wss.on('connection', (ws) => {
let user = null;
let ch = null;
let authing = false;
const cmdOk = bucket(CMD_RATE);
const reportOk = bucket(REPORT_RATE);
const msgOk = bucket(50);
const fatal = (message) => {
send(ws, { t: 'error', message });
ws.close(4001, message.slice(0, 100));
};
const helloTimer = setTimeout(() => !user && fatal('hello timeout'), HELLO_TIMEOUT_MS);
async function hello(msg) {
if (user || authing) return;
authing = true;
const channelId = String(msg.channelId || '');
if (!/^\d{1,25}$/.test(channelId)) return fatal('missing channelId');
let u;
try {
if (msg.dev && cfg.dev === true) {
const id = String(msg.userId || msg.user || '');
if (!/^[\w-]{1,32}$/.test(id)) return fatal('missing userId');
u = { id, username: String(msg.username || `dev-${id}`).slice(0, 32) };
} else {
if (typeof msg.token !== 'string' || !msg.token) return fatal('missing token');
u = await userForToken(msg.token);
}
} catch (e) {
return fatal('authentication failed');
}
let ok = false;
try {
ok = await isInVoice(channelId, u.id);
} catch (e) {
ok = false;
}
if (ws.readyState !== 1) return;
if (!ok) return fatal('join the voice channel first');
clearTimeout(helloTimer);
user = u;
ch = getChannel(channelId);
ch.sockets.add(ws);
lookup(ch);
joinUser(ch, user.id);
if (!ch.room) ensurePoll();
send(ws, { t: 'welcome', user, state: stateOf(ch) });
}
function run(fn) {
try {
const r = fn();
if (r && typeof r.then === 'function') {
r.then(
(res) => res && res.ok === false && res.error && send(ws, { t: 'error', message: String(res.error) }),
(e) => send(ws, { t: 'error', message: String(e.message || e) }),
);
}
} catch (e) {
send(ws, { t: 'error', message: String(e.message || e) });
}
}
ws.on('message', (raw, isBinary) => {
if (isBinary || !msgOk()) return;
let msg;
try {
msg = JSON.parse(raw.toString('utf8'));
} catch (e) {
return;
}
if (!msg || typeof msg !== 'object') return;
switch (msg.t) {
case 'ping':
return send(ws, { t: 'pong', at: msg.at, now: Date.now() });
case 'hello':
return void hello(msg);
case 'cmd': {
if (!user) return;
if (!cmdOk()) return send(ws, { t: 'error', message: 'slow down' });
if (typeof msg.op !== 'string') return;
if (!ch.room) return send(ws, { t: 'error', message: 'nothing is playing' });
const args = msg.args && typeof msg.args === 'object' ? msg.args : {};
return run(() => ch.room.command(msg.op, args, user.id));
}
case 'report': {
if (!user || !ch.room || !reportOk()) return;
const { t, ...data } = msg;
return run(() => ch.room.report(data, user.id));
}
default:
}
});
ws.on('close', () => {
clearTimeout(helloTimer);
if (!user || !ch) return;
ch.sockets.delete(ws);
leaveUser(ch, user.id);
dropChannelIfEmpty(ch);
});
ws.on('error', () => {});
});
server.on('close', () => {
if (pollTimer) clearInterval(pollTimer);
pollTimer = null;
for (const ws of wss.clients) ws.terminate();
wss.close();
for (const ch of channels.values()) {
if (ch.timer) clearTimeout(ch.timer);
if (ch.detach) ch.detach();
}
});
server.wss = wss;
server.channels = channels;
return server;
}
module.exports = { createServer, emptyState };