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.
75 lines
7.2 KiB
Markdown
75 lines
7.2 KiB
Markdown
# 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: <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`)
|
|
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.
|
|
|
|
## 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
|
|
- **`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.
|