Répartition des notes sur les fiches de films et séries (Trakt)
deploy / deploy (push) Successful in 42s
deploy / deploy (push) Successful in 42s
- 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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
5 files changed
+130
-5
No files matched your search
@@ -327,7 +327,7 @@ export default function TitleSheet({ item: initial, seed, onClose, onOpenPerson,
|
|||||||
|
|
||||||
const heroImage = backdrop ?? extras?.backdrop
|
const heroImage = backdrop ?? extras?.backdrop
|
||||||
const average = extras?.average ?? data.publicRating
|
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 runtime = type === 'film' ? (data.duration ?? extras?.runtime) : undefined
|
||||||
const metaLine = [
|
const metaLine = [
|
||||||
data.year,
|
data.year,
|
||||||
|
|||||||
+16
-4
@@ -1,6 +1,6 @@
|
|||||||
import type { MediaInput, MediaType } from '../types'
|
import type { MediaInput, MediaType } from '../types'
|
||||||
import { region, t, tmdbLanguage } from '../i18n'
|
import { region, t, tmdbLanguage } from '../i18n'
|
||||||
import { tmdbViaCloud } from './cloud/api'
|
import { ratingsViaCloud, tmdbViaCloud } from './cloud/api'
|
||||||
import { TYPE_BY_VALUE } from './constants'
|
import { TYPE_BY_VALUE } from './constants'
|
||||||
import { subtypeLabel, tmdbGenres } from './genres'
|
import { subtypeLabel, tmdbGenres } from './genres'
|
||||||
import { franchiseKey } from './franchise'
|
import { franchiseKey } from './franchise'
|
||||||
@@ -998,8 +998,10 @@ export interface TitleExtras {
|
|||||||
/** Note moyenne du public, sur 10 */
|
/** Note moyenne du public, sur 10 */
|
||||||
average?: number
|
average?: number
|
||||||
votes?: 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 }[]
|
distribution?: { score: number; amount: number }[]
|
||||||
|
/** D'où vient la note moyenne (« Trakt » quand elle remplace celle de TMDB) */
|
||||||
|
ratingSource?: string
|
||||||
cast: CastMember[]
|
cast: CastMember[]
|
||||||
/** Réalisation (films) ou création (séries) */
|
/** Réalisation (films) ou création (séries) */
|
||||||
directors: string[]
|
directors: string[]
|
||||||
@@ -1037,6 +1039,8 @@ async function tmdbExtras(externalId: string, key: string): Promise<TitleExtras>
|
|||||||
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
|
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
|
// 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.
|
// (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<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits,watch/providers' }).catch((e: unknown) => {
|
const d = await tmdbFetch<TmdbExtras>(`/${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
|
// 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
|
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<TitleExtras>
|
|||||||
.filter((c): c is CastMember => !!c.name)
|
.filter((c): c is CastMember => !!c.name)
|
||||||
const crew = Array.isArray(d.credits?.crew) ? d.credits!.crew! : []
|
const crew = Array.isArray(d.credits?.crew) ? d.credits!.crew! : []
|
||||||
const votes = count(d.vote_count, 100_000_000)
|
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 {
|
return {
|
||||||
backdrop: isSafeTmdbPath(d.backdrop_path) ? `${TMDB_IMG}/w780${d.backdrop_path}` : undefined,
|
backdrop: isSafeTmdbPath(d.backdrop_path) ? `${TMDB_IMG}/w780${d.backdrop_path}` : undefined,
|
||||||
average: tmdbPublicRating(d.vote_average, d.vote_count),
|
average: useTrakt ? Math.round(r!.rating! * 10) / 10 : tmdbPublicRating(d.vote_average, d.vote_count),
|
||||||
votes,
|
votes: useTrakt ? r!.votes : votes,
|
||||||
|
distribution,
|
||||||
|
ratingSource: useTrakt ? 'Trakt' : undefined,
|
||||||
cast,
|
cast,
|
||||||
directors:
|
directors:
|
||||||
kind === 'movie'
|
kind === 'movie'
|
||||||
|
|||||||
@@ -47,3 +47,25 @@ export async function tmdbViaCloud<T>(path: string, params: Record<string, strin
|
|||||||
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
|
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
|
||||||
return res.json() as Promise<T>
|
return res.json() as Promise<T>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 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<string, number> } | 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<string, number> = {}
|
||||||
|
for (let s = 1; s <= 10; s++) {
|
||||||
|
const n = (d.distribution as Record<string, unknown>)[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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,3 +10,6 @@ verify_jwt = false
|
|||||||
[functions.delete-account]
|
[functions.delete-account]
|
||||||
verify_jwt = false
|
verify_jwt = false
|
||||||
|
|
||||||
|
|
||||||
|
[functions.ratings]
|
||||||
|
verify_jwt = false
|
||||||
@@ -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<string, number>
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
|
||||||
|
async function trakt<T>(path: string): Promise<T | null> {
|
||||||
|
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<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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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' })
|
||||||
|
}
|
||||||
|
})
|
||||||
Reference in new issue
Block a user