Files
tv-discord/docs/protocol.md
T

105 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# tv-discord: module and protocol contract
Every workstream codes against this file. If you need to deviate, keep it backwards compatible and record it under "Deviations" at the bottom.
## 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).
## Config (`src/config.js`, already written)
`loadConfig()` reads JSON from `$BUG_TV_DISCORD_CONFIG` (default `./config.json`):
```
{ 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) }
```
`*File` values are read and trimmed into `token`, `clientSecret` and `tmdbKey`.
## 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
```
## Rooms (`src/room.js`, workstream A)
`createRooms(cfg)` → `{ get(id), create({ id, guildId, textChannelId }), delete(id), all() }`. `id` is the **voice channel id**.
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.
## 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.