From 7f53445d273091c3c67c32ee8ec170351fede411 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 10:39:53 +0000 Subject: [PATCH] =?UTF-8?q?R=C3=A9partition=20des=20notes=20sur=20les=20fi?= =?UTF-8?q?ches=20de=20films=20et=20s=C3=A9ries=20(Trakt)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fonction serveur « ratings » : moyenne, votes et répartition 1→10 de Trakt à partir de l'identifiant TMDB (clé TRAKT_CLIENT_ID côté serveur) - Fiche : la note Trakt remplace celle de TMDB quand il y a au moins 20 votes, avec le graphique comme pour les animes ; sinon rien ne change Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe --- src/components/title/TitleSheet.tsx | 2 +- src/lib/catalogApi.ts | 20 +++++-- src/lib/cloud/api.ts | 22 ++++++++ supabase/config.toml | 3 + supabase/functions/ratings/index.ts | 88 +++++++++++++++++++++++++++++ 5 files changed, 130 insertions(+), 5 deletions(-) create mode 100644 supabase/functions/ratings/index.ts diff --git a/src/components/title/TitleSheet.tsx b/src/components/title/TitleSheet.tsx index e698254..6f786fd 100644 --- a/src/components/title/TitleSheet.tsx +++ b/src/components/title/TitleSheet.tsx @@ -327,7 +327,7 @@ export default function TitleSheet({ item: initial, seed, onClose, onOpenPerson, const heroImage = backdrop ?? extras?.backdrop const average = extras?.average ?? data.publicRating - const source = externalId?.startsWith('anilist:') ? 'AniList' : externalId ? 'TMDB' : undefined + const source = externalId?.startsWith('anilist:') ? 'AniList' : externalId ? (extras?.ratingSource ?? 'TMDB') : undefined const runtime = type === 'film' ? (data.duration ?? extras?.runtime) : undefined const metaLine = [ data.year, diff --git a/src/lib/catalogApi.ts b/src/lib/catalogApi.ts index df0a2d1..3a5c2fe 100644 --- a/src/lib/catalogApi.ts +++ b/src/lib/catalogApi.ts @@ -1,6 +1,6 @@ import type { MediaInput, MediaType } from '../types' import { region, t, tmdbLanguage } from '../i18n' -import { tmdbViaCloud } from './cloud/api' +import { ratingsViaCloud, tmdbViaCloud } from './cloud/api' import { TYPE_BY_VALUE } from './constants' import { subtypeLabel, tmdbGenres } from './genres' import { franchiseKey } from './franchise' @@ -998,8 +998,10 @@ export interface TitleExtras { /** Note moyenne du public, sur 10 */ average?: number votes?: number - /** Répartition des notes du public (AniList) : note sur 10 → nombre de votes */ + /** Répartition des notes du public (AniList, ou Trakt pour les films et séries) : note sur 10 → nombre de votes */ distribution?: { score: number; amount: number }[] + /** D'où vient la note moyenne (« Trakt » quand elle remplace celle de TMDB) */ + ratingSource?: string cast: CastMember[] /** Réalisation (films) ou création (séries) */ directors: string[] @@ -1037,6 +1039,8 @@ async function tmdbExtras(externalId: string, key: string): Promise const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string] // Une seule requête pour le casting et « Où regarder ». Si le proxy n'accepte pas encore la combinaison // (fonction serveur pas redéployée), on retombe sur le casting seul. + // Répartition des notes : TMDB ne la donne pas, on la demande à Trakt (via notre serveur), en parallèle + const trakt = key.trim() === CLOUD_TMDB ? ratingsViaCloud(kind, id).catch(() => null) : Promise.resolve(null) const d = await tmdbFetch(`/${kind}/${id}`, key, { append_to_response: 'credits,watch/providers' }).catch((e: unknown) => { // Seul un refus du paramètre (400) justifie le second essai : hors ligne, 429, 5xx… on ne double pas la requête if (key.trim() !== CLOUD_TMDB || !(e instanceof Error) || e.message !== t('err.tmdbStatus', { status: 400 })) throw e @@ -1055,10 +1059,18 @@ async function tmdbExtras(externalId: string, key: string): Promise .filter((c): c is CastMember => !!c.name) const crew = Array.isArray(d.credits?.crew) ? d.credits!.crew! : [] const votes = count(d.vote_count, 100_000_000) + // Trakt : moyenne, votes et répartition ensemble (même public), dès qu'il y a assez de votes + const r = await trakt + const useTrakt = !!r && r.rating != null && r.votes >= 20 + const distribution = useTrakt + ? Object.entries(r!.distribution).map(([score, amount]) => ({ score: Number(score), amount })).sort((a, b) => a.score - b.score) + : undefined return { backdrop: isSafeTmdbPath(d.backdrop_path) ? `${TMDB_IMG}/w780${d.backdrop_path}` : undefined, - average: tmdbPublicRating(d.vote_average, d.vote_count), - votes, + average: useTrakt ? Math.round(r!.rating! * 10) / 10 : tmdbPublicRating(d.vote_average, d.vote_count), + votes: useTrakt ? r!.votes : votes, + distribution, + ratingSource: useTrakt ? 'Trakt' : undefined, cast, directors: kind === 'movie' diff --git a/src/lib/cloud/api.ts b/src/lib/cloud/api.ts index c79be5b..b6972f3 100644 --- a/src/lib/cloud/api.ts +++ b/src/lib/cloud/api.ts @@ -47,3 +47,25 @@ export async function tmdbViaCloud(path: string, params: Record } + +/** Notes du public d'un film ou d'une série (Trakt, via notre serveur) : moyenne sur 10, votes, répartition 1→10. */ +export async function ratingsViaCloud(kind: 'movie' | 'tv', id: string): Promise<{ rating?: number; votes: number; distribution: Record } | null> { + if (!/^\d{1,10}$/.test(id)) return null + const q = new URLSearchParams({ kind, id }) + const res = (await getAccessToken()) + ? await cloudFetch(`/functions/v1/ratings?${q}`) + : await timedFetch(`${SUPABASE_URL}/functions/v1/ratings?${q}`, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' }) + if (!res.ok) return null + const d = (await res.json().catch(() => null)) as { found?: boolean; rating?: unknown; votes?: unknown; distribution?: unknown } | null + if (!d?.found || typeof d.distribution !== 'object' || !d.distribution) return null + const distribution: Record = {} + for (let s = 1; s <= 10; s++) { + const n = (d.distribution as Record)[String(s)] + distribution[String(s)] = typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.round(n) : 0 + } + return { + rating: typeof d.rating === 'number' && d.rating > 0 && d.rating <= 10 ? d.rating : undefined, + votes: typeof d.votes === 'number' && d.votes >= 0 ? Math.round(d.votes) : 0, + distribution, + } +} diff --git a/supabase/config.toml b/supabase/config.toml index 6bee282..c63a173 100644 --- a/supabase/config.toml +++ b/supabase/config.toml @@ -10,3 +10,6 @@ verify_jwt = false [functions.delete-account] verify_jwt = false + +[functions.ratings] +verify_jwt = false diff --git a/supabase/functions/ratings/index.ts b/supabase/functions/ratings/index.ts new file mode 100644 index 0000000..4996a41 --- /dev/null +++ b/supabase/functions/ratings/index.ts @@ -0,0 +1,88 @@ +// 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' }) + } +})