Files
tv-discord/activity/js/main.js
T

636 lines
20 KiB
JavaScript

/*
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 };