14 KiB
14 KiB
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.js14,ws8. The Activity bundles@discord/embedded-app-sdkwith esbuild (npm run build:activity→activity/dist/main.js). - The bug-tv API contract is
~/library/repositories/tv/docs/api.md:GET /v1/streams(SSEmeta/streams/provider/done, or?format=json),GET /v1/prefetch, and the Stream shape withplayback {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)
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.stateholds 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'sduration,levels,buffering,endedanderror {fatal, message}are used, plus apositionheartbeat every 5s that corrects server drift while playing. A fatal error moves to the next unfailed source and setsnotice.room.join(userId)/room.leave(userId)keepviewersand 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
durationit calls/v1/prefetchfor the next episode once. On the leader'sendedit 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.jsexportscreateBot(cfg, rooms). It logs in with intentsGuildsandGuildVoiceStates, registers commands (guild-scoped forcfg.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 orpage:<n>),tv:sub,tv:q,tv:season,tv:ep. - Modal:
tv:seekFormwith text inputt(1:23:45,83m,45%,90).
- Buttons:
tv:launchanswers with interaction response type 12 (LAUNCH_ACTIVITY, raw RESTPOST /interactions/{id}/{token}/callbackwith{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.jsrender(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 toindex.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 /wsis a WebSocket using JSON messages:- client → server
{ t: "hello", token, channelId }: the server checks the token withGET /users/@me, thenisInVoice(channelId, user.id), thenroom.join.{ t: "cmd", op, args }: forwarded toroom.command.{ t: "report", ...data }: forwarded toroom.report.{ t: "ping", at }: the server replies withpong.
- 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 laterroomcreation for that channel must attach to waiting sockets.
- client → server
Activity (activity/, workstream B)
new DiscordSDK(applicationId)(the id is injected at serve time via/api/config→{ applicationId }), thenready(),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 WShellowithchannelId: sdk.channelId.- Playback goes through bug-tv's
player.js(copied in at build time toactivity/vendor/bugtv/js/ui/player.js, withactivity/vendor/bugtv/js/config.js= the shim exportingresolveUrl(u)→ relative/v1/...becomes/api/v1/...). It always plays the proxied URL:playback.fallbackwhen present, otherwiseplayback.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
playbackRateto 0.95–1.05 until within 0.3s. - The leader sends a
reportwithduration,levels(from hls),buffering,ended,error, and apositionheartbeat 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 itstextChannelId.rooms.lastProvideris an in-memory"type:tmdb" → providermap 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)androom.voiceCountare also exposed.publicState()addsbuffering.mediaaddslogo. Image URLs are absolutehttps://image.tmdb.org/t/p/...(the Activity's/imgmapping 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 nextjoin. An explicitplaywith no viewers still plays. report()also accepts an optionalsourceId. A report whosesourceIddiffers from the current source is ignored, so a late error from the old source doesn't fail over twice. Thepositionheartbeat 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 (returnfalse).'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 emitssource. The bot edits immediately onload 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,1h20mand relative+5m/-30(→seekBy). /watchwith free text (no autocomplete pick) uses the first TMDBsearch/multiresult. A new/watchor/npposts a new control message and deletes the old one. Control-message edits go throughchannel.messages.edit. If that fails, they fall back to the most recent interaction webhook (valid for about 15 minutes).tv:launchuses discord.js 14.27'sinteraction.launchActivity()(callback type 12), with the raw REST{type:12}callback only as a fallback.createBot()also returnsctx(internals for tests).src/bot/updater.jsis an extra module.package.json's test script becamenode --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.toolswould swallow our own/api/tokenand/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'spatchUrlMappingsdoesn't emit it), but the server strips a leading/.proxyfrom HTTP and WS paths anyway. The Activity callspatchUrlMappingswith/tvand/img, which only matters for absolute URLs. TMDB images are rewritten to/img/…explicitly. - Dev mode (no
frame_id): bug-tv base =?api=<url>(defaulthttp://127.0.0.1:8789), andhellois{t:'hello', dev:true, userId, channelId, username?}from?channel=&user=&name=. The server accepts it only whencfg.dev === true(a new optional config key, server-only).isInVoiceis still checked. createServer(cfg, rooms, { isInVoice, discordFetch, log }):discordFetchdefaults to globalfetch.GET /api/configalso returnsdev.GET /healthz→{ok:true}. The returned server has.wssand.channelsfor tests.- Room attach: the server listens for rooms'
'created'event and also pollsrooms.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 callroom.joinonce androom.leavewhen the last one closes.'change'broadcasts are coalesced within 50ms. Acmdresult 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:trueis 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 beforenpm run build:activity. It createsactivity/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 intodist/main.js. Because the bundledimport.meta.urlno longer points at player.js, main.js preloadswindow.Hlsfrom/vendor/bugtv/vendor/hls.min.jsbefore loading an HLS stream.activity/vendor/bugtv/is generated, so it should be gitignored likeactivity/dist/.activity/package.json({"type":"module"}) letsnode --testimportactivity/js/sync.jswithout 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.