180 lines
5.3 KiB
JavaScript
180 lines
5.3 KiB
JavaScript
/*
|
|
API — client for the bug-tv server (docs/api.md, "Endpoints").
|
|
|
|
streams(params, handlers) opens the SSE stream at /v1/streams and calls
|
|
handlers as events arrive:
|
|
onMeta({tmdb,type,season,episode,providers,timeoutMs,cached})
|
|
onStreams({provider, ms, streams:[Stream]})
|
|
onProvider({name, status, ms, count, error?})
|
|
onDone({total, ms})
|
|
onError(Error)
|
|
Returns { close() }.
|
|
|
|
If EventSource fails before any event arrives (old proxy, CORS, a browser
|
|
without SSE), it falls back to ?format=json and replays the aggregated
|
|
response through the same handlers.
|
|
*/
|
|
import { resolveUrl, getProviders } from './config.js';
|
|
|
|
function providerList() {
|
|
let list;
|
|
try {
|
|
list = getProviders();
|
|
} catch (e) {
|
|
list = null;
|
|
}
|
|
return Array.isArray(list) ? list.filter(Boolean) : [];
|
|
}
|
|
|
|
function query(params, extra) {
|
|
const q = new URLSearchParams();
|
|
q.set('tmdb', String(params.tmdb ?? params.id));
|
|
q.set('type', params.type === 'tv' ? 'tv' : 'movie');
|
|
if (params.type === 'tv') {
|
|
if (params.season != null) q.set('season', String(params.season));
|
|
if (params.episode != null) q.set('episode', String(params.episode));
|
|
}
|
|
const providers = Array.isArray(params.providers) ? params.providers : providerList();
|
|
if (providers.length) q.set('providers', providers.join(','));
|
|
for (const [k, v] of Object.entries(extra || {})) q.set(k, v);
|
|
return q.toString();
|
|
}
|
|
|
|
async function getJson(path) {
|
|
const res = await fetch(resolveUrl(path), { headers: { Accept: 'application/json' } });
|
|
if (!res.ok) throw new Error(`HTTP ${res.status} for ${path}`);
|
|
return res.json();
|
|
}
|
|
|
|
export function streams(params, handlers = {}) {
|
|
const h = {
|
|
onMeta() {},
|
|
onStreams() {},
|
|
onProvider() {},
|
|
onDone() {},
|
|
onError() {},
|
|
...handlers,
|
|
};
|
|
let closed = false;
|
|
let gotEvent = false;
|
|
let finished = false;
|
|
let es = null;
|
|
let abort = null;
|
|
|
|
const call = (fn, data) => {
|
|
try {
|
|
fn(data);
|
|
} catch (e) {
|
|
console.error('[api.streams] handler failed', e);
|
|
}
|
|
};
|
|
|
|
const listen = (fn) => (ev) => {
|
|
if (closed || finished) return;
|
|
gotEvent = true;
|
|
let data;
|
|
try {
|
|
data = JSON.parse(ev.data);
|
|
} catch (e) {
|
|
return;
|
|
}
|
|
call(fn, data);
|
|
};
|
|
|
|
function finish(data) {
|
|
if (finished || closed) return;
|
|
finished = true;
|
|
if (es) es.close();
|
|
call(h.onDone, data || { total: 0, ms: 0 });
|
|
}
|
|
|
|
async function jsonFallback() {
|
|
if (es) es.close();
|
|
es = null;
|
|
abort = typeof AbortController === 'function' ? new AbortController() : null;
|
|
const started = performance.now();
|
|
try {
|
|
const res = await fetch(resolveUrl(`/v1/streams?${query(params, { format: 'json' })}`), {
|
|
headers: { Accept: 'application/json' },
|
|
signal: abort ? abort.signal : undefined,
|
|
});
|
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
const data = await res.json();
|
|
if (closed) return;
|
|
const list = Array.isArray(data.streams) ? data.streams : [];
|
|
const errors = data.providerErrors || {};
|
|
const byProvider = new Map();
|
|
for (const s of list) {
|
|
const p = s.provider || 'unknown';
|
|
if (!byProvider.has(p)) byProvider.set(p, []);
|
|
byProvider.get(p).push(s);
|
|
}
|
|
const names = [...new Set([...byProvider.keys(), ...Object.keys(errors)])];
|
|
const ms = Math.round(performance.now() - started);
|
|
call(h.onMeta, {
|
|
tmdb: params.tmdb,
|
|
type: params.type,
|
|
season: params.season,
|
|
episode: params.episode,
|
|
providers: names,
|
|
timeoutMs: 0,
|
|
cached: [],
|
|
});
|
|
for (const [provider, s] of byProvider) call(h.onStreams, { provider, ms, streams: s });
|
|
for (const name of names) {
|
|
const count = (byProvider.get(name) || []).length;
|
|
call(
|
|
h.onProvider,
|
|
errors[name]
|
|
? { name, status: 'error', ms, count, error: String(errors[name]) }
|
|
: { name, status: count ? 'ok' : 'empty', ms, count },
|
|
);
|
|
}
|
|
finish({ total: list.length, ms });
|
|
} catch (e) {
|
|
if (closed) return;
|
|
call(h.onError, e);
|
|
finish({ total: 0, ms: Math.round(performance.now() - started), error: String(e.message || e) });
|
|
}
|
|
}
|
|
|
|
if (typeof EventSource !== 'function') {
|
|
jsonFallback();
|
|
} else {
|
|
es = new EventSource(resolveUrl(`/v1/streams?${query(params)}`));
|
|
es.addEventListener('meta', listen(h.onMeta));
|
|
es.addEventListener('streams', listen(h.onStreams));
|
|
es.addEventListener('provider', listen(h.onProvider));
|
|
es.addEventListener('done', listen(finish));
|
|
es.addEventListener('error', () => {
|
|
if (closed || finished) return;
|
|
if (!gotEvent) {
|
|
jsonFallback();
|
|
return;
|
|
}
|
|
// Connection dropped mid-stream. EventSource would reconnect and replay
|
|
// the whole scrape; stop and treat what arrived as final.
|
|
finish({ total: -1, ms: 0, error: 'stream interrupted' });
|
|
});
|
|
}
|
|
|
|
return {
|
|
close() {
|
|
if (closed) return;
|
|
closed = true;
|
|
if (es) es.close();
|
|
if (abort) abort.abort();
|
|
},
|
|
};
|
|
}
|
|
|
|
export function providers() {
|
|
return getJson('/v1/providers');
|
|
}
|
|
|
|
export function prefetch(params) {
|
|
return fetch(resolveUrl(`/v1/prefetch?${query(params)}`), { headers: { Accept: 'application/json' } })
|
|
.then((r) => (r.ok ? r.json() : null))
|
|
.catch(() => null);
|
|
}
|