Files
tpbproxy/controller/tmdb.js
wmantly 51e6817393 Add exponential backoff retry to all downstream calls
New controller/retry.js wraps async calls with infinite retries, capped

at 30s with jitter. Applied to: TPB search, TMDB, Emby, Ollama chat,

Transmission RPC, and the status/status interval calls inherit it via

a Proxy around the Transmission client.

Also handles ollama package returning pre-parsed JSON objects.

Signed-off-by: William Mantly <wmantly@gmail.com>
2026-07-20 14:44:41 -04:00

76 lines
2.4 KiB
JavaScript

'use strict';
const conf = require('>/conf');
const { fetchJSONWithRetry } = require('./retry');
async function tmdbSearch(query){
let url = `https://api.themoviedb.org/3/search/multi?include_adult=false`
+ `&query=${encodeURIComponent(query)}&api_key=${conf.tmdb.apiKey}`;
let data = await fetchJSONWithRetry(url);
return (data.results || [])
.filter(item => item.media_type === 'movie' || item.media_type === 'tv')
.slice(0, 4)
.map(item => {
let date = item.release_date || item.first_air_date || '';
return {
tmdbId: item.id,
mediaType: item.media_type,
title: item.title || item.name,
year: date ? date.slice(0, 4) : '',
posterUrl: item.poster_path ? `https://image.tmdb.org/t/p/w200${item.poster_path}` : null,
};
});
}
async function tmdbDetails(tmdbId, mediaType){
let url = `https://api.themoviedb.org/3/${mediaType}/${tmdbId}`
+ `?append_to_response=external_ids&api_key=${conf.tmdb.apiKey}`;
let data = await fetchJSONWithRetry(url);
let date = data.release_date || data.first_air_date || '';
return {
title: data.title || data.name,
year: date ? date.slice(0, 4) : '',
imdbId: data.imdb_id || (data.external_ids && data.external_ids.imdb_id) || null,
};
}
// Canonicalize a( possibly messy) title + year to the authoritative TMDB record.
// Returns null when nothing matches so callers can flag instead of guessing.
async function tmdbFindBest(title, year, mediaType){
let results = await tmdbSearch(title);
let pool = results.filter(r => r.mediaType === mediaType);
if(!pool.length) pool = results;
if(!pool.length) return null;
let pick = (year && pool.find(r => r.year === String(year))) || pool[0];
let details = await tmdbDetails(pick.tmdbId, pick.mediaType);
return {
title: details.title,
year: details.year,
tmdbId: pick.tmdbId,
mediaType: pick.mediaType,
imdbId: details.imdbId,
};
}
// Per-season episode counts for a show( season 0 / specials excluded).
async function tmdbSeasons(tmdbId){
let data = await fetchJSONWithRetry(`https://api.themoviedb.org/3/tv/${tmdbId}?api_key=${conf.tmdb.apiKey}`);
let date = data.first_air_date || '';
return {
title: data.name,
year: date ? date.slice(0, 4) : '',
seasons: (data.seasons || [])
.filter(s => s.season_number >= 1 && s.episode_count > 0)
.map(s => ({ season: s.season_number, episodeCount: s.episode_count })),
};
}
module.exports = { tmdbSearch, tmdbDetails, tmdbFindBest, tmdbSeasons };