// 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. import { corsHeaders, getUserId, json, rateLimited } from '../_shared/auth.ts' const TRAKT_KEY = Deno.env.get('TRAKT_CLIENT_ID') ?? '' const TRAKT = 'https://api.trakt.tv' interface Ratings { rating: number votes: number distribution: Record } // Réponses gardées 12 h par instance (les notes bougent lentement) : moins d'appels à Trakt const cache = new Map() const TTL = 12 * 3600_000 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) 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' }) // Même limite que le proxy TMDB : compte connecté par compte, visiteur sans compte 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)}`, 100, 10 * 60_000)) return json(req, 429, { error: 'rate' }) } const key = `${kind}:${id}` const hit = cache.get(key) const headers = { ...corsHeaders(req), 'Content-Type': 'application/json; charset=utf-8', 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, max-age=21600', } if (hit && Date.now() - hit.at < TTL) return new Response(hit.body, { status: 200, headers }) const type = kind === 'tv' ? 'show' : 'movie' try { const found = await trakt<{ type?: string; movie?: { ids?: { trakt?: number } }; show?: { ids?: { trakt?: number } } }[]>(`/search/tmdb/${id}?type=${type}`) const traktId = found?.find((r) => r.type === type)?.[type]?.ids?.trakt let body = JSON.stringify({ found: false }) if (typeof traktId === 'number') { const r = await trakt(`/${type}s/${traktId}/ratings`) if (r) { 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 body = JSON.stringify({ found: true, rating, votes: count(r.votes), distribution }) } } if (cache.size > 5000) cache.clear() cache.set(key, { at: Date.now(), body }) return new Response(body, { status: 200, headers }) } catch (e) { const timeout = e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError') return json(req, timeout ? 504 : 502, { error: timeout ? 'timeout' : 'upstream' }) } })