/* discord.js — the watch-party overlay on top of the bug.tv site (docs/protocol.md "Overlay"). Bundled with @discord/embedded-app-sdk by esbuild into /discord.js. - Inside Discord (?frame_id=…): SDK ready → patchUrlMappings → authorize/token/authenticate → WS /ws hello {token, instanceId, channelId, guildId}. - Outside Discord (dev): ?user=&instance=[&name=], only when /api/config says dev. Without those params the overlay stays out of the way and the site runs solo. - Transport for bug-tv's party layer (window.bugtvParty / 'bugtv:party-ready'): party.attach({ send(type, data) }) and party.receive(msg) for every server message. - UI: members pill, "👑 is in control" banner for viewers, toasts; viewers get html.party-viewer and their clicks/keys are blocked except volume/mute/fullscreen (m, f). */ import { DiscordSDK, patchUrlMappings } from '@discord/embedded-app-sdk'; const params = new URLSearchParams(location.search); const inDiscord = params.has('frame_id'); const PING_MS = 5000; const MAX_BACKOFF_MS = 15000; const ALLOW = '.pl-volwrap, [data-party-allow], .pl-btn[aria-label^="Fullscreen"], .pl-btn[aria-label^="Exit fullscreen"], .bp-root'; const ALLOWED_KEYS = new Set(['m', 'M', 'f', 'F']); const TOAST_MS = 3500; /* ---- state --------------------------------------------------------------- */ let ws = null; let hello = null; let me = null; let hostId = null; let members = []; let welcomed = 0; // number of welcomes so far (>1 → this is a reconnect) let fatal = false; let backoff = 1000; let pingTimer = null; let party = null; const pending = []; // server messages received before the party layer appeared // last route/play this client published, replayed after a reconnect if the party can't resend const lastSent = { route: null, play: null, playAt: 0 }; const isHost = () => !!me && me.id === hostId; const memberById = (id) => members.find((m) => m.id === id) || null; const nameOf = (id) => (memberById(id) || {}).username || 'someone'; /* ---- party layer --------------------------------------------------------- */ const transport = { send(type, data) { const msg = { ...(data && typeof data === 'object' ? data : {}), t: type }; if (type === 'route') lastSent.route = msg; else if (type === 'play') { lastSent.play = msg; lastSent.playAt = performance.now(); } if (ws && ws.readyState === 1 && me) ws.send(JSON.stringify(msg)); }, }; function toParty(msg) { if (!party) { pending.push(msg); if (pending.length > 200) pending.splice(0, pending.length - 200); return; } try { party.receive(msg); } catch (e) { console.warn('[bugtv-party] receive failed', e); } } function withParty(p) { if (party || !p || typeof p.attach !== 'function') return; party = p; try { party.attach(transport); } catch (e) { console.warn('[bugtv-party] attach failed', e); } for (const m of pending.splice(0)) toParty(m); } function findParty() { if (window.bugtvParty) return withParty(window.bugtvParty); window.addEventListener('bugtv:party-ready', (e) => withParty((e && e.detail) || window.bugtvParty), { once: true }); } /** The host (again) after a reconnect / handover: make sure viewers get the current state. */ function republish(reconnect) { if (party && typeof party.resend === 'function') { try { party.resend(); return; } catch (e) { console.warn('[bugtv-party] resend failed', e); } } if (!reconnect || !ws || ws.readyState !== 1) return; if (lastSent.route) ws.send(JSON.stringify(lastSent.route)); if (lastSent.play) { const p = lastSent.play; let snap = p.snapshot; if (snap && snap.playing && typeof snap.position === 'number') { snap = { ...snap, position: snap.position + (performance.now() - lastSent.playAt) / 1000 }; } ws.send(JSON.stringify({ ...p, snapshot: snap })); } } /* ---- connection ---------------------------------------------------------- */ function wsUrl() { return `${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/ws`; } function ping() { if (ws && ws.readyState === 1) ws.send(JSON.stringify({ t: 'ping', at: Date.now() })); } function connect() { setConn('connecting'); const sock = new WebSocket(wsUrl()); ws = sock; sock.onopen = () => { sock.send(JSON.stringify(hello)); }; sock.onmessage = (ev) => { let m; try { m = JSON.parse(ev.data); } catch (e) { return; } if (!m || typeof m !== 'object') return; onServer(m); }; sock.onclose = (ev) => { if (ws !== sock) return; clearInterval(pingTimer); pingTimer = null; const wasMe = me; me = null; if (fatal || ev.code === 4001) { fatal = true; setConn('error'); if (wasMe) applyRole(); return; } setConn('connecting', 'Reconnecting…'); setTimeout(connect, backoff + Math.random() * 300); backoff = Math.min(backoff * 2, MAX_BACKOFF_MS); }; sock.onerror = () => {}; } function onServer(m) { switch (m.t) { case 'welcome': { welcomed++; backoff = 1000; me = m.you; const prevHost = hostId; hostId = m.host; const prev = members; members = Array.isArray(m.members) ? m.members : []; setConn('live'); toParty(m); // clock samples: a few quick pings, then every 5s ping(); setTimeout(ping, 400); setTimeout(ping, 1200); clearInterval(pingTimer); pingTimer = setInterval(ping, PING_MS); if (welcomed > 1) diffMembers(prev, members); if (welcomed > 1 && prevHost !== hostId) hostToast(); render(); applyRole(); if (isHost()) republish(welcomed > 1); return; } case 'members': { const prev = members; members = Array.isArray(m.members) ? m.members : []; diffMembers(prev, members); toParty(m); render(); return; } case 'host': { const was = isHost(); hostId = m.host; toParty(m); hostToast(); render(); applyRole(); if (!was && isHost()) republish(false); return; } case 'error': toParty(m); if (/slow down/.test(m.message || '')) return; fatal = true; setConn('error', errorText(m.message)); toast(errorText(m.message), 'error'); return; default: // route, play, pong, … toParty(m); } } function errorText(msg) { const s = String(msg || 'error'); if (/not in this activity/.test(s)) return 'Not part of this Activity — reopen it from the call.'; if (/dev mode/.test(s)) return 'Dev mode is off on the server.'; if (/authentication/.test(s)) return 'Discord sign-in failed.'; return s; } /* ---- auth ---------------------------------------------------------------- */ async function discordHello(cfg) { const sdk = new DiscordSDK(cfg.applicationId); await sdk.ready(); // /api and /ws stay on the root mapping (our server); relative /tv, /tmdb, /img already hit // their mappings — this rewrites absolute URLs of those hosts. patchUrlMappings([ { prefix: '/tv', target: 'api-tv.bug.tools' }, { prefix: '/tmdb', target: 'api.themoviedb.org' }, { prefix: '/img', target: 'image.tmdb.org' }, ]); const { code } = await sdk.commands.authorize({ client_id: cfg.applicationId, response_type: 'code', state: '', prompt: 'none', scope: ['identify'], }); const r = await fetch('/api/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }); if (!r.ok) throw new Error(`token exchange failed (${r.status})`); const { access_token } = await r.json(); await sdk.commands.authenticate({ access_token }); if (!sdk.instanceId) throw new Error('no activity instance'); return { t: 'hello', token: access_token, instanceId: sdk.instanceId, channelId: sdk.channelId || undefined, guildId: sdk.guildId || undefined, }; } function devHello(cfg) { const userId = params.get('user'); const instanceId = params.get('instance'); if (!userId || !instanceId || !cfg.dev) return null; return { t: 'hello', dev: true, userId, instanceId, username: params.get('name') || `dev-${userId}` }; } /* ---- UI ------------------------------------------------------------------ */ const ui = {}; let bannerCollapsed = false; let connState = 'connecting'; let connText = 'Connecting…'; function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; } function buildUi() { const root = el('div', 'bp-root'); root.setAttribute('aria-live', 'polite'); root.dataset.conn = 'connecting'; const pill = el('button', 'bp-pill bp-glass'); pill.type = 'button'; pill.setAttribute('aria-label', 'Watch party'); const dot = el('span', 'bp-dot'); const avatars = el('span', 'bp-avatars'); const host = el('span', 'bp-host', 'Connecting…'); pill.append(dot, avatars, host); const list = el('div', 'bp-list bp-glass'); list.hidden = true; const banner = el('div', 'bp-banner bp-glass'); banner.hidden = true; const bannerText = el('span', 'bp-banner__text'); const x = el('button', 'bp-x', '×'); x.type = 'button'; x.setAttribute('aria-label', 'Hide'); x.title = 'Hide (click the pill to show again)'; banner.append(bannerText, x); const toasts = el('div', 'bp-toasts'); root.append(pill, list, banner, toasts); document.body.appendChild(root); pill.addEventListener('click', () => { if (!isHost() && me && bannerCollapsed) { bannerCollapsed = false; render(); return; } list.hidden = !list.hidden; render(); }); x.addEventListener('click', () => { bannerCollapsed = true; render(); }); document.addEventListener('click', (e) => { if (!list.hidden && !root.contains(e.target)) { list.hidden = true; } }); Object.assign(ui, { root, pill, avatars, host, list, banner, bannerText, toasts }); } function avatar(m, extra = '') { const a = el('span', `bp-av${extra}`); const initial = (m.username || '?').trim().charAt(0) || '?'; if (m.avatar) { const img = new Image(); img.alt = ''; img.decoding = 'async'; img.referrerPolicy = 'no-referrer'; img.onerror = () => { img.remove(); a.textContent = initial; }; img.src = m.avatar; a.appendChild(img); } else { a.textContent = initial; a.style.background = `hsl(${hue(m.id)} 45% 32%)`; } a.title = m.username || ''; return a; } function hue(s) { let h = 0; for (const c of String(s || '')) h = (h * 31 + c.charCodeAt(0)) >>> 0; return h % 360; } function setConn(state, text) { connState = state; connText = text || (state === 'connecting' ? 'Connecting…' : state === 'error' ? 'Disconnected' : ''); render(); } function render() { if (!ui.root) return; ui.root.dataset.conn = connState; ui.avatars.replaceChildren(); const shown = members.slice(0, 5); for (const m of shown) ui.avatars.appendChild(avatar(m, m.id === hostId ? ' is-host' : '')); if (members.length > shown.length) ui.avatars.appendChild(el('span', 'bp-more', `+${members.length - shown.length}`)); const live = connState === 'live' && me; ui.host.classList.toggle('is-me', !!live && isHost()); ui.host.textContent = live ? `👑 ${isHost() ? 'You' : nameOf(hostId)}` : connText; ui.pill.title = live ? `${members.length} watching · ${members.map((m) => m.username).join(', ')}` : connText; // member list if (!ui.list.hidden) { ui.list.replaceChildren(); for (const m of members) { const row = el('div', 'bp-row'); row.append(avatar(m, m.id === hostId ? ' is-host' : ''), el('span', 'bp-row__name', m.username)); const tags = [m.id === hostId ? '👑 host' : '', me && m.id === me.id ? 'you' : ''].filter(Boolean).join(' · '); if (tags) row.appendChild(el('span', 'bp-row__tag', tags)); ui.list.appendChild(row); } if (!live) ui.list.appendChild(el('div', 'bp-status', connText)); else if (isHost()) ui.list.appendChild(el('div', 'bp-status', 'You are in control — everyone follows what you watch.')); } // viewer banner const viewer = !!live && !isHost(); ui.banner.hidden = !viewer || bannerCollapsed; if (viewer) { ui.bannerText.replaceChildren( document.createTextNode('👑 '), el('b', '', nameOf(hostId)), document.createTextNode(' is in control'), el('span', 'bp-banner__sub', 'You can change volume and fullscreen.'), ); } } function toast(text, kind = '') { if (!ui.toasts) return; const t = el('div', `bp-toast bp-glass${kind ? ` bp-toast--${kind}` : ''}`, text); ui.toasts.appendChild(t); while (ui.toasts.children.length > 3) ui.toasts.firstChild.remove(); requestAnimationFrame(() => t.classList.add('is-shown')); setTimeout(() => { t.classList.remove('is-shown'); setTimeout(() => t.remove(), 300); }, TOAST_MS); } function hostToast() { if (!me || !hostId) return; toast(isHost() ? '👑 You are in control now' : `👑 ${nameOf(hostId)} is in control`, 'host'); } function diffMembers(prev, next) { if (!me) return; const before = new Set(prev.map((m) => m.id)); const after = new Set(next.map((m) => m.id)); for (const m of next) if (!before.has(m.id) && m.id !== me.id) toast(`${m.username} joined`); for (const m of prev) if (!after.has(m.id) && m.id !== me.id) toast(`${m.username} left`); } /* ---- viewer input blocking ----------------------------------------------- */ const viewerNow = () => document.documentElement.classList.contains('party-viewer'); function applyRole() { const viewer = !!me && !isHost(); document.documentElement.classList.toggle('party-viewer', viewer); document.documentElement.classList.toggle('party-host', !!me && isHost()); if (viewer) { const a = document.activeElement; if (a && a !== document.body && !allowed(a) && typeof a.blur === 'function') a.blur(); } } function allowed(target) { return !!(target && target.closest && target.closest(ALLOW)); } function blockPointer(e) { if (!viewerNow() || allowed(e.target)) return; e.stopImmediatePropagation(); // touchstart must stay passive-compatible so scrolling keeps working if (e.cancelable && e.type !== 'touchstart' && e.type !== 'touchmove') e.preventDefault(); } function editable(t) { return !!(t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))); } function blockKey(e) { if (!viewerNow() || allowed(e.target)) return; if (e.ctrlKey || e.metaKey || e.altKey) return; // browser / Discord shortcuts if (ALLOWED_KEYS.has(e.key) && !editable(e.target)) return; e.stopImmediatePropagation(); // keep native scrolling keys (arrows, space, page up/down) on the page itself if (editable(e.target) || e.key === 'Enter' || e.key === 'Escape' || e.key === 'Tab' || e.key.length === 1) { if (e.key !== ' ' || editable(e.target)) e.preventDefault(); } } function blockForm(e) { if (!viewerNow() || allowed(e.target)) return; e.stopImmediatePropagation(); if (e.cancelable) e.preventDefault(); } function installBlocking() { for (const t of ['click', 'dblclick', 'auxclick', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'contextmenu', 'touchstart', 'touchend']) { window.addEventListener(t, blockPointer, { capture: true, passive: false }); } for (const t of ['keydown', 'keypress', 'keyup']) window.addEventListener(t, blockKey, { capture: true }); for (const t of ['submit', 'input', 'change', 'beforeinput']) window.addEventListener(t, blockForm, { capture: true }); window.addEventListener( 'focusin', (e) => { if (viewerNow() && editable(e.target) && !allowed(e.target)) e.target.blur(); }, true, ); } /* ---- boot ---------------------------------------------------------------- */ async function boot() { let cfg; try { cfg = await (await fetch('/api/config')).json(); } catch (e) { console.warn('[bugtv-party] no /api/config — overlay off'); return; } if (!inDiscord) { hello = devHello(cfg); if (!hello) return; // plain site, nothing to do } buildUi(); installBlocking(); findParty(); if (inDiscord) { try { hello = await discordHello(cfg); } catch (e) { console.warn('[bugtv-party] discord auth failed', e); setConn('error', `Discord: ${e.message || e}`); return; } } connect(); } // leaving the page (or Discord closing the iframe): close now so the host hands over at once let hidden = false; window.addEventListener('pagehide', () => { if (!ws) return; hidden = true; fatal = true; ws.close(1000, 'bye'); }); // restored from the back/forward cache: join again window.addEventListener('pageshow', (e) => { if (!e.persisted || !hidden || !hello) return; hidden = false; fatal = false; connect(); }); if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once: true }); else boot();