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

+101 -15
View File
@@ -998,10 +998,8 @@ export interface TitleExtras {
/** Note moyenne du public, sur 10 */
average?: number
votes?: number
/** Répartition des notes du public (AniList, ou Trakt pour les films et séries) : note sur 10 → nombre de votes */
/** Répartition des notes du public (AniList) : note sur 10 → nombre de votes. Films et séries : voir getPublicRatings (Trakt) */
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[]
@@ -1039,8 +1037,6 @@ async function tmdbExtras(externalId: string, key: string): Promise<TitleExtras>
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<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
if (key.trim() !== CLOUD_TMDB || !(e instanceof Error) || e.message !== t('err.tmdbStatus', { status: 400 })) throw e
@@ -1059,18 +1055,10 @@ async function tmdbExtras(externalId: string, key: string): Promise<TitleExtras>
.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: useTrakt ? Math.round(r!.rating! * 10) / 10 : tmdbPublicRating(d.vote_average, d.vote_count),
votes: useTrakt ? r!.votes : votes,
distribution,
ratingSource: useTrakt ? 'Trakt' : undefined,
average: tmdbPublicRating(d.vote_average, d.vote_count),
votes,
cast,
directors:
kind === 'movie'
@@ -1162,6 +1150,104 @@ async function aniListExtras(externalId: string): Promise<TitleExtras> {
}
}
// ─────────────────────────── Notes du public Trakt (films et séries) ───────────────────────────
/** Note du public Trakt : moyenne (sur 10), votes et répartition de 1 à 10. */
export interface PublicRatings {
average: number
votes: number
distribution: { score: number; amount: number }[]
}
// Gardées sur l'appareil : une fiche déjà ouverte affiche sa note tout de suite (et hors-ligne), puis la rafraîchit
const RATINGS_KEY = 'azuucine:ratings'
const RATINGS_MAX = 800
const RATINGS_FRESH = 2 * 24 * 3600_000
type RatingsEntry = { r: PublicRatings | null; at: number }
let ratingsMem: Map<string, RatingsEntry> | undefined
let ratingsSave: ReturnType<typeof setTimeout> | undefined
const ratingsInflight = new Map<string, Promise<PublicRatings | null>>()
function ratingsStore(): Map<string, RatingsEntry> {
if (ratingsMem) return ratingsMem
ratingsMem = new Map()
try {
const raw = JSON.parse(localStorage.getItem(RATINGS_KEY) ?? '{}') as Record<string, unknown>
for (const [k, v] of Object.entries(raw ?? {})) {
if (!/^tmdb:(movie|tv):\d{1,10}$/.test(k) || !Array.isArray(v) || typeof v[3] !== 'number') continue
const [average, votes, dist, at] = v as [unknown, unknown, unknown, number]
const ok = typeof average === 'number' && average > 0 && average <= 10 && typeof votes === 'number' && Array.isArray(dist) && dist.length === 10
ratingsMem.set(k, {
r: ok ? { average, votes, distribution: (dist as unknown[]).map((n, i) => ({ score: i + 1, amount: typeof n === 'number' && n >= 0 ? n : 0 })) } : null,
at,
})
}
} catch {
/* copie illisible ou stockage bloqué : on repart de zéro */
}
return ratingsMem
}
function saveRatings() {
clearTimeout(ratingsSave)
ratingsSave = setTimeout(() => {
try {
const entries = [...ratingsStore().entries()].sort((a, b) => b[1].at - a[1].at).slice(0, RATINGS_MAX)
const out: Record<string, unknown> = {}
for (const [k, { r, at }] of entries) out[k] = r ? [r.average, r.votes, r.distribution.map((d) => d.amount), at] : [0, 0, null, at]
localStorage.setItem(RATINGS_KEY, JSON.stringify(out))
} catch {
/* stockage plein ou bloqué : la note sera simplement redemandée */
}
}, 800)
}
/** Dernière note Trakt connue sur cet appareil (affichage immédiat). `undefined` : jamais demandée ; `null` : pas de note Trakt. */
export function cachedPublicRatings(externalId: string | undefined): PublicRatings | null | undefined {
return externalId ? ratingsStore().get(externalId)?.r : undefined
}
/** Note Trakt d'un film ou d'une série (via notre serveur), dédoublonnée et gardée sur l'appareil. */
export function getPublicRatings(externalId: string): Promise<PublicRatings | null> {
const m = /^tmdb:(movie|tv):(\d{1,10})$/.exec(externalId)
if (!m) return Promise.resolve(null)
const hit = ratingsStore().get(externalId)
if (hit && Date.now() - hit.at < RATINGS_FRESH) return Promise.resolve(hit.r)
let p = ratingsInflight.get(externalId)
if (!p) {
p = ratingsViaCloud(m[1] as 'movie' | 'tv', m[2])
.then((d) => {
// Trop peu de votes : la note TMDB reste plus parlante
const r: PublicRatings | null =
d && d.rating != null && d.votes >= 20
? {
average: Math.round(d.rating * 10) / 10,
votes: d.votes,
distribution: Object.entries(d.distribution).map(([score, amount]) => ({ score: Number(score), amount })).sort((a, b) => a.score - b.score),
}
: null
ratingsStore().set(externalId, { r, at: Date.now() })
saveRatings()
return r
})
.finally(() => ratingsInflight.delete(externalId))
ratingsInflight.set(externalId, p)
}
return p
}
// Clé TMDB du moment (compte, visiteur ou clé perso), pour le préchargement
let prefetchKey: string | undefined
export const setPrefetchKey = (key?: string) => void (prefetchKey = key)
/** Commence à charger une fiche dès qu'on touche son affiche : elle s'ouvre avec ses infos déjà là. */
export function prefetchTitle(externalId: string | null | undefined): void {
if (!externalId || !navigator.onLine || !isSafeExternalId(externalId)) return
const isTmdb = externalId.startsWith('tmdb:')
if (!isTmdb || prefetchKey?.trim()) void getTitleExtras(externalId, prefetchKey).catch(() => {})
if (isTmdb) void getPublicRatings(externalId).catch(() => {})
}
/** Infos de la fiche (note moyenne, votes, casting…), gardées en mémoire le temps de la session. */
export function getTitleExtras(externalId: string, tmdbKey?: string): Promise<TitleExtras> {
if (!isSafeExternalId(externalId)) return Promise.reject(new Error(t('err.tmdbRef')))
+3 -2
View File
@@ -48,14 +48,15 @@ export async function tmdbViaCloud<T>(path: string, params: Record<string, strin
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. */
/** Notes du public d'un film ou d'une série (Trakt, via notre serveur) : moyenne sur 10, votes, répartition 1→10.
* `null` : Trakt ne connaît pas le titre. Erreur réseau ou serveur : exception (rien n'est gardé). */
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
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
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> = {}