# 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 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`) ``` { path: "/watch/tv/1399/1/2", media: { type, id, season, episode }, stream: | null, subtitle: { index, lang, label } | null, // viewers match lang+label, index as fallback quality: -1 | , // -1 = auto audio: -1 | , playing: bool, position: seconds, duration: seconds, at: } ``` 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`) 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 "👑 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. ## Build (`nix/activity.nix`) Start from bug-tv `packages.web.override { apiBase = "/tv"; }`, then in `index.html` and `404.html`: - set ``, `` and `` - remove the Google Fonts `` tags - append `` and `