Files
tv/src/routes/streams.js
T
2026-10-27 05:49:38 -05:00

204 lines
7.1 KiB
JavaScript

// GET /v1/streams (SSE or JSON), GET|POST /v1/prefetch, legacy GET /streams. See docs/api.md.
const { json, error, sse } = require('../http');
const scrape = require('../scrape');
const tmdb = require('../tmdb');
const { toPublic, toLegacy } = require('../scrape/normalize');
const { applyFilters, rankStreams, filtersFrom } = require('../scrape/filter');
const MAX_PROVIDERS = 100;
// -> { p, names } or { err }
function parseParams(url, cfg) {
const q = url.searchParams;
const id = (q.get('tmdb') || q.get('id') || '').trim();
if (!/^\d+$/.test(id)) return { err: 'missing or invalid ?tmdb=<id>' };
const type = q.get('type') === 'tv' ? 'tv' : 'movie';
const season = (q.get('season') || '').trim();
const episode = (q.get('episode') || '').trim();
if (type === 'tv') {
if (!season || !episode) return { err: 'tv streams need ?season=<n>&episode=<n>' };
if (!/^\d+$/.test(season) || !/^\d+$/.test(episode)) return { err: 'season and episode must be numbers' };
}
const param = q.get('providers');
let names = param ? param.split(',').map((s) => s.trim()).filter(Boolean) : scrape.defaults();
names = [...new Set(names)].slice(0, MAX_PROVIDERS);
if (!names.length) return { err: 'no providers requested' };
return {
p: { tmdb: id, type, season: type === 'tv' ? parseInt(season, 10) : null, episode: type === 'tv' ? parseInt(episode, 10) : null },
names,
filters: filtersFrom(q, cfg.filters),
fresh: q.get('fresh') === '1',
};
}
function wantsJson(req, url) {
const f = url.searchParams.get('format');
if (f) return f === 'json';
const accept = String(req.headers.accept || '');
return accept.includes('application/json') && !accept.includes('text/event-stream');
}
const score = (name) => scrape.health.score(name);
function shape(r, filters) {
return rankStreams(applyFilters(r.streams, filters), score);
}
// run every provider; onResult(r, fromCache) fires as each settles
async function runAll(names, p, onResult, fresh = false) {
const cachedNames = [];
const jobs = [];
let warmed = false;
for (const name of names) {
const hit = !fresh && scrape.cached(name, p);
if (hit) {
cachedNames.push(name);
jobs.push(Promise.resolve().then(() => onResult(hit, true)));
continue;
}
if (!warmed) {
scrape.warm(p); // details/external_ids/season fetched once in the main thread, joined by workers
warmed = true;
}
jobs.push(scrape.scrape(name, p, { fresh }).then((r) => onResult(r, false)));
}
return { cachedNames, done: Promise.all(jobs) };
}
function budgetFor(names, p, cachedNames) {
const live = names.filter((n) => !cachedNames.includes(n) && scrape.exists(n) && scrape.supports(n, p.type));
return live.length ? Math.max(...live.map((n) => scrape.health.budget(n))) : 0;
}
async function handleSse(req, res, { p, names, filters, fresh }) {
const t0 = Date.now();
const net0 = tmdb.stats().network;
const ev = sse(req, res);
const dbg = { calls: 0, local: 0, remote: 0 };
let total = 0;
const pending = [];
let metaSent = false;
const onResult = (r, fromCache) => {
if (!fromCache && r.tmdb) for (const k in dbg) dbg[k] += r.tmdb[k] || 0;
if (!metaSent) return pending.push([r, fromCache]);
if (ev.closed) return;
const streams = shape(r, filters).map(toPublic);
total += streams.length;
const ms = fromCache ? 0 : r.ms;
if (streams.length) ev.event('streams', { provider: r.name, ms, streams });
const pe = { name: r.name, status: r.status, ms, count: streams.length };
if (r.error) pe.error = r.error;
if (fromCache) pe.cached = true;
ev.event('provider', pe);
};
const { cachedNames, done } = await runAll(names, p, onResult, fresh);
ev.event('meta', {
tmdb: p.tmdb,
type: p.type,
season: p.season,
episode: p.episode,
providers: names,
timeoutMs: budgetFor(names, p, cachedNames),
cached: cachedNames,
});
metaSent = true;
for (const [r, c] of pending.splice(0)) onResult(r, c);
await done;
ev.event('done', { total, ms: Date.now() - t0, debug: { tmdb: { ...dbg, network: tmdb.stats().network - net0 } } });
ev.close();
}
async function collect(names, p, fresh) {
const out = [];
const { done } = await runAll(names, p, (r, fromCache) => out.push({ r, fromCache }), fresh);
await done;
return out;
}
async function handleJson(req, res, { p, names, filters, fresh }) {
const t0 = Date.now();
const results = await collect(names, p, fresh);
const providerErrors = {};
const providers = {};
let streams = [];
for (const { r, fromCache } of results) {
const kept = applyFilters(r.streams, filters);
streams.push(...kept);
providers[r.name] = { status: r.status, ms: fromCache ? 0 : r.ms, count: kept.length, ...(fromCache ? { cached: true } : {}) };
if ((r.status === 'error' || r.status === 'timeout') && r.error) providerErrors[r.name] = r.error;
}
streams = rankStreams(streams, score).map(toPublic);
return json(req, res, 200, {
tmdb_id: p.tmdb,
type: p.type,
season: p.season,
episode: p.episode,
total: streams.length,
streams,
providerErrors,
providers,
ms: Date.now() - t0,
});
}
async function streams(req, res, ctx) {
const parsed = parseParams(ctx.url, ctx.cfg);
if (parsed.err) return error(req, res, 400, parsed.err);
if (wantsJson(req, ctx.url)) return handleJson(req, res, parsed);
return handleSse(req, res, parsed);
}
async function prefetch(req, res, ctx) {
const parsed = parseParams(ctx.url, ctx.cfg);
if (parsed.err) return error(req, res, 400, parsed.err);
const { p, names } = parsed;
const queued = names.filter((n) => scrape.exists(n) && scrape.supports(n, p.type) && !scrape.cached(n, p));
if (queued.length) {
scrape.warm(p);
for (const n of queued) scrape.scrape(n, p);
}
return json(req, res, 202, { queued });
}
// v4 shape: aggregated JSON, raw urls + headers, filters from query/cfg
async function legacy(req, res, ctx) {
const parsed = parseParams(ctx.url, ctx.cfg);
if (parsed.err) return error(req, res, 400, parsed.err);
const { p, names, filters } = parsed;
const loadErrors = {};
for (const n of names) if (!scrape.exists(n)) loadErrors[n] = 'not found';
const valid = names.filter((n) => scrape.exists(n));
if (!valid.length) return error(req, res, 500, 'no providers available', { loadErrors });
const results = await collect(valid, p);
const providerErrors = {};
const all = [];
for (const { r } of results) {
all.push(...r.streams);
if ((r.status === 'error' || r.status === 'timeout') && r.error) providerErrors[r.name] = r.error;
}
const ranked = rankStreams(applyFilters(all, filters), score);
return json(req, res, 200, {
tmdb_id: p.tmdb,
type: p.type,
season: p.season,
episode: p.episode,
total: all.length,
matched: ranked.length,
streams: ranked.map(toLegacy),
providerErrors,
loadErrors,
});
}
module.exports = {
init: (cfg) => scrape.init(cfg),
routes: [
{ method: 'GET', path: '/v1/streams', handler: streams },
{ method: 'GET', path: '/v1/prefetch', handler: prefetch },
{ method: 'POST', path: '/v1/prefetch', handler: prefetch },
{ method: 'GET', path: '/streams', handler: legacy },
],
};