Note Trakt affichée tout de suite
deploy / deploy (push) Successful in 40s

- Gardée sur l'appareil : une fiche déjà ouverte affiche sa note et sa répartition immédiatement (et hors-ligne), rafraîchie en arrière-plan
- La fiche n'attend plus Trakt pour le casting et « Où regarder » ; pendant le premier chargement, place réservée sans chiffre provisoire (plus de bascule TMDB → Trakt)
- Préchargement dès qu'on touche une affiche (ou qu'on la survole à la souris) : la fiche s'ouvre avec ses infos
- Serveur : notes Trakt gardées 24 h pour tout le monde (table title_ratings), correspondance TMDB → Trakt gardée pour toujours ; une note plus ancienne est renvoyée tout de suite puis rafraîchie

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-11-29 15:13:59 +00:00
1 parent e627e935c4
commit f3b7d0c025
16 files changed
+326 -75

No files matched your search

+118 -30
View File
@@ -1,21 +1,77 @@
// 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 Ratings {
rating: number
interface Row {
external_id: string
trakt_id: number | null
found: boolean
rating: number | null
votes: number
distribution: Record<string, number>
distribution: Record<string, number> | null
fetched_at: string
}
// Réponses gardées 12 h par instance (les notes bougent lentement) : moins d'appels à Trakt
const cache = new Map<string, { at: number; body: string }>()
const TTL = 12 * 3600_000
interface TraktRatings {
rating?: number
votes?: number
distribution?: Record<string, number>
}
// Mémoire de l'instance : évite même la lecture en base
const mem = new Map<string, Row>()
/** Laisse une tâche finir après la réponse (enregistrement, rafraîchissement). */
const inBackground = (p: Promise<unknown>) => (globalThis as { EdgeRuntime?: { waitUntil?: (p: Promise<unknown>) => void } }).EdgeRuntime?.waitUntil?.(p)
function db(path: string, init: RequestInit = {}): Promise<Response> {
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<Row | null> {
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<void> {
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<T>(path: string): Promise<T | null> {
const res = await fetch(TRAKT + path, {
@@ -35,6 +91,27 @@ async function trakt<T>(path: string): Promise<T | null> {
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<Row> {
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<TraktRatings>(`/${type}s/${traktId}/ratings`)
if (!r) return { ...base, trakt_id: traktId, found: false, rating: null, votes: 0, distribution: null }
const distribution: Record<string, number> = {}
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' })
@@ -54,33 +131,44 @@ Deno.serve(async (req) => {
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',
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)
}
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<Ratings>(`/${type}s/${traktId}/ratings`)
if (r) {
const distribution: Record<string, number> = {}
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 })
}
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(() => {}),
)
}
if (cache.size > 5000) cache.clear()
cache.set(key, { at: Date.now(), body })
return new Response(body, { status: 200, headers })
return respond(row)
}
// Jamais vue : Trakt maintenant (l'enregistrement en base ne retarde pas la réponse)
try {
const fresh = await fetchTrakt(ext, kind, id)
remember(fresh)
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' })
@@ -0,0 +1,15 @@
-- Bobinoo — 29 nov. 2026 : notes Trakt gardées côté serveur (pour tout le monde). Idempotent.
-- La fonction serveur « ratings » lit ici avant d'interroger Trakt : une fiche déjà vue dans la journée
-- (par n'importe qui) a sa note tout de suite. La correspondance TMDB → Trakt, elle, ne change jamais.
-- Données publiques (notes du public Trakt) ; seule la fonction serveur y accède (clé de service) : aucune règle d'accès.
create table if not exists public.title_ratings (
external_id text primary key check (external_id ~ '^tmdb:(movie|tv):[0-9]{1,10}$'),
trakt_id integer,
found boolean not null default true,
rating numeric(4, 2),
votes integer not null default 0 check (votes >= 0),
distribution jsonb,
fetched_at timestamptz not null default now()
);
alter table public.title_ratings enable row level security;
revoke all on public.title_ratings from public, anon, authenticated;