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.
7.2 KiB
tv-discord v2: watch-party protocol
The Activity is the full bug.tv site (built from the bug-tv repo's packages.web) plus a small overlay script (activity/js/discord.js). Whoever starts an Activity instance is the host. The host's site does everything: search, scraping, source picking and failover. The server relays what the host is doing to everyone else in the instance (the viewers), who mirror it.
There is no bot gateway or slash commands. The bot token is only used for GET /applications/{app}/activity-instances/{instanceId} (membership checks) and the client secret for the OAuth code exchange.
Server (src/server.js)
createServer(cfg, { discordFetch?, now?, log? }) → http.Server.
- HTTP:
- Static files from
cfg.activityDir(the merged site + overlay), with SPA fallback toindex.html. A leading/.proxyis stripped. GET /api/config→{ applicationId, dev }POST /api/token {code}→{ access_token }, via Discord oauth2/token with client credentials.GET /healthz
- Static files from
- WebSocket
/ws(JSON):- client → server
{t:'hello', token, instanceId, channelId?, guildId?}: the server checks the token withGET /users/@me(cached 10 min), then membership:GET /applications/{cfg.applicationId}/activity-instances/{instanceId}withAuthorization: Bot ${cfg.token}. The result listsusers: [id…]and is cached 10s per instance; one refetch is allowed on a miss. If the user isn't in the list →error+ close. In dev (cfg.dev === true),{t:'hello', dev:true, userId, username, instanceId}is accepted without Discord.{t:'route', path}: host only.{t:'play', snapshot}: host only. The server stampssnapshot.at = now()on receipt and stores it.{t:'ping', at}: anyone.- Anything from a non-host apart from
pingis ignored.
- server → client
{t:'welcome', you:{id,username,avatar}, host, members:[{id,username,avatar}], route, play, now}{t:'host', host}: on handover.{t:'members', members}{t:'route', path}and{t:'play', snapshot}: relayed to everyone except the host.{t:'pong', at, now}{t:'error', message}
- client → server
- Hubs: one per
instanceId,{ members (join order), host, route, play }.- The first member is host. When the host's last socket closes, the earliest remaining member becomes host, and everyone gets
host. - A hub is dropped 10 minutes after it empties. If the original host rejoins within that window, they get host back.
- A user with several sockets counts once.
- The first member is host. When the host's last socket closes, the earliest remaining member becomes host, and everyone gets
Snapshot (play)
{ path: "/watch/tv/1399/1/2",
media: { type, id, season, episode },
stream: <bug-tv Stream object as the host's player loaded it> | null,
subtitle: { index, lang, label } | null, // viewers match lang+label, index as fallback
quality: -1 | <level height>, // -1 = auto
audio: -1 | <track index>,
playing: bool, position: seconds, duration: seconds, at: <server ms, stamped by server> }
Viewers compute the target time as position + (playing ? (serverNow - at) / 1000 : 0). Server time comes from pong (median of the last 5 offsets).
Overlay (activity/js/discord.js, bundled with @discord/embedded-app-sdk)
- If not inside Discord (no
frame_id), use dev mode:?user=&instance=, and the server must havecfg.dev. - In Discord:
new DiscordSDK(applicationId)→ready()→patchUrlMappings([{prefix:'/tv',target:'api-tv.bug.tools'},{prefix:'/tmdb',target:'api.themoviedb.org'},{prefix:'/img',target:'image.tmdb.org'}])authorize→POST /api/token→authenticate- WS
hellowithsdk.instanceId.
- Attach to the site:
window.bugtvParty.attach(transport)(see bug-tvdocs/api.md→ "Party"), then feed it server messages throughparty.receive(msg). - UI: a small top-right pill showing member avatars and "👑 name". For viewers it adds a banner "👑 is in control", and
html.party-viewerblocks clicks and inputs outside the player's volume/fullscreen controls. - Reconnect with backoff. On reconnect, resend
hello, and the host resends route and snapshot.
Build (nix/activity.nix)
Start from bug-tv packages.web.override { apiBase = "/tv"; }, then in index.html and 404.html:
- set
<meta name="bug-tv-tmdb" content="/tmdb/3">,<meta name="bug-tv-img" content="/img/t/p/">and<meta name="bug-tv-force-proxy" content="1"> - remove the Google Fonts
<link>tags - append
<link rel="stylesheet" href="/overlay.css">and<script type="module" src="/discord.js">
Then copy in dist/discord.js (esbuild bundle) and activity/overlay.css. For local dev, scripts/build-activity.sh <bug-tv web dir> <out dir> does the same.
Deviations
hostinwelcomeand{t:'host'}is the host's user id (string); details come frommembers.- Avatars:
members[].avataris/api/avatar/<id>(ornullfor dev users). The server proxiescdn.discordapp.com(the Activity CSP blocks it) for users it has seen in a hello, caching the image in memory for 1h; no avatar hash → Discord's default embed avatar. - Hello errors:
missing instanceId,missing token,authentication failed,not in this activity,membership check failed(Discord API error),dev mode is off; all close with code 4001. A 404 from activity-instances counts as "not a member".slow down(rate limit, 30 msgs/s per socket) does not close. - Reclaim: the hub's owner is its first-ever member. If the owner leaves and rejoins within 10 minutes they get host back, even if the hub never emptied.
- Stale snapshots: a
routewhose path differs from the storedplay.pathclears the stored snapshot, so late joiners don't get dragged back to the watch page.{t:'play', snapshot:null}from the host is relayed and clears it too. - Heartbeat: the server pings sockets every 30s and drops dead ones, so a host whose network vanished hands over. The overlay also closes its socket on
pagehide. - Reconnect: after a reconnect the overlay calls
party.resend()when the party has it; otherwise it replays the lastroute/playit sent (advancingpositionby the elapsed time if playing). - Viewer blocking: the overlay blocks pointer/keyboard/form events in the capture phase except inside
.pl-volwrap,[data-party-allow],.pl-btn[aria-label^="Fullscreen"|"Exit fullscreen"]and the overlay itself; keysm/f(and anything with Ctrl/Meta/Alt) pass. Scrolling still works. - Build: the site's
img/is moved tosite-img/(references in*.html/*.cssrewritten), because Discord's/imgmapping to image.tmdb.org would otherwise swallow/img/bug.svg. The TMDB preconnect<link>s are removed as well as Google Fonts. Thebug-tv-apimeta is also set (3rd arg, default/tv), andweb/test/is dropped. - Dev: with
cfg.dev, the server also reverse-proxies/tv/v1/*→cfg.devApiUrl,/tmdb/*→ api.themoviedb.org and/img/*→ image.tmdb.org, so dev uses the same paths as Discord. Only/tv/v1/is proxied, because/tvis also the site's Series route. In Discord, the/tvmapping would catch a full page reload at/tv…; history navigation is unaffected. - Config:
activityDirdefaults to./site.devmode ("dev": trueorBUG_TV_DISCORD_DEV=1) doesn't require Discord credentials.