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

+64 -94
View File
@@ -1,104 +1,74 @@
# tv-discord: module and protocol contract
# tv-discord v2: watch-party protocol
Every workstream codes against this file. If you need to deviate, keep it backwards compatible and record it under "Deviations" at the bottom.
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.
## Runtime
- Node 22+, CommonJS in `src/`. Deps: `discord.js` 14, `ws` 8. The Activity bundles `@discord/embedded-app-sdk` with esbuild (`npm run build:activity` → `activity/dist/main.js`).
- The bug-tv API contract is `~/library/repositories/tv/docs/api.md`: `GET /v1/streams` (SSE `meta`/`streams`/`provider`/`done`, or `?format=json`), `GET /v1/prefetch`, and the Stream shape with `playback {kind,url,fallback,status}` (URLs relative to the API base).
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.
## Config (`src/config.js`, already written)
`loadConfig()` reads JSON from `$BUG_TV_DISCORD_CONFIG` (default `./config.json`):
## Server (`src/server.js`)
`createServer(cfg, { discordFetch?, now?, log? })` → `http.Server`.
- **HTTP:**
- Static files from `cfg.activityDir` (the merged site + overlay), with SPA fallback to `index.html`. A leading `/.proxy` is stripped.
- `GET /api/config` → `{ applicationId, dev }`
- `POST /api/token {code}` → `{ access_token }`, via Discord oauth2/token with client credentials.
- `GET /healthz`
- **WebSocket `/ws`** (JSON):
- client → server
- `{t:'hello', token, instanceId, channelId?, guildId?}`: the server checks the token with `GET /users/@me` (cached 10 min), then membership: `GET /applications/{cfg.applicationId}/activity-instances/{instanceId}` with `Authorization: Bot ${cfg.token}`. The result lists `users: [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 stamps `snapshot.at = now()` on receipt and stores it.
- `{t:'ping', at}`: anyone.
- Anything from a non-host apart from `ping` is 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}`
- **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.
## Snapshot (`play`)
```
{ host, port (8791), apiUrl ("http://127.0.0.1:8789", server-side calls), applicationId, guildIds: [],
token | tokenFile, clientSecret | clientSecretFile, tmdbKey | tmdbKeyFile, activityDir (default ./activity),
providers: [] (empty = bug-tv defaults) }
{ 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> }
```
`*File` values are read and trimmed into `token`, `clientSecret` and `tmdbKey`.
Viewers compute the target time as `position + (playing ? (serverNow - at) / 1000 : 0)`. Server time comes from `pong` (median of the last 5 offsets).
## Wiring (`src/index.js`, already written)
```js
const rooms = createRooms(cfg); // src/room.js
const bot = await createBot(cfg, rooms); // src/bot/index.js → { client, isInVoice(channelId, userId), voiceMembers(channelId) }
const server = createServer(cfg, rooms, { isInVoice: bot.isInVoice }); // src/server.js → http.Server
```
## Overlay (`activity/js/discord.js`, bundled with `@discord/embedded-app-sdk`)
1. If not inside Discord (no `frame_id`), use dev mode: `?user=&instance=`, and the server must have `cfg.dev`.
2. 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 `hello` with `sdk.instanceId`.
3. Attach to the site: `window.bugtvParty.attach(transport)` (see bug-tv `docs/api.md` → "Party"), then feed it server messages through `party.receive(msg)`.
4. UI: a small top-right pill showing member avatars and "👑 name". For viewers it adds a banner "👑 <host> is in control", and `html.party-viewer` blocks clicks and inputs outside the player's volume/fullscreen controls.
5. Reconnect with backoff. On reconnect, resend `hello`, and the host resends route and snapshot.
## Rooms (`src/room.js`, workstream A)
`createRooms(cfg)` → `{ get(id), create({ id, guildId, textChannelId }), delete(id), all() }`. `id` is the **voice channel id**.
## 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">`
A room is an EventEmitter:
- `room.state` holds the full server state:
```
{ id, guildId, textChannelId, messageId,
media: { type, tmdb, title, year, poster, backdrop, overview, season, episode, episodeTitle, still, seasons: [{n, count}] } | null,
sources: [Stream] (ranked), scraping: bool, providers: { done, total },
sourceId, failed: [ids], notice: string|null (shown in the embed, e.g. "vidrock failed, trying castle"),
subtitle: -1|index, quality: -1|levelIndex, levels: [{ index, height, bitrate }],
playing: bool, position: seconds, updatedAt: ms (server clock), duration: seconds|0, buffering: bool,
viewers: [userId], leader: userId|null, rev: int }
```
- `room.load({ type, tmdb, season?, episode? })` fetches TMDB metadata, starts the bug-tv SSE scrape, ranks sources and auto-picks one using the web player's rule (≥1080p hls/file at once, else 1.5s after the first playable, else on done). It resets the playback clock.
- `room.command(op, args, userId)` handles these ops:
`play`, `pause`, `toggle`, `seek {t}` (absolute), `seekBy {d}`, `source {id}`, `subtitle {index}`, `quality {index}`, `episode {season, episode}`, `next`, `prev`, `stop`.
- `room.report(data, userId)` takes client reports. Only the leader's `duration`, `levels`, `buffering`, `ended` and `error {fatal, message}` are used, plus a `position` heartbeat every 5s that corrects server drift while playing. A fatal error moves to the next unfailed source and sets `notice`.
- `room.join(userId)` / `room.leave(userId)` keep `viewers` and leader election (first joiner; re-elected on leave).
- `room.publicState(now = Date.now())` returns the state sent to Activity clients: `{ media, stream (selected Stream object or null), subtitle, quality, playing, position, updatedAt, now, duration, viewers, leader, rev, notice }`.
- Events: `'change'` (`state`, `reason`) on every mutation, so the bot re-renders (throttled) and the server broadcasts. `'closed'` fires on stop or idle close.
- Clock: the current time is `position + (playing ? (now - updatedAt) / 1000 : 0)`, clamped to `[0, duration || ∞]`.
- Prefetch: at ≥80% of `duration` it calls `/v1/prefetch` for the next episode once. On the leader's `ended` it moves to the next episode (TV) or pauses at the end (movie).
- Idle: when the bot reports the voice channel empty (`rooms.get(id).setVoiceCount(n)`), the room closes after 2 minutes at 0.
## Bot (`src/bot/*`, workstream A)
- `src/bot/index.js` exports `createBot(cfg, rooms)`. It logs in with intents `Guilds` and `GuildVoiceStates`, registers commands (guild-scoped for `cfg.guildIds`, otherwise global), and handles interactions. It returns `{ client, isInVoice(channelId, userId), voiceMembers(channelId) }`.
- Commands: `/watch query:<string, autocomplete> season:<int?> episode:<int?>`, `/np`, `/stop`.
- Component custom ids are `tv:<action>:<roomId>[:<arg>]`, one action per id:
- Buttons: `tv:toggle`, `tv:seekBy:<±sec>`, `tv:seekModal`, `tv:prev`, `tv:next`, `tv:launch`, `tv:stop`, `tv:episodes`, `tv:sources`.
- Selects: `tv:src` (value = stream id or `page:<n>`), `tv:sub`, `tv:q`, `tv:season`, `tv:ep`.
- Modal: `tv:seekForm` with text input `t` (`1:23:45`, `83m`, `45%`, `90`).
- `tv:launch` answers with interaction response type 12 (`LAUNCH_ACTIVITY`, raw REST `POST /interactions/{id}/{token}/callback` with `{type:12}`) when the clicker is in the room's VC. Otherwise it gives an ephemeral hint.
- The control message is rendered by `src/bot/render.js` `render(room.state) → { embeds, components }` and edited on `'change'`, at most once every 3s plus immediately on source, episode, play or pause changes.
## HTTP + WS server (`src/server.js`, workstream B)
- Static Activity files come from `cfg.activityDir` (`index.html`, `css/`, `js/`, `dist/`, `vendor/`), with SPA fallback to `index.html`.
- `POST /api/token {code}` → `{ access_token }`. It exchanges the code with Discord (`POST https://discord.com/api/oauth2/token`, client credentials, `grant_type=authorization_code`). No redirect_uri is needed for Activities.
- `GET /ws` is a WebSocket using JSON messages:
- **client → server**
- `{ t: "hello", token, channelId }`: the server checks the token with `GET /users/@me`, then `isInVoice(channelId, user.id)`, then `room.join`.
- `{ t: "cmd", op, args }`: forwarded to `room.command`.
- `{ t: "report", ...data }`: forwarded to `room.report`.
- `{ t: "ping", at }`: the server replies with `pong`.
- **server → client**
- `{ t: "welcome", user: {id, username}, state: publicState }`
- `{ t: "state", state: publicState }`: broadcast on every room `'change'`.
- `{ t: "pong", at, now }`: lets the client estimate its clock offset.
- `{ t: "error", message }`, followed by a close for auth failures.
- When no room exists for the channel yet, the welcome state is empty (`media: null`) and the Activity shows "Use /watch in chat to pick something". A later `room` creation for that channel must attach to waiting sockets.
## Activity (`activity/`, workstream B)
- `new DiscordSDK(applicationId)` (the id is injected at serve time via `/api/config` → `{ applicationId }`), then `ready()`, `patchUrlMappings([{prefix:'/tv', target:'api-tv.bug.tools'}, {prefix:'/img', target:'image.tmdb.org'}])`, `authorize({client_id, response_type:'code', prompt:'none', scope:['identify']})`, `POST /api/token`, `authenticate`, then WS `hello` with `channelId: sdk.channelId`.
- Playback goes through bug-tv's `player.js` (copied in at build time to `activity/vendor/bugtv/js/ui/player.js`, with `activity/vendor/bugtv/js/config.js` = the shim exporting `resolveUrl(u)` → relative `/v1/...` becomes `/api/v1/...`). It **always plays the proxied URL**: `playback.fallback` when present, otherwise `playback.url`.
- Sync: the target time is computed from publicState plus the server clock offset. Drift over 1.5s means a hard seek; smaller drift sets `playbackRate` to 0.95–1.05 until within 0.3s.
- The leader sends a `report` with `duration`, `levels` (from hls), `buffering`, `ended`, `error`, and a `position` heartbeat every 5s.
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
### Workstream A (rooms, bug-tv client, bot)
- `createRooms(cfg, { bugtv, now, setTimeout, clearTimeout })`: the optional second arg injects the bug-tv client and the clock (for tests). The registry is an EventEmitter that emits `'created'(room)` and `'deleted'(room)`. `create()` returns the existing room for that id and updates its `textChannelId`. `rooms.lastProvider` is an in-memory `"type:tmdb" → provider` map that feeds the web player's +100 ranking bonus. It is set when the leader reports a duration for the current source.
- `room.command()` is async and never throws. It resolves `{ ok: true }` or `{ ok: false, error }`. `room.load()` resolves once TMDB metadata is in, while the scrape keeps running in the background. `room.clock(now?)`, `room.current()` (the selected Stream), `room.episodeRef(±1)` → `{season, episode}|null`, `room.close(reason)` and `room.voiceCount` are also exposed.
- `publicState()` adds `buffering`. `media` adds `logo`. Image URLs are absolute `https://image.tmdb.org/t/p/...` (the Activity's `/img` mapping rewrites them).
- Autoplay: an auto-picked source starts playing only if someone has the Activity open. Otherwise the room stays paused and starts playing on the first `join`. When the last viewer leaves, a playing room pauses and resumes on the next `join`. An explicit `play` with no viewers still plays.
- `report()` also accepts an optional `sourceId`. A report whose `sourceId` differs from the current source is ignored, so a late error from the old source doesn't fail over twice. The `position` heartbeat corrects the clock only when the drift is over 1s, and is ignored for 3s after any clock-changing command so a stale heartbeat can't undo a seek. Reports from anyone except the leader are ignored entirely (return `false`).
- `'change'` reasons: `load meta providers sources scrape-done source play pause seek subtitle quality duration levels buffering drift ended notice join leave leader stop idle`. Failover emits `source`. The bot edits immediately on `load source play pause stop idle ended`, and otherwise at most every 3s. It also refreshes every 15s while playing so the progress bar moves.
- Episodes mode shows 4 rows (two button rows, Season select, Episode select) and hides Subtitles/Quality. The Episode select pages with `page:<startIndex>` values ("Earlier/Later episodes…"). Movies have no Episodes button, and Prev/Next are disabled for them.
- The seek modal also accepts `90s`, `1h20m` and relative `+5m`/`-30` (→ `seekBy`).
- `/watch` with free text (no autocomplete pick) uses the first TMDB `search/multi` result. A new `/watch` or `/np` posts a new control message and deletes the old one. Control-message edits go through `channel.messages.edit`. If that fails, they fall back to the most recent interaction webhook (valid for about 15 minutes).
- `tv:launch` uses discord.js 14.27's `interaction.launchActivity()` (callback type 12), with the raw REST `{type:12}` callback only as a fallback.
- `createBot()` also returns `ctx` (internals for tests). `src/bot/updater.js` is an extra module. `package.json`'s test script became `node --test 'test/**/*.test.js'`, because Node 24 rejects a bare directory argument.
### Workstream B (server, Activity)
- **URL mapping prefix for bug-tv is `/tv`, not `/api`.** Discord matches the most specific prefix, so `/api → api-tv.bug.tools` would swallow our own `/api/token` and `/api/config`. Portal URL mappings: `/` → `tv-activity.bug.tools`, `/tv` → `api-tv.bug.tools`, `/img` → `image.tmdb.org`. Inside Discord, `resolveUrl('/v1/…')` returns the same-origin `/tv/v1/…`. The legacy `/.proxy/` prefix is not used (SDK 2.5's `patchUrlMappings` doesn't emit it), but the server strips a leading `/.proxy` from HTTP and WS paths anyway. The Activity calls `patchUrlMappings` with `/tv` and `/img`, which only matters for absolute URLs. TMDB images are rewritten to `/img/…` explicitly.
- Dev mode (no `frame_id`): bug-tv base = `?api=<url>` (default `http://127.0.0.1:8789`), and `hello` is `{t:'hello', dev:true, userId, channelId, username?}` from `?channel=&user=&name=`. The server accepts it only when `cfg.dev === true` (a new optional config key, server-only). `isInVoice` is still checked.
- `createServer(cfg, rooms, { isInVoice, discordFetch, log })`: `discordFetch` defaults to global `fetch`. `GET /api/config` also returns `dev`. `GET /healthz` → `{ok:true}`. The returned server has `.wss` and `.channels` for tests.
- Room attach: the server listens for rooms' `'created'` event and also polls `rooms.get()` every 2s for channels with waiting sockets. On a room's `'closed'` it broadcasts an empty state (`media:null`) and the sockets wait for the next room. Several sockets of one user in one channel call `room.join` once and `room.leave` when the last one closes. `'change'` broadcasts are coalesced within 50ms. A `cmd` result of `{ok:false, error}` is sent back to that socket as `{t:'error', message}`. Limits: 10 cmd/s and 20 report/s per socket (excess cmds → `{t:'error', message:'slow down'}`), 16 KB max frame, and a 15s hello timeout. Auth failures close with code 4001.
- Reports carry `sourceId` (the stream the player has loaded). `buffering:true` is sent only after a 1s stall. The position heartbeat is skipped while stalled or seeking.
- Vendoring: `scripts/vendor-bugtv.sh <bug-tv web dir> [activity dir]` must run **before** `npm run build:activity`. It creates `activity/vendor/bugtv/{js/ui/player.js, js/config.js (shim → activity/js/urls.js), vendor/hls.min.js}`. esbuild bundles player.js and the shim into `dist/main.js`. Because the bundled `import.meta.url` no longer points at player.js, main.js preloads `window.Hls` from `/vendor/bugtv/vendor/hls.min.js` before loading an HLS stream. `activity/vendor/bugtv/` is generated, so it should be gitignored like `activity/dist/`. `activity/package.json` (`{"type":"module"}`) lets `node --test` import `activity/js/sync.js` without warnings.
- Activity UX: a single click on the video only reveals the controls, so a touch can't pause the room. Double-click, Space or k toggles; ←/→ or j/l → `seekBy ∓10`. When autoplay is refused, the Activity retries muted and shows "Unmute". If that is refused too, it shows "Click to join playback". A follower whose player fails fatally reloads once after 2s and doesn't report.
- **`host`** in `welcome` and `{t:'host'}` is the host's user id (string); details come from `members`.
- **Avatars:** `members[].avatar` is `/api/avatar/<id>` (or `null` for dev users). The server proxies `cdn.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 `route` whose path differs from the stored `play.path` clears 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 last `route`/`play` it sent (advancing `position` by 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; keys `m`/`f` (and anything with Ctrl/Meta/Alt) pass. Scrolling still works.
- **Build:** the site's `img/` is moved to `site-img/` (references in `*.html`/`*.css` rewritten), because Discord's `/img` mapping to image.tmdb.org would otherwise swallow `/img/bug.svg`. The TMDB preconnect `<link>`s are removed as well as Google Fonts. The `bug-tv-api` meta is also set (3rd arg, default `/tv`), and `web/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 `/tv` is also the site's Series route. In Discord, the `/tv` mapping would catch a full page reload at `/tv…`; history navigation is unaffected.
- **Config:** `activityDir` defaults to `./site`. `dev` mode (`"dev": true` or `BUG_TV_DISCORD_DEV=1`) doesn't require Discord credentials.