/* tmdb.js — direct browser → TMDB client (CORS-enabled API), cached. - In-memory promise cache for every request (dedupes concurrent callers). - sessionStorage cache (30 min) for list endpoints (trending/popular/discover/search/seasons…), so navigating back and forth is instant. Details stay memory-only (large payloads). All functions resolve to raw TMDB JSON. List results get `media_type` filled in when the endpoint is type-specific, so cards always know whether an item is a movie or tv show. */ import { getTmdbKey } from './config.js'; import { safe } from './util.js'; const API = 'https://api.themoviedb.org/3'; export const IMG_BASE = 'https://image.tmdb.org/t/p/'; const SESSION_PREFIX = 'bug-tv.tmdb.'; const SESSION_TTL = 30 * 60 * 1000; const mem = new Map(); function buildUrl(path, params) { const url = new URL(API + path); url.searchParams.set('api_key', getTmdbKey()); if (!params || params.language === undefined) url.searchParams.set('language', 'en-US'); for (const [k, v] of Object.entries(params || {})) { if (v === undefined || v === null || v === '') continue; url.searchParams.set(k, String(v)); } return url; } function cacheKey(path, params) { const p = new URLSearchParams(); for (const k of Object.keys(params || {}).sort()) { const v = params[k]; if (v !== undefined && v !== null && v !== '') p.set(k, String(v)); } return `${path}?${p}`; } async function fetchJson(path, params, key) { const url = buildUrl(path, params); if (key) url.searchParams.set('api_key', key); let res; try { res = await fetch(url.toString()); } catch (e) { throw new Error('Cannot reach TMDB — check your connection'); } let data = null; try { data = await res.json(); } catch (e) { /* non-JSON */ } if (!res.ok) { const msg = (data && data.status_message) || `TMDB error: HTTP ${res.status}`; const err = new Error(res.status === 401 ? `TMDB key rejected: ${msg}` : msg); err.status = res.status; throw err; } return data; } // get(path, params, { session: bool }) export function get(path, params = {}, opts = {}) { const ck = cacheKey(path, params); if (mem.has(ck)) return mem.get(ck); if (opts.session) { const hit = safe(() => JSON.parse(sessionStorage.getItem(SESSION_PREFIX + ck)), null); if (hit && hit.at && Date.now() - hit.at < SESSION_TTL && hit.data) { const p = Promise.resolve(hit.data); mem.set(ck, p); return p; } } const p = fetchJson(path, params).then((data) => { if (opts.session) { safe(() => sessionStorage.setItem(SESSION_PREFIX + ck, JSON.stringify({ at: Date.now(), data }))); } return data; }); mem.set(ck, p); p.catch(() => mem.delete(ck)); return p; } // Validate a key without touching the cache (Settings "Test"). export function testKey(key) { return fetchJson('/configuration', {}, key); } function tag(type) { return (data) => { if (data && Array.isArray(data.results) && type && type !== 'all') { data.results.forEach((r) => { if (r && !r.media_type) r.media_type = type; }); } return data; }; } const t = (type) => (type === 'tv' ? 'tv' : 'movie'); export function trending(type = 'all', window = 'day', page = 1) { const ty = type === 'all' ? 'all' : t(type); return get(`/trending/${ty}/${window === 'week' ? 'week' : 'day'}`, { page }, { session: true }).then(tag(ty)); } export function popular(type, page = 1) { return get(`/${t(type)}/popular`, { page }, { session: true }).then(tag(t(type))); } export function topRated(type, page = 1) { return get(`/${t(type)}/top_rated`, { page }, { session: true }).then(tag(t(type))); } export function discover(type, params = {}) { return get(`/discover/${t(type)}`, { sort_by: 'popularity.desc', ...params }, { session: true }).then(tag(t(type))); } export function details(type, id) { const ty = t(type); const extra = ty === 'tv' ? 'content_ratings' : 'release_dates'; return get(`/${ty}/${id}`, { append_to_response: `images,credits,similar,recommendations,external_ids,videos,${extra}`, include_image_language: 'en,null', }).then((d) => { if (d) { d.media_type = ty; if (d.similar) tag(ty)(d.similar); if (d.recommendations) tag(ty)(d.recommendations); } return d; }); } export function season(tvId, n) { return get(`/tv/${tvId}/season/${n}`, {}, { session: true }); } export function search(q, page = 1) { const query = String(q || '').trim(); if (!query) return Promise.resolve({ results: [], total_results: 0, page: 1, total_pages: 0 }); return get('/search/multi', { query, page, include_adult: 'false' }, { session: true }).then((d) => { d.results = (d.results || []).filter((r) => r.media_type === 'movie' || r.media_type === 'tv'); return d; }); } export function genres(type) { return get(`/genre/${t(type)}/list`, {}, { session: true }).then((d) => { const map = {}; for (const g of (d && d.genres) || []) map[g.id] = g.name; return map; }); } export function network(id) { return get(`/network/${id}`, {}, { session: true }); } export function company(id) { return get(`/company/${id}`, {}, { session: true }); } // Image URL helper: img('/abc.jpg', 'w342'); returns '' for missing paths. export function img(path, size = 'original') { if (!path) return ''; if (/^https?:/i.test(path)) return path; return `${IMG_BASE}${size}${path}`; } // srcset for responsive images: srcset('/abc.jpg', ['w300','w780','w1280']) export function srcset(path, sizes) { if (!path) return ''; return sizes .map((s) => `${img(path, s)} ${s.replace(/^w/, '')}w`) .filter((s) => !/original/.test(s)) .join(', '); } /* ---- details helpers ---------------------------------------------------------------- */ // Best logo: English png first, then English, then language-neutral; null if none. export function logoFor(d) { const logos = (d && d.images && d.images.logos) || []; if (!logos.length) return null; const score = (l) => (l.iso_639_1 === 'en' ? 4 : l.iso_639_1 == null ? 1 : 0) + (/\.png$/i.test(l.file_path) ? 2 : 0) + (l.vote_average || 0) / 20; const best = [...logos].sort((a, b) => score(b) - score(a))[0]; return best && (best.iso_639_1 === 'en' || best.iso_639_1 == null) ? best : null; } export function trailerFor(d) { const vids = ((d && d.videos && d.videos.results) || []).filter((v) => v.site === 'YouTube'); const score = (v) => (v.type === 'Trailer' ? 4 : v.type === 'Teaser' ? 2 : 0) + (v.official ? 1 : 0) + (v.iso_639_1 === 'en' ? 1 : 0); return vids.sort((a, b) => score(b) - score(a))[0] || null; } export function certificationFor(d) { if (!d) return ''; if (d.content_ratings) { const us = (d.content_ratings.results || []).find((r) => r.iso_3166_1 === 'US'); return (us && us.rating) || ''; } if (d.release_dates) { const us = (d.release_dates.results || []).find((r) => r.iso_3166_1 === 'US'); const c = us && (us.release_dates || []).map((r) => r.certification).find(Boolean); return c || ''; } return ''; } // normalize any TMDB list result / details / my-list item into a card model export function toItem(r, typeHint) { if (!r) return null; const type = r.media_type === 'tv' || r.media_type === 'movie' ? r.media_type : r.type || typeHint || (r.first_air_date !== undefined ? 'tv' : 'movie'); return { type: type === 'tv' ? 'tv' : 'movie', id: r.id, title: r.title || r.name || r.original_title || r.original_name || '', year: r.year || String(r.release_date || r.first_air_date || '').slice(0, 4), rating: Number(r.vote_average || r.rating || 0), poster_path: r.poster_path || null, backdrop_path: r.backdrop_path || null, overview: r.overview || '', genre_ids: r.genre_ids || (r.genres ? r.genres.map((g) => g.id) : []), }; }