Files
2026-10-27 05:49:38 -05:00

224 lines
16 KiB
Markdown
Raw Permalink 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.
# bug tv v5 — API & module contract
This is the single source of truth every workstream codes against. If you need to
deviate, keep the deviation backwards compatible and note it at the bottom of this file.
## Runtime
- Node 22+, CommonJS in `src/` (providers are CommonJS). No TypeScript, no bundler.
- npm deps allowed: `cheerio-without-node-native`, `crypto-js` (providers), `undici`
(keep-alive agent), `webtorrent` (torrents). `ffmpeg`/`ffprobe` come from PATH
(`cfg.remux.ffmpeg` / `cfg.remux.ffprobe`).
- Static site in `web/` is vanilla ES modules (`<script type="module">`), no build step.
## Server wiring (already written — `src/server.js`)
- Each `src/routes/<name>.js` exports `{ routes: [{ method, path, handler(req, res, ctx) }], init?(cfg) }`.
`path` is an exact string or a RegExp; capture groups → `ctx.params` (URI-decoded).
`ctx = { cfg, url, params }`. Loaded modules: `health providers streams proxy torrent remux subs openapi`.
- Helpers in `src/http.js`: `send(req,res,status,body,type,extraHeaders)` (auto br/gzip for text >1KB),
`json(req,res,status,obj)`, `error(req,res,status,msg,extra)`, `sse(req,res)` → `{event(name,data), close(), closed}`, `CORS` headers object.
- `src/sign.js`: `sign(obj) → token`, `verify(token) → obj|null` (HMAC, URL-safe, no `/`).
- `src/config.js` `loadConfig()` → cfg:
```
{ host, port, tmdbKey, enabledProviders: [..] ([] = all), disabledProviders: [..] (default ["torrentio"]), providerSettings: {..} (→ global.SCRAPER_SETTINGS),
timeoutMs, workers (0 = auto, min(cpus,4)), cacheTtlSec, secret,
torrent: { enable, cacheDir, maxSizeGB }, remux: { enable, ffmpeg, ffprobe },
filters: { minQuality, audioCodec, subtitles, subtitleLang } }
```
Config file path: `$BUG_TV_CONFIG` or `./config.json`.
## Signed URL formats (owned by media workstream, consumed by scrape workstream)
All are relative to the API base; the client resolves them against its configured base.
| Purpose | URL | Token payload |
|---|---|---|
| proxy (any http media, playlists, keys, segments) | `/v1/p/<token>/<path-and-query-of-upstream>` | `{ o: "https://upstream.origin", h: {headers} }` |
| remux (mkv/avi/etc → fragmented MP4) | `/v1/remux/<token>?start=<sec>` | `{ u: "absolute upstream url", h: {headers} }` |
| remux probe | `/v1/remux/<token>/probe` → `{ duration, video:{codec,width,height}, audio:[{index,codec,lang,channels}], subtitles:[{index,codec,lang,title}] }` | same |
| torrent stream | `/v1/torrent/<token>/stream?start=<sec>` | `{ m: "magnet:…", s?: season, e?: episode, f?: fileIdx }` |
| torrent status | `/v1/torrent/<token>/status` → `{ ready, name, file:{idx,name,size,container,remux}, peers, downSpeed, progress, buffered }` | same |
| torrent files | `/v1/torrent/<token>/files` → `{ files:[{idx,name,size}] }` | same |
| subtitles → VTT | `/v1/subs/<token>` (always `text/vtt`; SRT/ASS converted) | `{ u, h }` |
Proxy rules: path-based so relative URIs inside m3u8 resolve to the same token naturally;
only absolute/cross-origin URIs inside playlists are rewritten (new token). Range requests are
passed through. Playlists may be cached ~5s; segments are never buffered in memory (stream pipe).
Remux responses set header `X-Bug-Tv-Offset: <start>` so the player can offset its clock;
seeking = reload with `?start=`. Torrent `/stream` range-serves browser-native files (mp4/webm) and
remuxes others (honouring `?start=`); `status.file.remux` tells the client which mode it is.
`src/media/playback.js` (media workstream) exports
`playbackFor(stream) → { kind, url, fallback?, status? }` and `subtitleUrl(sub, headers) → string`,
called by the scrape workstream during normalization:
- `kind`: `"hls" | "file" | "remux" | "torrent"`
- `hls`/`file`: if the stream needs no headers beyond User-Agent, `url` = raw upstream URL (direct
play, zero server cost) and `fallback` = proxy URL; otherwise `url` = proxy URL, no fallback.
- `remux`: types mkv/avi/other non-browser containers → `url` = remux URL.
- `torrent`: `magnet:` URLs (or `infoHash`) → `url` = torrent stream URL, `status` = status URL.
## Endpoints
### `GET /v1/streams?tmdb=<id>&type=movie|tv&season=&episode=&providers=a,b`
Default response is **SSE**. Events, in order:
- `meta` → `{ tmdb, type, season, episode, providers: [names], timeoutMs, cached: [names] }`
- `streams` (0..n, one per provider that returned something) → `{ provider, ms, streams: [Stream] }`
- `provider` (one per provider) → `{ name, status: "ok"|"empty"|"error"|"timeout", ms, count, error? }`
- `done` → `{ total, ms }` then the connection closes.
Cached provider results are emitted immediately. Client disconnect aborts outstanding scrapes
whose results won't be cached (scrapes still in flight are allowed to finish into the cache).
`?format=json` or `Accept: application/json` (without `text/event-stream`) → aggregated:
`{ tmdb_id, type, season, episode, total, streams: [Stream], providerErrors: {name: msg} }`.
**Stream**:
```
{ id, // stable hash of provider+url
provider, name, title,
quality, // "1080p" | "2160p" | "" …
pixels, // 2160|1080|720|480|null (parsed from quality, else name/title)
audio, // aac|ac3|dts|opus|flac|mp3|multi|null
type, // m3u8|mp4|webm|mkv|avi|magnet|other
size, // bytes (number) or 0
sizeText, // human string if provider only gave text
language, // "" if unknown
seeds, // number|null (torrents)
subtitles: [{ url /* /v1/subs/… */, lang, label }],
playback: { kind, url, fallback?, status? } }
```
Ordering within an event: pixels desc, then provider health score.
### `GET /v1/prefetch?<same params as streams>` → `202 { queued: [names] }`
Starts the scrape in the background to fill the cache (used for next episode).
### `GET /v1/providers`
`{ defaults: [names], providers: [{ id, name, enabled, types, formats, language, logo, health: { ok, fail, timeouts, avgMs, p90Ms } }] }`
(metadata from `providers/manifest.json`).
### `GET /healthz` → `{ ok: true }`
### `GET /` Swagger UI, `GET /api.json` OpenAPI spec (`src/routes/openapi.js`).
## Scrape internals (scrape workstream)
- Worker pool (`worker_threads`), providers `require()`d once per worker at boot.
- `global.SCRAPER_SETTINGS = cfg.providerSettings` in every worker.
- Fetch shim in workers: any `api.themoviedb.org/3/...` request is answered from a cache keyed by
path+query minus `api_key` (seeded by the main thread with details + external_ids for the current
title, shared cache for everything else); per-fetch timeout; all fetches of a job abort when the job
is cancelled; keep-alive undici dispatcher.
- Adaptive per-provider budget from health stats (p90 × 1.5, clamped to [3s, cfg.timeoutMs]).
- Result cache per `(provider, tmdb, type, season, episode)` for `cfg.cacheTtlSec`; in-flight dedupe.
## Web (frontend workstreams)
ES modules under `web/js/`. Shared modules (owned by the UI-shell workstream; exports are frozen
as listed — add, don't rename):
- `config.js`: `getBase(), setBase(v), getTmdbKey(), setTmdbKey(v), getProviders(), setProviders(list), resolveUrl(relOrAbs)` (resolves API-relative URLs against `getBase()`).
- `storage.js`: resume — `resume.get(key), resume.save(record), resume.remove(key), resume.list(), resume.latestPerShow(), keyFor({type,tmdbId,season,episode})` (record shape as in v4, key `bug-tv.resume.v1` kept);
my list — `myList.has(type,id), myList.toggle(item), myList.all()`;
prefs — `prefs.get(name, fallback), prefs.set(name, value)` (subtitle lang, volume, autoplay-next, …).
- `tmdb.js` (direct browser → TMDB, cached in memory): `trending(type, window), popular(type), topRated(type), discover(type, params), details(type, id)` (append `images,credits,similar,recommendations,external_ids`), `season(tvId, n), search(q)`, image helpers `img(path, size)`.
- `router.js`: history router; `navigate(path)`, routes:
`/` home, `/title/:type/:id` title page, `/watch/:type/:id[/:season/:episode]` player, `/search?q=`,
`/list` my list, `/settings`. Static hosting fallback: `404.html` = copy of `index.html`, and hash
fallback (`#/title/…`) must work when served from `file://` or a host without rewrites.
- `ui/` components return DOM nodes (no innerHTML with untrusted strings without escaping).
Player workstream owns `web/js/api.js` (bug-tv server client: `streams(params, {onMeta,onStreams,onProvider,onDone}) → { close() }` over `EventSource`, `providers()`, `prefetch(params)`),
`web/js/views/watch.js`, `web/js/ui/player.js`, and `web/css/player.css`.
## Deviations
### Media workstream (B)
- `playbackFor(stream, ctx?)` takes an optional second arg `{ season, episode }` (stored as `s`/`e` in the
torrent token). Also accepts `stream.infoHash` (magnet built with default trackers) and `stream.fileIdx` (→ `f`).
`type: "other"` is sniffed by URL extension (.m3u8 → hls, .mp4/.webm/.m4v/.mov → file, else remux).
Extra exports: `proxyUrl(absUrl, headers)`, `remuxUrl(absUrl, headers)`, `magnetFor(stream)`.
Tokens use `src/sign.js`, so `playbackFor` must run where `sign.init(cfg.secret)` was called (main thread,
or init sign in the worker with the same secret).
- Rewritten playlist URIs are emitted as *relative* paths (`../../<token>/path`) so they work when the API
is mounted under a path prefix. Root-relative (`/x.ts`) and `../` URIs are rewritten too, and every URI
is rewritten when the upstream redirected.
- Added (additive): `GET /v1/torrent/<token>/raw` (range-serves the chosen file whatever its container;
ffmpeg reads this over loopback for torrent remuxing, so `?start=` uses real input seeking), and
`GET /v1/torrent/<token>/probe` (same shape as remux probe).
- `/status` adds `infoHash`, `bufferedBytes` and `error`; `buffered` = fraction of the file downloaded
contiguously from byte 0; `progress` = fraction of the chosen file downloaded. Before metadata arrives
`/status` returns immediately with `ready:false` (never blocks). `/files`/`/stream` wait up to 45s and
return 504 on timeout, but the torrent keeps fetching metadata in the background (retry succeeds).
- Remux probe adds `container`, `video.profile/pixFmt`, `audio[].title/default`. `?audio=<stream index>`
selects the audio track (absolute ffprobe index). HEVC is tagged `hvc1`. 503 when more than
`cfg.remux.maxProcs` (default 4) ffmpeg processes run.
- `/v1/subs/<token>` also accepts a trailing `.vtt`.
- New optional config keys: `allowPrivateTargets` (default false; lets proxy/subs/remux reach
private/loopback hosts — testing only), `remux.maxProcs`. Env `BUG_TV_WEBTORRENT` overrides the
webtorrent module specifier (testing).
- Legacy `GET /proxy/media?url=&h=<json>` kept (unsigned, SSRF-guarded); its playlists rewrite every URI
to `../v1/p/<token>/…`.
- Media stats for the health route: `require('./media/stats').mediaStats()`.
### Player workstream (D)
- `api.streams(params, handlers)` also takes `onError(err)`; `params.providers` (array) overrides
`config.getProviders()`. If EventSource errors before the first event, it falls back to
`?format=json` and replays the result as meta/streams/provider/done. A drop mid-stream counts as `done`,
so EventSource does not reconnect and replay the scrape.
- `views/watch.js` also exports `update(params)`. Switching episodes in place calls
`router.navigate('/watch/tv/:id/:s/:e', { replace: true })` (keeping the query string). The router then
calls `update()`, which returns true for the same title, so the view is not re-rendered.
- Prefs names follow `storage.js`, not the task text: `subtitleLang` (not `subLang`; "" = off), plus
`subtitleSize` (`s|m|l|xl`), `volume`, `muted`, `autoplayNext`, and `lastProvider`
(`{ "<type>:<id>": providerName }`, which adds a ranking bonus).
- Subtitles are fetched with `fetch()` and attached as blob-URL `<track>`s, so `<video>` needs no
`crossorigin` and direct non-CORS media still plays. Non-WEBVTT bodies get a minimal SRT→VTT fix
client-side. With remux the cues are shifted by the `?start=` offset.
- Torrent remux duration comes from `/v1/torrent/<token>/probe` (status URL with `/status` replaced by
`/probe`), or from `status.file.duration` / `status.duration` when present.
- Remux audio tracks come from the probe's `audio[]`. Switching a track reloads with
`?start=<t>&audio=<ffprobe index>`.
- Resume records also carry `backdrop` and `still`, as documented in `storage.js`. The save/delete rules
are unchanged from v4: skip if t < 10s, delete when t ≥ 95% or less than 15s remain, throttle to 3s,
and force a save on pause, seek, pagehide and visibility change.
### Scrape workstream (A)
- `/v1/streams` (and `/v1/prefetch`) accept the v4 filter params `minQuality` (`720`/`720p`/…),
`audioCodec`, `subtitles` (`any|required|lang`) and `subtitleLang`. They override `cfg.filters`.
`fresh=1` ignores cached provider results, but in-flight scrapes are still joined (used by `scripts/bench.js`).
`id=` is accepted as an alias of `tmdb=`.
- SSE `provider` events carry `cached: true` and `ms: 0` for results served from the cache. Providers that
are unknown or whose manifest `supportedTypes` lacks the type get an immediate `error`
(`"unknown provider"`) or `empty` (`"tv not supported"`) event. `count` is the count after filtering.
- `done` adds `debug: { tmdb: { calls, local, remote, network } }`:
- `calls`: TMDB requests the providers made.
- `local`: requests answered from the worker cache.
- `remote`: requests answered by the main-thread cache.
- `network`: real TMDB fetches made during the request. This is a global counter delta, so it is approximate when requests run concurrently.
- `meta.timeoutMs` is the largest adaptive budget among the providers being scraped (0 when everything was cached).
- JSON mode adds `providers: { name: { status, ms, count, cached? } }` and `ms`. `total` = number of streams
returned (after filters).
- Stream records omit raw `url`/`headers` (use `playback`). Streams with no playable `playback` are dropped.
`quality` is `""` when unknown. `id` = 12-char base64url SHA-1 of provider + url, so a season-pack magnet keeps
the same id across episodes.
- Client disconnect never aborts scrapes. Each scrape finishes within its own budget and lands in the cache.
- Result cache TTL: `ok` → `cacheTtlSec`; `empty` → min(5 min, `cacheTtlSec`); `error`/`timeout` are not cached.
- `GET /v1/providers` adds `description` and `health.{empty,budgetMs}` per provider, plus a top-level
`stats: { tmdb, pool, results }`. `POST /v1/prefetch` behaves like `GET`. `queued` lists only providers
that were not already cached.
- Legacy `GET /streams` keeps the v4 JSON shape (raw `url`, `headers`, v4 subtitle objects, `matched`,
`loadErrors`). Legacy `GET /providers` returns `{ all, enabled }`.
- Workers resolve DNS through c-ares (`dns.Resolver`, cached, with 30s negative caching for
ENOTFOUND/ETIMEOUT) instead of getaddrinfo. The scrape module also sets `UV_THREADPOOL_SIZE=24` if it is
unset. This matters: dead provider domains were exhausting libuv's 4-thread getaddrinfo pool and stalling every
other provider by 5–10s.
- Env `BUG_TV_DEBUG_PROVIDERS=1` shows provider console output, prefixed `[w<thread> <provider>]`. It is
silent by default. The optional `cfg.providersDir` overrides the providers directory used by workers (for tests).
- Health stats are kept in memory only, with no persistence.
- `X-Bug-Tv-Offset` is the *actual* start of the remux (the keyframe at/before `?start=`, found with a
parallel ffprobe), so it can be a little smaller than the requested `start`; the player should use the
header value, not its own requested value.
- Dependency note: `webtorrent@2.8.5` crashes on every `add()` with the currently resolved
`uint8-util@2.3.x` (`arr2hex(string)` in `Torrent._onTorrentId`). `webtorrent@^3.0.21` fixes it and is
API-compatible with `src/media/torrent.js` (tested); package.json should bump to it.
### Integration
- `/v1/remux/<token>/probe?start=<sec>` and `/v1/torrent/<token>/probe?start=<sec>` add `keyframe`: the time the remux really starts at. The player uses it as its clock offset because a `<video>` element can't read `X-Bug-Tv-Offset`.
- Extensionless stream URLs are sniffed by their first 1 KB (`src/media/sniff.js`) and typed m3u8/mp4/webm/mkv before `playbackFor` runs.
- The Swagger UI moved to `src/public/index.html`, `mod/` and `rest/` are removed, and webtorrent is bumped to ^3.0.21.