- 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:
16 files changed
+326
-75
No files matched your search
+19
-2
@@ -7,7 +7,7 @@ import HomePage from './pages/HomePage'
|
|||||||
import CatalogPage from './pages/CatalogPage'
|
import CatalogPage from './pages/CatalogPage'
|
||||||
import SyncIndicator from './components/SyncIndicator'
|
import SyncIndicator from './components/SyncIndicator'
|
||||||
import { useMedia } from './store'
|
import { useMedia } from './store'
|
||||||
import type { SearchResult } from './lib/catalogApi'
|
import { prefetchTitle, setPrefetchKey, type SearchResult } from './lib/catalogApi'
|
||||||
import type { MediaItem } from './types'
|
import type { MediaItem } from './types'
|
||||||
import type { Completion } from './lib/seasons'
|
import type { Completion } from './lib/seasons'
|
||||||
|
|
||||||
@@ -65,7 +65,24 @@ type Layer =
|
|||||||
let layerUid = 0
|
let layerUid = 0
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const { error } = useMedia()
|
const { error, settings } = useMedia()
|
||||||
|
|
||||||
|
// Préchargement d'une fiche dès qu'on touche (ou survole à la souris) une affiche marquée data-prefetch :
|
||||||
|
// infos TMDB et note Trakt arrivent pendant l'appui, la fiche s'ouvre avec tout déjà là
|
||||||
|
useEffect(() => setPrefetchKey(settings.tmdbKey), [settings.tmdbKey])
|
||||||
|
useEffect(() => {
|
||||||
|
const onPointer = (e: PointerEvent) => {
|
||||||
|
if (e.type === 'pointerover' && e.pointerType !== 'mouse') return
|
||||||
|
const el = e.target instanceof Element ? e.target.closest('[data-prefetch]') : null
|
||||||
|
if (el) prefetchTitle(el.getAttribute('data-prefetch'))
|
||||||
|
}
|
||||||
|
document.addEventListener('pointerdown', onPointer, { capture: true, passive: true })
|
||||||
|
document.addEventListener('pointerover', onPointer, { passive: true })
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('pointerdown', onPointer, { capture: true })
|
||||||
|
document.removeEventListener('pointerover', onPointer)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
const [route, setRoute] = useState<Route>(routeFromHash)
|
const [route, setRoute] = useState<Route>(routeFromHash)
|
||||||
const [layers, setLayers] = useState<(Layer & { uid: number })[]>([])
|
const [layers, setLayers] = useState<(Layer & { uid: number })[]>([])
|
||||||
const pushLayer = (l: Layer) => setLayers((ls) => [...ls.slice(-11), { ...l, uid: ++layerUid }])
|
const pushLayer = (l: Layer) => setLayers((ls) => [...ls.slice(-11), { ...l, uid: ++layerUid }])
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ function EntryRow({ e, onOpen, onAdd, busy, added }: { e: Entry; onOpen: (i: Med
|
|||||||
)
|
)
|
||||||
if (mine) {
|
if (mine) {
|
||||||
return (
|
return (
|
||||||
<button onClick={() => onOpen(e.item!)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
<button data-prefetch={e.item?.externalId} onClick={() => onOpen(e.item!)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
||||||
{body}
|
{body}
|
||||||
<ChevronRight size={16} className="shrink-0 text-ink-3" />
|
<ChevronRight size={16} className="shrink-0 text-ink-3" />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
|
|||||||
if (Math.abs(dx) > 45) go(current + (dx < 0 ? 1 : -1))
|
if (Math.abs(dx) > 45) go(current + (dx < 0 ? 1 : -1))
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<button onClick={() => onOpen(item)} className="relative block aspect-video w-full overflow-hidden bg-surface-2 lg:aspect-auto lg:h-full lg:min-h-[22rem]" aria-label={t('card.open', { title: item.title })}>
|
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="relative block aspect-video w-full overflow-hidden bg-surface-2 lg:aspect-auto lg:h-full lg:min-h-[22rem]" aria-label={t('card.open', { title: item.title })}>
|
||||||
{items.map((it, k) => {
|
{items.map((it, k) => {
|
||||||
const image = it.backdrop ?? it.poster
|
const image = it.backdrop ?? it.poster
|
||||||
return image ? (
|
return image ? (
|
||||||
@@ -164,7 +164,7 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
|
|||||||
<Check size={17} /> {waitingLabel(item)}
|
<Check size={17} /> {waitingLabel(item)}
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
<button onClick={() => onOpen(item)} className="btn btn-ghost px-4">
|
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="btn btn-ghost px-4">
|
||||||
<Info size={17} /> {t('homeHero.details')}
|
<Info size={17} /> {t('homeHero.details')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -196,7 +196,7 @@ export function ContinueCard({ item, onOpen }: { item: MediaItem; onOpen: (item:
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<article className="flex h-[5.5rem] w-72 shrink-0 overflow-hidden rounded-md border border-line bg-surface">
|
<article className="flex h-[5.5rem] w-72 shrink-0 overflow-hidden rounded-md border border-line bg-surface">
|
||||||
<button onClick={() => onOpen(item)} className="flex min-w-0 flex-1 items-stretch text-start" aria-label={t('card.open', { title: item.title })}>
|
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="flex min-w-0 flex-1 items-stretch text-start" aria-label={t('card.open', { title: item.title })}>
|
||||||
<span className="block w-[3.6rem] shrink-0 bg-surface-2">{image && <img src={image} alt="" loading="lazy" className="size-full object-cover" />}</span>
|
<span className="block w-[3.6rem] shrink-0 bg-surface-2">{image && <img src={image} alt="" loading="lazy" className="size-full object-cover" />}</span>
|
||||||
<span className="flex min-w-0 flex-1 flex-col justify-center px-3">
|
<span className="flex min-w-0 flex-1 flex-col justify-center px-3">
|
||||||
<span className="block truncate font-bold text-base leading-tight">{item.title}</span>
|
<span className="block truncate font-bold text-base leading-tight">{item.title}</span>
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ export default function JournalView({ onOpen }: { onOpen: (item: MediaItem) => v
|
|||||||
const d = new Date(e.date + 'T12:00:00')
|
const d = new Date(e.date + 'T12:00:00')
|
||||||
return (
|
return (
|
||||||
<li key={e.item.id + e.date + e.kind}>
|
<li key={e.item.id + e.date + e.kind}>
|
||||||
<button onClick={() => onOpen(e.item)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
<button data-prefetch={e.item.externalId} onClick={() => onOpen(e.item)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
||||||
<span className="w-9 shrink-0 text-center">
|
<span className="w-9 shrink-0 text-center">
|
||||||
<span className="block text-xl font-bold leading-none tabular-nums">{d.getDate()}</span>
|
<span className="block text-xl font-bold leading-none tabular-nums">{d.getDate()}</span>
|
||||||
<span className="block text-[10px] text-ink-3">{d.toLocaleDateString(locale(), { weekday: 'short' }).replace('.', '')}</span>
|
<span className="block text-[10px] text-ink-3">{d.toLocaleDateString(locale(), { weekday: 'short' }).replace('.', '')}</span>
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ export default function LatestReleases({ onOpenSeed }: { onOpenSeed: (seed: Sear
|
|||||||
return (
|
return (
|
||||||
<div key={r.externalId} className="w-28 shrink-0">
|
<div key={r.externalId} className="w-28 shrink-0">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<button onClick={() => void open(r)} className="block w-full" aria-label={t('card.open', { title: r.title })}>
|
<button data-prefetch={r.externalId} onClick={() => void open(r)} className="block w-full" aria-label={t('card.open', { title: r.title })}>
|
||||||
<Poster src={r.poster} title={r.title} />
|
<Poster src={r.poster} title={r.title} />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ export const MediaCard = memo(function MediaCard({ item, onOpen }: { item: Media
|
|||||||
return (
|
return (
|
||||||
<article>
|
<article>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<button onClick={() => onOpen(item)} className="block w-full" aria-label={t('card.open', { title: item.title })}>
|
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="block w-full" aria-label={t('card.open', { title: item.title })}>
|
||||||
<Poster src={item.poster} title={item.title} />
|
<Poster src={item.poster} title={item.title} />
|
||||||
</button>
|
</button>
|
||||||
<TypeBadge item={item} className="pointer-events-none absolute start-2 top-2 border-transparent bg-bg/85" />
|
<TypeBadge item={item} className="pointer-events-none absolute start-2 top-2 border-transparent bg-bg/85" />
|
||||||
@@ -69,7 +69,7 @@ export const MediaCard = memo(function MediaCard({ item, onOpen }: { item: Media
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<button onClick={() => onOpen(item)} className="block w-full text-start">
|
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="block w-full text-start">
|
||||||
<h3 className="mt-2.5 line-clamp-2 font-sans text-sm font-semibold leading-snug tracking-normal">{item.title}</h3>
|
<h3 className="mt-2.5 line-clamp-2 font-sans text-sm font-semibold leading-snug tracking-normal">{item.title}</h3>
|
||||||
<div className="mt-1 flex items-center justify-between gap-2">
|
<div className="mt-1 flex items-center justify-between gap-2">
|
||||||
<StatusPill status={item.status} />
|
<StatusPill status={item.status} />
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ export default function TopFive({ onOpen, items: others }: { onOpen: (item: Medi
|
|||||||
<RankNumber rank={1} big />
|
<RankNumber rank={1} big />
|
||||||
</span>
|
</span>
|
||||||
{first ? (
|
{first ? (
|
||||||
<button onClick={() => onOpen(first)} className="relative z-10 w-32 lg:w-40">
|
<button data-prefetch={first.externalId} onClick={() => onOpen(first)} className="relative z-10 w-32 lg:w-40">
|
||||||
<Poster src={first.poster} title={first.title} />
|
<Poster src={first.poster} title={first.title} />
|
||||||
</button>
|
</button>
|
||||||
) : (
|
) : (
|
||||||
@@ -121,7 +121,7 @@ export default function TopFive({ onOpen, items: others }: { onOpen: (item: Medi
|
|||||||
<span className="eyebrow text-accent">{t('top.number', { rank: 1 })} · {current.plural}</span>
|
<span className="eyebrow text-accent">{t('top.number', { rank: 1 })} · {current.plural}</span>
|
||||||
{first ? (
|
{first ? (
|
||||||
<>
|
<>
|
||||||
<button onClick={() => onOpen(first)} className="mt-1.5 block text-start text-lg font-bold leading-snug">
|
<button data-prefetch={first.externalId} onClick={() => onOpen(first)} className="mt-1.5 block text-start text-lg font-bold leading-snug">
|
||||||
{first.title}
|
{first.title}
|
||||||
</button>
|
</button>
|
||||||
<div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-ink-3">
|
<div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-ink-3">
|
||||||
@@ -149,7 +149,7 @@ export default function TopFive({ onOpen, items: others }: { onOpen: (item: Medi
|
|||||||
</span>
|
</span>
|
||||||
<div className="relative z-10 ms-4">
|
<div className="relative z-10 ms-4">
|
||||||
{item ? (
|
{item ? (
|
||||||
<button onClick={() => onOpen(item)} className="block w-full">
|
<button data-prefetch={item.externalId} onClick={() => onOpen(item)} className="block w-full">
|
||||||
<Poster src={item.poster} title={item.title} />
|
<Poster src={item.poster} title={item.title} />
|
||||||
</button>
|
</button>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -174,7 +174,7 @@ export default function PersonSheet({
|
|||||||
const it = mine(c.result)
|
const it = mine(c.result)
|
||||||
return (
|
return (
|
||||||
<li key={c.group + c.result.externalId}>
|
<li key={c.group + c.result.externalId}>
|
||||||
<button onClick={() => (it ? onOpenItem(it) : onOpenSeed(c.result))} className="group block w-full text-start">
|
<button data-prefetch={it?.externalId ?? c.result.externalId} onClick={() => (it ? onOpenItem(it) : onOpenSeed(c.result))} className="group block w-full text-start">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Poster src={c.result.posterUrl ?? c.result.thumb} title={c.result.title} />
|
<Poster src={c.result.posterUrl ?? c.result.thumb} title={c.result.title} />
|
||||||
{it && (
|
{it && (
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import { useSocial } from './SocialProvider'
|
|||||||
|
|
||||||
function PosterTile({ item, onOpen, caption }: { item: MediaItem; onOpen: () => void; caption?: string }) {
|
function PosterTile({ item, onOpen, caption }: { item: MediaItem; onOpen: () => void; caption?: string }) {
|
||||||
return (
|
return (
|
||||||
<button onClick={onOpen} className="block w-full text-start">
|
<button data-prefetch={item.externalId} onClick={onOpen} className="block w-full text-start">
|
||||||
<Poster src={item.poster} title={item.title} />
|
<Poster src={item.poster} title={item.title} />
|
||||||
<p className="mt-1.5 truncate text-[11px] font-medium text-ink-2">{item.title}</p>
|
<p className="mt-1.5 truncate text-[11px] font-medium text-ink-2">{item.title}</p>
|
||||||
<p className="flex h-4 items-center gap-1 text-[11px] text-ink-3">
|
<p className="flex h-4 items-center gap-1 text-[11px] text-ink-3">
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ export default function AddTitle({
|
|||||||
const mine = inLibrary(r)
|
const mine = inLibrary(r)
|
||||||
return (
|
return (
|
||||||
<li key={r.externalId}>
|
<li key={r.externalId}>
|
||||||
<button onClick={() => (mine ? onOpenItem(mine) : onPick(r))} className="flex w-full items-center gap-3 py-3 text-start active:bg-surface lg:border-b lg:border-line">
|
<button data-prefetch={r.externalId} onClick={() => (mine ? onOpenItem(mine) : onPick(r))} className="flex w-full items-center gap-3 py-3 text-start active:bg-surface lg:border-b lg:border-line">
|
||||||
{r.thumb ? (
|
{r.thumb ? (
|
||||||
<img src={r.thumb} alt="" loading="lazy" className="h-[5.25rem] w-14 shrink-0 rounded-lg border border-line bg-surface-2 object-cover" />
|
<img src={r.thumb} alt="" loading="lazy" className="h-[5.25rem] w-14 shrink-0 rounded-lg border border-line bg-surface-2 object-cover" />
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { locale, t } from '../../i18n'
|
|||||||
import { FilmStrip } from '../ui'
|
import { FilmStrip } from '../ui'
|
||||||
import { Bookmark, Check, ChevronDown, Eye, Heart, Loader2, MessagesSquare, Minus, MoreHorizontal, Pencil, Play, Plus, Share2, Trash2, X } from 'lucide-react'
|
import { Bookmark, Check, ChevronDown, Eye, Heart, Loader2, MessagesSquare, Minus, MoreHorizontal, Pencil, Play, Plus, Share2, Trash2, X } from 'lucide-react'
|
||||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||||
import { getTitleExtras, getTmdbCredits, getTmdbDetails, getTmdbExtras, type SearchResult, type TitleExtras } from '../../lib/catalogApi'
|
import { cachedPublicRatings, getPublicRatings, getTitleExtras, getTmdbCredits, getTmdbDetails, getTmdbExtras, type PublicRatings, type SearchResult, type TitleExtras } from '../../lib/catalogApi'
|
||||||
import { CRITERIA, STATUS_BY_VALUE, TYPE_BY_VALUE } from '../../lib/constants'
|
import { CRITERIA, STATUS_BY_VALUE, TYPE_BY_VALUE } from '../../lib/constants'
|
||||||
import { genreLabel } from '../../lib/genres'
|
import { genreLabel } from '../../lib/genres'
|
||||||
import { airedCount, nextAirDate, useAiringCache } from '../../lib/airing'
|
import { airedCount, nextAirDate, useAiringCache } from '../../lib/airing'
|
||||||
@@ -107,6 +107,26 @@ export default function TitleSheet({ item: initial, seed, onClose, onOpenPerson,
|
|||||||
}
|
}
|
||||||
}, [externalId, settings.tmdbKey])
|
}, [externalId, settings.tmdbKey])
|
||||||
|
|
||||||
|
// Note du public Trakt (films et séries), à part du reste de la fiche (qui ne l'attend plus) :
|
||||||
|
// la copie gardée sur l'appareil s'affiche tout de suite, puis est rafraîchie si elle date un peu
|
||||||
|
const isTmdbTitle = !!externalId?.startsWith('tmdb:')
|
||||||
|
const [trakt, setTrakt] = useState<PublicRatings | null | undefined>(() => (isTmdbTitle ? cachedPublicRatings(externalId) : undefined))
|
||||||
|
useEffect(() => {
|
||||||
|
if (!externalId?.startsWith('tmdb:')) return
|
||||||
|
// Hors-ligne et rien de gardé : on s'en tient à la note TMDB
|
||||||
|
if (!navigator.onLine) return setTrakt((v) => v ?? null)
|
||||||
|
let alive = true
|
||||||
|
getPublicRatings(externalId).then(
|
||||||
|
(r) => alive && setTrakt(r),
|
||||||
|
() => alive && setTrakt((v) => v ?? null),
|
||||||
|
)
|
||||||
|
return () => {
|
||||||
|
alive = false
|
||||||
|
}
|
||||||
|
}, [externalId])
|
||||||
|
// Note finale (Trakt, ou TMDB / AniList quand Trakt n'en a pas) : undefined tant qu'on ne la connaît pas
|
||||||
|
const publicAvg = trakt ? trakt.average : trakt === null || !isTmdbTitle ? extras?.average : undefined
|
||||||
|
|
||||||
// Fiche TMDB ajoutée avant le suivi par saison : grande image et saisons récupérées en arrière-plan (et gardées)
|
// Fiche TMDB ajoutée avant le suivi par saison : grande image et saisons récupérées en arrière-plan (et gardées)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const key = settings.tmdbKey?.trim()
|
const key = settings.tmdbKey?.trim()
|
||||||
@@ -135,9 +155,9 @@ export default function TitleSheet({ item: initial, seed, onClose, onOpenPerson,
|
|||||||
|
|
||||||
// Garde la note du public de la fiche à jour (utilisée par les stats « Moi vs le public »)
|
// Garde la note du public de la fiche à jour (utilisée par les stats « Moi vs le public »)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (item && extras?.average != null && Math.abs((item.publicRating ?? 0) - extras.average) >= 0.1) void patchMany([{ id: item.id, patch: { publicRating: extras.average } }])
|
if (item && publicAvg != null && Math.abs((item.publicRating ?? 0) - publicAvg) >= 0.1) void patchMany([{ id: item.id, patch: { publicRating: publicAvg } }])
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [extras?.average, item?.id])
|
}, [publicAvg, item?.id])
|
||||||
|
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
const addingRef = useRef(false)
|
const addingRef = useRef(false)
|
||||||
@@ -166,7 +186,7 @@ export default function TitleSheet({ item: initial, seed, onClose, onOpenPerson,
|
|||||||
// On garde l'adresse de l'affiche (le service worker la met en cache : visible hors-ligne). La copier dans
|
// On garde l'adresse de l'affiche (le service worker la met en cache : visible hors-ligne). La copier dans
|
||||||
// la fiche l'alourdissait d'environ 50 Ko, renvoyés au serveur à chaque modification et chez les amis.
|
// la fiche l'alourdissait d'environ 50 Ko, renvoyés au serveur à chaque modification et chez les amis.
|
||||||
if (seed.posterUrl) base.poster = seed.posterUrl
|
if (seed.posterUrl) base.poster = seed.posterUrl
|
||||||
if (extras?.average != null) base.publicRating = extras.average
|
if (publicAvg != null) base.publicRating = publicAvg
|
||||||
const created = await add({
|
const created = await add({
|
||||||
...BLANK,
|
...BLANK,
|
||||||
status: 'a_voir',
|
status: 'a_voir',
|
||||||
@@ -326,8 +346,10 @@ 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
|
// Premier chargement de Trakt (quelques dixièmes de seconde) : place réservée, sans chiffre provisoire qui changerait ensuite
|
||||||
const source = externalId?.startsWith('anilist:') ? 'AniList' : externalId ? (extras?.ratingSource ?? 'TMDB') : undefined
|
const ratingPending = isTmdbTitle && trakt === undefined
|
||||||
|
const average = trakt ? trakt.average : ratingPending ? undefined : (extras?.average ?? data.publicRating)
|
||||||
|
const source = externalId?.startsWith('anilist:') ? 'AniList' : externalId ? (trakt ? 'Trakt' : '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,
|
||||||
@@ -429,7 +451,16 @@ export default function TitleSheet({ item: initial, seed, onClose, onOpenPerson,
|
|||||||
<div className="flex flex-col lg:mt-8 lg:px-6 lg:grid lg:grid-cols-[minmax(0,1fr)_28rem] xl:grid-cols-[minmax(0,1fr)_32rem] lg:items-start lg:gap-6">
|
<div className="flex flex-col lg:mt-8 lg:px-6 lg:grid lg:grid-cols-[minmax(0,1fr)_28rem] xl:grid-cols-[minmax(0,1fr)_32rem] lg:items-start lg:gap-6">
|
||||||
<div className="order-1 lg:col-start-2 lg:row-start-1">
|
<div className="order-1 lg:col-start-2 lg:row-start-1">
|
||||||
{/* Note moyenne du public */}
|
{/* Note moyenne du public */}
|
||||||
{source && <PublicRating average={average} votes={extras?.votes} distribution={extras?.distribution} source={source} mine={item?.rating} />}
|
{source && (
|
||||||
|
<PublicRating
|
||||||
|
average={average}
|
||||||
|
votes={trakt ? trakt.votes : extras?.votes}
|
||||||
|
distribution={trakt ? trakt.distribution : extras?.distribution}
|
||||||
|
source={source}
|
||||||
|
pending={ratingPending}
|
||||||
|
mine={item?.rating}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Mes actions */}
|
{/* Mes actions */}
|
||||||
<section className="card mx-4 mt-4 p-4">
|
<section className="card mx-4 mt-4 p-4">
|
||||||
@@ -756,12 +787,15 @@ function PublicRating({
|
|||||||
distribution,
|
distribution,
|
||||||
source,
|
source,
|
||||||
mine,
|
mine,
|
||||||
|
pending,
|
||||||
}: {
|
}: {
|
||||||
average?: number
|
average?: number
|
||||||
votes?: number
|
votes?: number
|
||||||
distribution?: { score: number; amount: number }[]
|
distribution?: { score: number; amount: number }[]
|
||||||
source: string
|
source: string
|
||||||
mine?: number
|
mine?: number
|
||||||
|
/** Note Trakt en cours de chargement : place du graphique réservée, source pas encore annoncée */
|
||||||
|
pending?: boolean
|
||||||
}) {
|
}) {
|
||||||
const max = Math.max(1, ...(distribution ?? []).map((d) => d.amount))
|
const max = Math.max(1, ...(distribution ?? []).map((d) => d.amount))
|
||||||
const compact = new Intl.NumberFormat(locale(), { notation: 'compact', maximumFractionDigits: 1 })
|
const compact = new Intl.NumberFormat(locale(), { notation: 'compact', maximumFractionDigits: 1 })
|
||||||
@@ -776,10 +810,13 @@ function PublicRating({
|
|||||||
<span className="text-base font-normal text-ink-3">/5</span>
|
<span className="text-base font-normal text-ink-3">/5</span>
|
||||||
</p>
|
</p>
|
||||||
<p className="mt-1.5 text-xs text-ink-3">
|
<p className="mt-1.5 text-xs text-ink-3">
|
||||||
{votes ? `${t('title.votes', { count: votes, n: compact.format(votes) })} · ` : ''}
|
{pending ? '\u00a0' : `${votes ? `${t('title.votes', { count: votes, n: compact.format(votes) })} · ` : ''}${source}`}
|
||||||
{source}
|
|
||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
|
) : pending ? (
|
||||||
|
<p className="mt-1 text-4xl font-bold leading-none text-line-strong" aria-hidden="true">
|
||||||
|
–
|
||||||
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<p className="mt-1 text-sm text-ink-3">{t('title.noAverage')}</p>
|
<p className="mt-1 text-sm text-ink-3">{t('title.noAverage')}</p>
|
||||||
)}
|
)}
|
||||||
@@ -789,14 +826,21 @@ function PublicRating({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{distribution && distribution.length > 0 && (
|
{distribution && distribution.length > 0 ? (
|
||||||
<div className="flex h-16 max-w-48 flex-1 items-end gap-[3px]" role="img" aria-label={t('title.distribution')}>
|
<div className="flex h-16 max-w-48 flex-1 items-end gap-[3px]" role="img" aria-label={t('title.distribution')}>
|
||||||
{Array.from({ length: 10 }, (_, k) => {
|
{Array.from({ length: 10 }, (_, k) => {
|
||||||
const amount = distribution.find((d) => d.score === k + 1)?.amount ?? 0
|
const amount = distribution.find((d) => d.score === k + 1)?.amount ?? 0
|
||||||
return <span key={k} className="flex-1 rounded-t-sm bg-ink-3" style={{ height: `${Math.max(4, (amount / max) * 100)}%`, opacity: amount ? 1 : 0.3 }} />
|
return <span key={k} className="flex-1 rounded-t-sm bg-ink-3" style={{ height: `${Math.max(4, (amount / max) * 100)}%`, opacity: amount ? 1 : 0.3 }} />
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
) : pending ? (
|
||||||
|
// Place réservée pendant le chargement : rien ne bouge quand les barres arrivent
|
||||||
|
<div className="flex h-16 max-w-48 flex-1 animate-pulse items-end gap-[3px]" aria-hidden="true">
|
||||||
|
{[6, 5, 5, 7, 10, 18, 32, 52, 70, 60].map((h, k) => (
|
||||||
|
<span key={k} className="flex-1 rounded-t-sm bg-line" style={{ height: `${h}%` }} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+101
-15
@@ -998,10 +998,8 @@ 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, 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 }[]
|
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[]
|
||||||
@@ -1039,8 +1037,6 @@ 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
|
||||||
@@ -1059,18 +1055,10 @@ 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: useTrakt ? Math.round(r!.rating! * 10) / 10 : tmdbPublicRating(d.vote_average, d.vote_count),
|
average: tmdbPublicRating(d.vote_average, d.vote_count),
|
||||||
votes: useTrakt ? r!.votes : votes,
|
votes,
|
||||||
distribution,
|
|
||||||
ratingSource: useTrakt ? 'Trakt' : undefined,
|
|
||||||
cast,
|
cast,
|
||||||
directors:
|
directors:
|
||||||
kind === 'movie'
|
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. */
|
/** 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> {
|
export function getTitleExtras(externalId: string, tmdbKey?: string): Promise<TitleExtras> {
|
||||||
if (!isSafeExternalId(externalId)) return Promise.reject(new Error(t('err.tmdbRef')))
|
if (!isSafeExternalId(externalId)) return Promise.reject(new Error(t('err.tmdbRef')))
|
||||||
|
|||||||
@@ -48,14 +48,15 @@ export async function tmdbViaCloud<T>(path: string, params: Record<string, strin
|
|||||||
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. */
|
/** 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> {
|
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
|
if (!/^\d{1,10}$/.test(id)) return null
|
||||||
const q = new URLSearchParams({ kind, id })
|
const q = new URLSearchParams({ kind, id })
|
||||||
const res = (await getAccessToken())
|
const res = (await getAccessToken())
|
||||||
? await cloudFetch(`/functions/v1/ratings?${q}`)
|
? await cloudFetch(`/functions/v1/ratings?${q}`)
|
||||||
: await timedFetch(`${SUPABASE_URL}/functions/v1/ratings?${q}`, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' })
|
: 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
|
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
|
if (!d?.found || typeof d.distribution !== 'object' || !d.distribution) return null
|
||||||
const distribution: Record<string, number> = {}
|
const distribution: Record<string, number> = {}
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ function PosterStrip({ items, onOpen }: { items: MediaItem[]; onOpen: (item: Med
|
|||||||
return (
|
return (
|
||||||
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
|
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
|
||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<button key={item.id} onClick={() => onOpen(item)} className="w-32 shrink-0 text-start">
|
<button key={item.id} data-prefetch={item.externalId} onClick={() => onOpen(item)} className="w-32 shrink-0 text-start">
|
||||||
<Poster src={item.poster} title={item.title} />
|
<Poster src={item.poster} title={item.title} />
|
||||||
<p className="mt-2 truncate text-sm font-semibold leading-snug">{item.title}</p>
|
<p className="mt-2 truncate text-sm font-semibold leading-snug">{item.title}</p>
|
||||||
<p className="flex gap-2 truncate text-xs text-ink-3">
|
<p className="flex gap-2 truncate text-xs text-ink-3">
|
||||||
|
|||||||
@@ -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.
|
// 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.
|
// 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.
|
// 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'
|
import { corsHeaders, getUserId, json, rateLimited } from '../_shared/auth.ts'
|
||||||
|
|
||||||
const TRAKT_KEY = Deno.env.get('TRAKT_CLIENT_ID') ?? ''
|
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 TRAKT = 'https://api.trakt.tv'
|
||||||
|
const FRESH_MS = 24 * 3600_000
|
||||||
|
|
||||||
interface Ratings {
|
interface Row {
|
||||||
rating: number
|
external_id: string
|
||||||
|
trakt_id: number | null
|
||||||
|
found: boolean
|
||||||
|
rating: number | null
|
||||||
votes: number
|
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
|
interface TraktRatings {
|
||||||
const cache = new Map<string, { at: number; body: string }>()
|
rating?: number
|
||||||
const TTL = 12 * 3600_000
|
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> {
|
async function trakt<T>(path: string): Promise<T | null> {
|
||||||
const res = await fetch(TRAKT + path, {
|
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)
|
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) => {
|
Deno.serve(async (req) => {
|
||||||
if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(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 (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' })
|
if (rateLimited(`ratings-ip:${ip.slice(0, 64)}`, 100, 10 * 60_000)) return json(req, 429, { error: 'rate' })
|
||||||
}
|
}
|
||||||
|
|
||||||
const key = `${kind}:${id}`
|
const respond = (row: Row) =>
|
||||||
const hit = cache.get(key)
|
new Response(bodyOf(row), {
|
||||||
const headers = {
|
status: 200,
|
||||||
...corsHeaders(req),
|
headers: { ...corsHeaders(req), 'Content-Type': 'application/json; charset=utf-8', 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, max-age=21600' },
|
||||||
'Content-Type': 'application/json; charset=utf-8',
|
})
|
||||||
'X-Content-Type-Options': 'nosniff',
|
const remember = (row: Row) => {
|
||||||
'Cache-Control': 'private, max-age=21600',
|
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'
|
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(() => {}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return respond(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Jamais vue : Trakt maintenant (l'enregistrement en base ne retarde pas la réponse)
|
||||||
try {
|
try {
|
||||||
const found = await trakt<{ type?: string; movie?: { ids?: { trakt?: number } }; show?: { ids?: { trakt?: number } } }[]>(`/search/tmdb/${id}?type=${type}`)
|
const fresh = await fetchTrakt(ext, kind, id)
|
||||||
const traktId = found?.find((r) => r.type === type)?.[type]?.ids?.trakt
|
remember(fresh)
|
||||||
let body = JSON.stringify({ found: false })
|
inBackground(saveRow(fresh))
|
||||||
if (typeof traktId === 'number') {
|
return respond(fresh)
|
||||||
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) {
|
} catch (e) {
|
||||||
const timeout = e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError')
|
const timeout = e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError')
|
||||||
return json(req, timeout ? 504 : 502, { error: timeout ? 'timeout' : 'upstream' })
|
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;
|
||||||
Reference in new issue
Block a user