This commit is contained in:
4DBug committed 2026-10-27 05:49:38 -05:00
1 parent bcf05e8063
commit f37985b4c8
109 files changed
+22810 -6143

No files matched your search

+169 -166
View File
@@ -1,176 +1,179 @@
/*
API — two upstreams:
1. the bug-tv REST server (SR.config.getBase()): provider catalog,
/streams lookup, and the /proxy/media tunnel the player needs (CORS,
headers, m3u8 rewrite).
2. TMDB, called straight from the browser (it is CORS-enabled): search,
trending, details, seasons, episodes. Each returns the same shape the
server's endpoints used to, so the pages are unchanged.
API — client for the bug-tv server (docs/api.md, "Endpoints").
Keeping catalog traffic off the server means it only does provider scraping
and stream proxying.
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.
*/
(function () {
'use strict';
import { resolveUrl, getProviders } from './config.js';
const TMDB_BASE = 'https://api.themoviedb.org/3';
const TMDB_IMG = 'https://image.tmdb.org/t/p/';
async function request(path, params) {
const url = new URL(SR.config.getBase() + path);
if (params) {
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null || value === '') continue;
url.searchParams.set(key, String(value));
}
}
let res;
try {
res = await fetch(url.toString());
} catch (e) {
throw new Error(`cannot reach the API at ${SR.config.getBase()} — check the base URL in Settings`);
}
let data = null;
try {
data = await res.json();
} catch (e) {
/* non-JSON body */
}
if (!res.ok) {
throw new Error((data && data.error) || `API error: HTTP ${res.status}`);
}
return data;
function providerList() {
let list;
try {
list = getProviders();
} catch (e) {
list = null;
}
return Array.isArray(list) ? list.filter(Boolean) : [];
}
// Direct TMDB call. `key` overrides the configured key (Settings "Test").
async function tmdb(pathname, params, key) {
const url = new URL(TMDB_BASE + pathname);
url.searchParams.set('api_key', key || SR.config.getTmdbKey());
url.searchParams.set('language', 'en-US');
if (params) {
for (const [k, v] of Object.entries(params)) {
if (v === undefined || v === null || v === '') continue;
url.searchParams.set(k, String(v));
}
}
let res;
try {
res = await fetch(url.toString());
} catch (e) {
throw new Error('cannot reach the TMDB API — check your connection or the TMDB API key in Settings');
}
let data = null;
try {
data = await res.json();
} catch (e) {
/* non-JSON body */
}
if (!res.ok) {
if (res.status === 401) {
throw new Error('TMDB rejected the API key — check "TMDB API key" in Settings');
}
throw new Error((data && (data.status_message || data.error)) || `TMDB error: HTTP ${res.status}`);
}
return data;
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();
}
// route a media/subtitle URL through the API proxy (CORS, headers, m3u8 rewrite)
function proxyUrl(target, headers) {
const q = new URLSearchParams();
q.set('url', target);
q.set('h', JSON.stringify(headers || {}));
return SR.config.getBase() + '/proxy/media?' + 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();
}
// Same shapes the server endpoints used to return.
function searchResult(m) {
const isTv = m.media_type === 'tv';
const date = isTv ? m.first_air_date : m.release_date;
return {
tmdb_id: m.id,
type: isTv ? 'tv' : 'movie',
name: m.title || m.name,
year: date ? String(date).slice(0, 4) : '',
poster: m.poster_path ? `${TMDB_IMG}w342${m.poster_path}` : '',
backdrop: m.backdrop_path ? `${TMDB_IMG}w1280${m.backdrop_path}` : '',
rating: m.vote_average ? Number(m.vote_average).toFixed(1) : '',
overview: m.overview || '',
};
}
function fullImage(pathname) {
return pathname ? `${TMDB_IMG}original${pathname}` : '';
}
window.SR = window.SR || {};
SR.api = {
request,
tmdb,
proxyUrl,
// — TMDB, straight from the browser —
search: (q) =>
tmdb('/search/multi', { query: q, include_adult: 'false', page: 1 }).then((r) => {
const results = (r.results || [])
.filter((m) => m.media_type === 'movie' || m.media_type === 'tv')
.slice(0, 15)
.map(searchResult);
return { query: q, count: results.length, results };
}),
trending: (type, timeWindow) => {
const t = ['movie', 'tv', 'all'].includes(type) ? type : 'all';
const w = timeWindow === 'day' ? 'day' : 'week';
return tmdb(`/trending/${t}/${w}`).then((r) => {
const results = (r.results || []).slice(0, 20).map(searchResult);
return { type: t, window: w, count: results.length, results };
});
},
details: (type, id) =>
tmdb(`/${type}/${id}`, { append_to_response: 'images' }).then((d) => {
d.poster_url = fullImage(d.poster_path);
d.backdrop_url = fullImage(d.backdrop_path);
if (d.images) {
for (const key of Object.keys(d.images)) {
d.images[key] = (d.images[key] || []).map((im) => ({ ...im, url: fullImage(im.file_path) }));
}
}
return d;
}),
seasons: (id) =>
tmdb(`/tv/${id}`).then((r) => {
const seasons = (r.seasons || [])
.filter((s) => s.season_number > 0 && (s.episode_count || 0) > 0)
.map((s) => ({
season_number: s.season_number,
name: s.name,
episode_count: s.episode_count,
air_date: s.air_date || '',
}));
return { tmdb_id: id, count: seasons.length, seasons };
}),
episodes: (id, season) =>
tmdb(`/tv/${id}/season/${season}`).then((r) => {
const episodes = (r.episodes || [])
.slice()
.sort((a, b) => a.episode_number - b.episode_number)
.map((e) => ({
episode_number: e.episode_number,
name: e.name,
air_date: e.air_date || '',
still: e.still_path ? `${TMDB_IMG}w300${e.still_path}` : '',
}));
return { tmdb_id: id, season: parseInt(season, 10), count: episodes.length, episodes };
}),
// — bug-tv server (providers, streams, proxy) —
streams: ({ tmdb, type, season, episode, providers }) =>
request('/streams', {
tmdb,
type,
season,
episode,
providers: Array.isArray(providers) && providers.length ? providers.join(',') : '',
}),
providers: () => request('/providers'),
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);
}