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:
1 parent
4d900c5b56
commit
7de90b5b7c
39 files changed
+1620
-4372
No files matched your search
+305
-213
@@ -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 };
|
||||
Reference in new issue
Block a user