// Notes du public d'un film ou d'une série (Trakt) : moyenne, nombre de votes et répartition de 1 à 10. // TMDB ne donne pas la répartition : on la demande à Trakt à partir de l'identifiant TMDB. // La clé Trakt est un « secret » Supabase (TRAKT_CLIENT_ID) : jamais dans le code, jamais envoyée au navigateur. // // Rapidité : la note est gardée en mémoire puis dans la table title_ratings (pour tout le monde, 24 h). // Une note plus ancienne est renvoyée tout de suite et rafraîchie en arrière-plan ; la correspondance // TMDB → Trakt est gardée pour toujours (une seule requête à Trakt au lieu de deux). import { corsHeaders, getUserId, json, rateLimited } from '../_shared/auth.ts' const TRAKT_KEY = Deno.env.get('TRAKT_CLIENT_ID') ?? '' const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? '' const SERVICE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '' const TRAKT = 'https://api.trakt.tv' const FRESH_MS = 24 * 3600_000 interface Row { external_id: string trakt_id: number | null found: boolean rating: number | null votes: number distribution: Record | null fetched_at: string } interface TraktRatings { rating?: number votes?: number distribution?: Record } // Mémoire de l'instance : évite même la lecture en base const mem = new Map() /** Laisse une tâche finir après la réponse (enregistrement, rafraîchissement). */ const inBackground = (p: Promise) => (globalThis as { EdgeRuntime?: { waitUntil?: (p: Promise) => void } }).EdgeRuntime?.waitUntil?.(p) function db(path: string, init: RequestInit = {}): Promise { return fetch(`${SUPABASE_URL}/rest/v1/${path}`, { ...init, headers: { apikey: SERVICE_KEY, Authorization: `Bearer ${SERVICE_KEY}`, 'Content-Type': 'application/json', ...(init.headers ?? {}) }, signal: AbortSignal.timeout(5000), }) } async function readRow(ext: string): Promise { if (!SERVICE_KEY) return null try { const res = await db(`title_ratings?external_id=eq.${encodeURIComponent(ext)}&select=*`) if (!res.ok) { await res.body?.cancel() return null } const [row] = (await res.json()) as Row[] return row ?? null } catch { return null } } async function saveRow(row: Row): Promise { if (!SERVICE_KEY) return try { const res = await db('title_ratings?on_conflict=external_id', { method: 'POST', headers: { Prefer: 'resolution=merge-duplicates,return=minimal' }, body: JSON.stringify(row), }) await res.body?.cancel() } catch { /* la note sera simplement redemandée la prochaine fois */ } } async function trakt(path: string): Promise { const res = await fetch(TRAKT + path, { headers: { 'Content-Type': 'application/json', 'trakt-api-version': '2', 'trakt-api-key': TRAKT_KEY }, signal: AbortSignal.timeout(8000), }) if (res.status === 404) { await res.body?.cancel() return null } if (!res.ok) { await res.body?.cancel() throw new Error(String(res.status)) } return (await res.json()) as T } const count = (n: unknown) => (typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.min(Math.round(n), 1_000_000_000) : 0) /** Note Trakt d'un titre (la correspondance TMDB → Trakt déjà connue évite la recherche). */ async function fetchTrakt(ext: string, kind: 'movie' | 'tv', id: string, known?: number | null): Promise { const type = kind === 'tv' ? 'show' : 'movie' let traktId = known ?? undefined if (!traktId) { const found = await trakt<{ type?: string; movie?: { ids?: { trakt?: number } }; show?: { ids?: { trakt?: number } } }[]>(`/search/tmdb/${id}?type=${type}`) traktId = found?.find((r) => r.type === type)?.[type]?.ids?.trakt } const base = { external_id: ext, fetched_at: new Date().toISOString() } if (typeof traktId !== 'number' || !Number.isInteger(traktId)) return { ...base, trakt_id: null, found: false, rating: null, votes: 0, distribution: null } const r = await trakt(`/${type}s/${traktId}/ratings`) if (!r) return { ...base, trakt_id: traktId, found: false, rating: null, votes: 0, distribution: null } const distribution: Record = {} for (let s = 1; s <= 10; s++) distribution[String(s)] = count(r.distribution?.[String(s)]) const rating = typeof r.rating === 'number' && r.rating > 0 && r.rating <= 10 ? Math.round(r.rating * 100) / 100 : null return { ...base, trakt_id: traktId, found: true, rating, votes: count(r.votes), distribution } } const bodyOf = (row: Row) => JSON.stringify(row.found ? { found: true, rating: row.rating === null ? null : Number(row.rating), votes: row.votes, distribution: row.distribution } : { found: false }) Deno.serve(async (req) => { if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(req) }) if (req.method !== 'GET') return json(req, 405, { error: 'method' }) if (!TRAKT_KEY) return json(req, 503, { error: 'TRAKT_CLIENT_ID manquante' }) const url = new URL(req.url) const kind = url.searchParams.get('kind') const id = url.searchParams.get('id') ?? '' if ((kind !== 'movie' && kind !== 'tv') || !/^\d{1,10}$/.test(id)) return json(req, 400, { error: 'param' }) // Avec jeton : limite par compte. Sans jeton (cas normal : pas d'en-tête, donc pas de pré-requête CORS) : par adresse IP const userId = await getUserId(req) if (userId) { if (rateLimited('ratings:' + userId, 300, 10 * 60_000)) return json(req, 429, { error: 'rate' }) } else { const ip = (req.headers.get('x-forwarded-for') ?? '').split(',')[0].trim() || req.headers.get('cf-connecting-ip') || 'inconnu' if (rateLimited(`ratings-ip:${ip.slice(0, 64)}`, 400, 10 * 60_000)) return json(req, 429, { error: 'rate' }) } const respond = (row: Row) => new Response(bodyOf(row), { status: 200, headers: { ...corsHeaders(req), 'Content-Type': 'application/json; charset=utf-8', 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, max-age=21600' }, }) const remember = (row: Row) => { if (mem.size > 5000) mem.clear() mem.set(row.external_id, row) } const ext = `tmdb:${kind}:${id}` const now = Date.now() const hot = mem.get(ext) if (hot && now - Date.parse(hot.fetched_at) < FRESH_MS) return respond(hot) // Déjà connue (par n'importe qui) : renvoyée tout de suite ; trop ancienne, elle est rafraîchie en arrière-plan const row = hot ?? (await readRow(ext)) if (row) { remember(row) if (now - Date.parse(row.fetched_at) >= FRESH_MS) { inBackground( fetchTrakt(ext, kind, id, row.trakt_id) .then((fresh) => { remember(fresh) return saveRow(fresh) }) .catch(() => {}), ) } return respond(row) } // Jamais vue : Trakt maintenant (l'enregistrement en base ne retarde pas la réponse). // Plafond commun à tous (par instance) : un robot qui change d'adresse IP à chaque appel (la limite par IP // se contourne) ne peut ni épuiser la clé Trakt, ni remplir la table en essayant tous les numéros. if (rateLimited('ratings-cold', 120, 60_000)) return json(req, 429, { error: 'rate' }) try { const fresh = await fetchTrakt(ext, kind, id) remember(fresh) // Seuls les titres connus de Trakt vont en base (leur nombre est fini) ; « inconnu » reste en mémoire if (fresh.found) inBackground(saveRow(fresh)) return respond(fresh) } catch (e) { const timeout = e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError') return json(req, timeout ? 504 : 502, { error: timeout ? 'timeout' : 'upstream' }) } })