// Loads imdb2movie.json / imdb2tv.json into memory and reloads on mtime change. import { readFile, stat } from 'node:fs/promises'; import { join } from 'node:path'; import { TMDBINTEGRAL_DIR } from '../config.js'; const cache = { movie: null, tv: null }; const mtimes = { movie: 0, tv: 0 }; async function loadOne(type) { const file = join(TMDBINTEGRAL_DIR, `imdb2${type}.json`); const st = await stat(file); if (cache[type] && st.mtimeMs === mtimes[type]) return cache[type]; const obj = JSON.parse(await readFile(file, 'utf8')); cache[type] = new Map(Object.entries(obj).map(([k, v]) => [k, Number(v)])); mtimes[type] = st.mtimeMs; return cache[type]; } export async function lookupImdb(imdbId) { // Try movie first, then tv (matches PHP behaviour of exhaustive lookup). try { const movieMap = await loadOne('movie'); if (movieMap.has(imdbId)) return { type: 'movie', tmdb: movieMap.get(imdbId) }; } catch { /* file may be missing on a fresh install */ } try { const tvMap = await loadOne('tv'); if (tvMap.has(imdbId)) return { type: 'tv', tmdb: tvMap.get(imdbId) }; } catch { /* same */ } return null; } // Eager-load both mappings — used at server startup to remove the first-request // 1s latency. Returns the number of entries loaded per type. export async function preloadMappings() { const out = { movie: 0, tv: 0 }; try { out.movie = (await loadOne('movie')).size; } catch { /* missing */ } try { out.tv = (await loadOne('tv')).size; } catch { /* missing */ } return out; }