Backend - Route all TMDB requests through a rate limiter (20 req/s, 8 concurrent) with 429/5xx retries; stop logging the API key - Fetch external ids, certification, keywords, videos, watch providers and alternative titles in the entry details request - Shared entry mapper used by create, refresh, season refresh and importer - New columns on entries, ids, ratings, seasons, episodes and people, with an idempotent startup migration (adds missing columns, widens types) - Fix TV IMDb ids, network country/logo, episode tmdb_id on refresh, and genre/network removal on refresh - Add stale-entries maintenance job (count, start, cancel) and live recommendations endpoint Frontend - Entry page: certification, tagline, creators, in-app trailer, vote count, TV/movie details, network logos, external links, keywords, where to watch, and recommendations - Episode page: directors, writers and guest stars - Settings: TMDB refresh card with live progress
246 lines
7.5 KiB
JavaScript
246 lines
7.5 KiB
JavaScript
const axios = require("axios");
|
|
const { logToFile } = require("./logService");
|
|
const configService = require("./configService");
|
|
|
|
const TMDB_APIURL = configService.getTmdbApiUrl();
|
|
const TMDB_APIKEY = configService.getTmdbApiKey();
|
|
|
|
// ─── Rate limiting ───────────────────────────────────────────────────────────
|
|
// TMDB allows roughly 50 requests/second per IP. We stay well below that so
|
|
// bulk jobs (e.g. the stale-entries refresh) never get the IP blocked.
|
|
const MAX_REQUESTS_PER_WINDOW = 20;
|
|
const WINDOW_MS = 1000;
|
|
const MAX_CONCURRENT = 8;
|
|
const MAX_RETRIES = 4;
|
|
|
|
const queue = [];
|
|
const recentStarts = [];
|
|
let activeRequests = 0;
|
|
let wakeTimer = null;
|
|
|
|
function scheduleNext() {
|
|
while (queue.length > 0 && activeRequests < MAX_CONCURRENT) {
|
|
const now = Date.now();
|
|
while (recentStarts.length && now - recentStarts[0] >= WINDOW_MS) {
|
|
recentStarts.shift();
|
|
}
|
|
|
|
if (recentStarts.length >= MAX_REQUESTS_PER_WINDOW) {
|
|
if (!wakeTimer) {
|
|
const waitMs = WINDOW_MS - (now - recentStarts[0]) + 5;
|
|
wakeTimer = setTimeout(() => {
|
|
wakeTimer = null;
|
|
scheduleNext();
|
|
}, waitMs);
|
|
}
|
|
return;
|
|
}
|
|
|
|
recentStarts.push(now);
|
|
activeRequests++;
|
|
const job = queue.shift();
|
|
job().finally(() => {
|
|
activeRequests--;
|
|
scheduleNext();
|
|
});
|
|
}
|
|
}
|
|
|
|
function enqueue(fn) {
|
|
return new Promise((resolve, reject) => {
|
|
queue.push(() => fn().then(resolve, reject));
|
|
scheduleNext();
|
|
});
|
|
}
|
|
|
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
|
function isRetryable(error) {
|
|
const status = error.response?.status;
|
|
if (status === 429) return true;
|
|
if (status >= 500) return true;
|
|
return !error.response; // network error / timeout
|
|
}
|
|
|
|
/**
|
|
* Rate-limited GET against the TMDB API. Retries 429s (honouring Retry-After)
|
|
* and transient failures with backoff. The API key is never logged.
|
|
* @param {string} path - e.g. "movie/550"
|
|
* @param {Object} [params] - extra query params
|
|
* @returns {Promise<Object>} response data
|
|
*/
|
|
async function tmdbGet(path, params = {}) {
|
|
const query = { language: "en-US", ...params };
|
|
const logQuery = new URLSearchParams(
|
|
Object.entries(query).filter(([, v]) => v !== undefined),
|
|
).toString();
|
|
|
|
for (let attempt = 1; ; attempt++) {
|
|
try {
|
|
logToFile(`TMDB GET ${path}?${logQuery}`);
|
|
const response = await enqueue(() =>
|
|
axios.get(`${TMDB_APIURL}${path}`, {
|
|
params: { api_key: TMDB_APIKEY, ...query },
|
|
timeout: 20000,
|
|
}),
|
|
);
|
|
return response.data;
|
|
} catch (error) {
|
|
if (attempt >= MAX_RETRIES || !isRetryable(error)) throw error;
|
|
|
|
const retryAfter = Number(error.response?.headers?.["retry-after"]);
|
|
const waitMs =
|
|
Number.isFinite(retryAfter) && retryAfter > 0
|
|
? retryAfter * 1000
|
|
: 1000 * 2 ** (attempt - 1);
|
|
logToFile(
|
|
`TMDB GET ${path} failed (${error.response?.status ?? error.code}), retry ${attempt}/${MAX_RETRIES - 1} in ${waitMs}ms`,
|
|
);
|
|
await sleep(waitMs);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Runs a TMDB request, logging and returning null on failure. */
|
|
async function safeGet(label, path, params) {
|
|
try {
|
|
return await tmdbGet(path, params);
|
|
} catch (error) {
|
|
logToFile(
|
|
`Error fetching ${label} (${path}): ${error.response?.status ?? ""} ${error.message}`,
|
|
);
|
|
console.log(`Error fetching ${label}.`, error.message);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// ─── Entries ─────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Fetches movie/TV details plus everything we store from the same request:
|
|
* external ids, certification, keywords, videos, watch providers and
|
|
* alternative titles.
|
|
*/
|
|
async function fetchEntryData(tmdb_id, is_tvserie) {
|
|
const type = is_tvserie ? "tv" : "movie";
|
|
const appends = [
|
|
"external_ids",
|
|
is_tvserie ? "content_ratings" : "release_dates",
|
|
"keywords",
|
|
"videos",
|
|
"watch/providers",
|
|
"alternative_titles",
|
|
];
|
|
return safeGet("entry data", `${type}/${tmdb_id}`, {
|
|
append_to_response: appends.join(","),
|
|
include_video_language: "en,null",
|
|
});
|
|
}
|
|
|
|
async function fetchSeasonData(tmdbTvId, seasonNumber) {
|
|
return safeGet("season data", `tv/${tmdbTvId}/season/${seasonNumber}`, {
|
|
append_to_response: "external_ids",
|
|
});
|
|
}
|
|
|
|
async function fetchEntryMedia(tmdb_id, is_tvserie) {
|
|
const type = is_tvserie ? "tv" : "movie";
|
|
// Images are language-agnostic, so don't send language=en-US
|
|
return safeGet("entry media", `${type}/${tmdb_id}/images`, {
|
|
language: undefined,
|
|
});
|
|
}
|
|
|
|
async function fetchEntryRecommendations(tmdb_id, is_tvserie, page = 1) {
|
|
const type = is_tvserie ? "tv" : "movie";
|
|
return safeGet("recommendations", `${type}/${tmdb_id}/recommendations`, {
|
|
page,
|
|
});
|
|
}
|
|
|
|
async function fetchCollectionData(collectionId) {
|
|
return safeGet("collection data", `collection/${collectionId}`);
|
|
}
|
|
|
|
/**
|
|
* Fetches credits (cast and crew) for a movie or TV show
|
|
* @param {number} tmdb_id - The TMDB ID of the movie or TV show
|
|
* @param {boolean} is_tvserie - Whether the entry is a TV series or not
|
|
* @returns {Promise<Object|null>} - The credits data or null if there's an error
|
|
*/
|
|
async function fetchEntryCredits(tmdb_id, is_tvserie) {
|
|
const path = is_tvserie
|
|
? `tv/${tmdb_id}/aggregate_credits`
|
|
: `movie/${tmdb_id}/credits`;
|
|
return safeGet("entry credits", path);
|
|
}
|
|
|
|
// ─── People ──────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Fetches detailed information about a person
|
|
* @param {number} tmdb_id - The TMDB ID of the person
|
|
* @returns {Promise<Object|null>} - The person data or null if there's an error
|
|
*/
|
|
async function fetchPersonDetails(tmdb_id) {
|
|
return safeGet("person details", `person/${tmdb_id}`, {
|
|
append_to_response: "external_ids",
|
|
});
|
|
}
|
|
|
|
async function fetchPersonCombinedCredits(tmdb_id) {
|
|
return safeGet(
|
|
"person combined credits",
|
|
`person/${tmdb_id}/combined_credits`,
|
|
);
|
|
}
|
|
|
|
// ─── Lists & search ──────────────────────────────────────────────────────────
|
|
|
|
async function fetchTrending(type, page = 1) {
|
|
return safeGet(`trending ${type}`, `trending/${type}/week`, { page });
|
|
}
|
|
|
|
async function fetchPopular(type, page = 1) {
|
|
return safeGet(`popular ${type}`, `${type}/popular`, { page });
|
|
}
|
|
|
|
async function fetchTopRated(type, page = 1) {
|
|
return safeGet(`top rated ${type}`, `${type}/top_rated`, { page });
|
|
}
|
|
|
|
async function fetchUpcoming(page = 1) {
|
|
return safeGet("upcoming movies", "movie/upcoming", { page });
|
|
}
|
|
|
|
async function searchMulti(query, page = 1) {
|
|
return safeGet("search", "search/multi", { query, page });
|
|
}
|
|
|
|
async function searchPeople(query, page = 1) {
|
|
return safeGet("people search", "search/person", { query, page });
|
|
}
|
|
|
|
async function fetchPopularPeople(page = 1) {
|
|
return safeGet("popular people", "person/popular", { page });
|
|
}
|
|
|
|
module.exports = {
|
|
tmdbGet,
|
|
fetchEntryData,
|
|
fetchSeasonData,
|
|
fetchEntryMedia,
|
|
fetchEntryRecommendations,
|
|
fetchCollectionData,
|
|
fetchEntryCredits,
|
|
fetchPersonDetails,
|
|
fetchPersonCombinedCredits,
|
|
fetchTrending,
|
|
fetchPopular,
|
|
fetchTopRated,
|
|
fetchUpcoming,
|
|
searchMulti,
|
|
searchPeople,
|
|
fetchPopularPeople,
|
|
};
|