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

-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" }