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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-27 08:54:57 -05:00
commit ef7b44f074
36 files changed
+5841

No files matched your search

+146
View File
@@ -0,0 +1,146 @@
: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
@@ -0,0 +1 @@
<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>

After

Width:  |  Height:  |  Size: 2.8 KiB

+64
View File
@@ -0,0 +1,64 @@
<!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>
+635
View File
@@ -0,0 +1,635 @@
/*
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
@@ -0,0 +1,88 @@
/*
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
@@ -0,0 +1,52 @@
/*
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;
}
+1
View File
@@ -0,0 +1 @@
{ "type": "module" }