Audit : corrections de bugs, sécurité et performances (sans changement de fonctionnement)

Données et synchro
- Import « remplacer » atomique (plus de bibliothèque vidée si l'écriture échoue).
- Deux onglets sur le même compte : mise à jour croisée, file d'envoi partagée sans perte.
- Réception : une modification locale faite pendant la synchro n'est plus écrasée ; une seule transaction.
- Envoi : file vidée paquet par paquet, fiche invalide isolée (quota : gardée en attente), taille en octets réels,
  délai proportionnel à la taille ; grandes affiches décodées sans fetch (bloqué par la CSP).
- Plus d'écriture dans la base d'un autre compte après déconnexion ; base fermée proprement (iOS).
- Revisionnages journalisés à part (rewatchLog) : les défis ne sous-estiment plus le 1er visionnage ;
  décocher des épisodes un autre jour ne gonfle plus les défis.

Comptes et social
- Renouvellement de session : plus de déconnexion de tous les onglets avec un jeton déjà utilisé,
  plus de rafale de renouvellements, déconnexion qui révoque bien la session serveur.
- Délais maximum sur les appels réseau, écran blanc évité au retour de Google.
- Abonnés/abonnements au-delà de 50, pagination du fil et des profils, fil hors-ligne, listes bloquées.
- Code mort retiré (CommentsSheet et options jamais utilisées).

Interface et logique
- Toast qui ne disparaissait plus, focus sur « Annuler » dans les confirmations, Échap pendant la saisie IME.
- Demi-étoile en arabe, flèches RTL, fonds d'overlay en jeton de thème, couleur du thème étoilé.
- Séries en cours sans total connu : les nouveaux épisodes se cochent à nouveau ; épisodes spéciaux ignorés.
- Catalogue, accueil et calendrier plus rapides sur les grosses bibliothèques.

Sources externes
- Proxy TMDB : les 18 langues acceptées (9 étaient refusées), 429 transmis, délais, paramètres durcis.
- Contenus adultes AniList filtrés des recommandations, cache d'import borné, imports plus sûrs.

Serveur (migration 20261122140000_audit_hardening.sql, déjà appliquée en ligne)
- Fonctions admin et « comptes suspendus » versionnées ; blocage effectif ; avis robustes ;
  fiches supprimées vidées ; comptes suspendus sans abonnement ni réaction ; objets morts supprimés.

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-24 15:11:01 +00:00
1 parent 0683f77e54
commit 459101bbf8
73 files changed
+2074 -2162

No files matched your search

+5 -5
View File
@@ -60,9 +60,9 @@ npm run build # build de prod
- Garder les fichiers idempotents côté SQL. - Garder les fichiers idempotents côté SQL.
- RTL géré (arabe) : préférer les classes logiques (`ps-`/`pe-`, `ms-`/`me-`, `start-`/`end-`, `border-e`). - RTL géré (arabe) : préférer les classes logiques (`ps-`/`pe-`, `ms-`/`me-`, `start-`/`end-`, `border-e`).
## État / en attente (au 9 oct. 2026) ## État (au 24 nov. 2026)
- Appliqués en ligne : tout jusqu'à `20261008150000`, + `20261009110000_private_tags` et `20261009140000_challenges`. - **Toutes les migrations de `supabase/migrations/` sont appliquées en ligne**, jusqu'à `20261122140000_audit_hardening.sql` incluse.
- **À coller dans SQL Editor** : `supabase/A_COLLER_2026-10-09.sql` (commentaires/spoilers, listes partagées, web push, modération, bugs/erreurs). Idempotent. - **Notifications retirées (22 nov. 2026)** : plus de cloche ni de push. Table `notifications` gardée vide (des fonctions de listes partagées y font encore référence), `azuu_notify` ne fait plus rien. Ne pas les réintroduire sans demande.
- **Notifications retirées (22 nov. 2026)** : plus de cloche ni de push. Migration `20261122120000_remove_notifications.sql` appliquée en ligne (triggers supprimés, `azuu_notify` ne fait plus rien, tables `notifications` / `push_subscriptions` vidées mais gardées). Ne pas les réintroduire sans demande. - **Audit (22-24 nov. 2026)** : `20261122140000_audit_hardening.sql` versionne aussi les fonctions admin / « comptes suspendus » qui n'existaient qu'en ligne. Blocage = le compte bloquant devient invisible pour le bloqué ; fiches supprimées = `data` vidée (trigger `azuu_tombstone`) ; profils lisibles directement seulement par soi-même.
- Sauvegardes : secrets Gitea `SUPABASE_DB_URL` + `BACKUP_PASSPHRASE`, préparation du VPS → voir `deploy/BACKUP.md`. - Sauvegardes : secrets Gitea `SUPABASE_DB_URL` + `BACKUP_PASSPHRASE`, préparation du VPS → voir `deploy/BACKUP.md`.
- Recommandé : activer **Leaked Password Protection** (Authentication → Passwords) ; supprimer `_tmp_ping2` / `_tmp_sd2`. - Leaked Password Protection (Supabase) demande l'offre payante : remplacée par la vérification HIBP côté client (`src/lib/pwned.ts`).
+3 -2
View File
@@ -1,6 +1,6 @@
import { SocialProvider } from './components/social/SocialProvider' import { SocialProvider } from './components/social/SocialProvider'
import { ToastProvider } from './components/Toast' import { ToastProvider } from './components/Toast'
import { useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import BottomNav, { type Tab } from './components/BottomNav' import BottomNav, { type Tab } from './components/BottomNav'
import SideNav from './components/SideNav' import SideNav from './components/SideNav'
import AddTitle from './components/title/AddTitle' import AddTitle from './components/title/AddTitle'
@@ -75,7 +75,8 @@ export default function App() {
const navTab: Tab = route === 'admin' ? 'settings' : route === 'notfound' ? 'home' : route const navTab: Tab = route === 'admin' ? 'settings' : route === 'notfound' ? 'home' : route
/** `focus` : saison (ou série) qu'on vient de finir avec +1 → la fiche s'ouvre sur la note */ /** `focus` : saison (ou série) qu'on vient de finir avec +1 → la fiche s'ouvre sur la note */
const openItem = (item: MediaItem, focus?: Completion) => pushLayer({ kind: 'title', item, focus }) // Stable : les cartes mémorisées (MediaCard) ne se redessinent pas à chaque rendu de l'app
const openItem = useCallback((item: MediaItem, focus?: Completion) => setLayers((ls) => [...ls.slice(-11), { kind: 'title', item, focus, uid: ++layerUid }]), [])
const openSeed = (seed: SearchResult) => pushLayer({ kind: 'title', seed }) const openSeed = (seed: SearchResult) => pushLayer({ kind: 'title', seed })
const openPerson = (p: { id: string; name?: string; photo?: string }) => pushLayer({ kind: 'person', personId: p.id, name: p.name, photo: p.photo }) const openPerson = (p: { id: string; name?: string; photo?: string }) => pushLayer({ kind: 'person', personId: p.id, name: p.name, photo: p.photo })
const openNew = () => setAdding(true) const openNew = () => setAdding(true)
+8 -5
View File
@@ -54,11 +54,14 @@ export default function Root() {
if (!cloudEnabled) return if (!cloudEnabled) return
const off = onSessionChange(setSession) const off = onSessionChange(setSession)
if (redirect === 'checking') { if (redirect === 'checking') {
consumeAuthRedirect().then((r) => { consumeAuthRedirect()
if (r.error) setNotice(r.error) .then((r) => {
setRedirect(r.type === 'recovery' ? 'recovery' : 'none') if (r.error) setNotice(r.error)
setSession(getSession()) setRedirect(r.type === 'recovery' ? 'recovery' : 'none')
}) setSession(getSession())
})
// Échec inattendu (stockage indisponible…) : on n'affiche pas un écran vide indéfiniment
.catch(() => setRedirect('none'))
} }
return () => { return () => {
off() off()
+2
View File
@@ -39,6 +39,8 @@ export default function AccountSection({ account, onMessage }: { account: Accoun
try { try {
const r = await account.logout(force) const r = await account.logout(force)
if (r === 'pending') setConfirmLogout(true) if (r === 'pending') setConfirmLogout(true)
} catch (err) {
onMessage('error', (err as Error).message)
} finally { } finally {
setBusy(null) setBusy(null)
} }
+10 -1
View File
@@ -1,7 +1,7 @@
import { t } from '../i18n' import { t } from '../i18n'
import { LanguageSelect } from '../i18n/react' import { LanguageSelect } from '../i18n/react'
import { Eye, EyeOff, Loader2 } from 'lucide-react' import { Eye, EyeOff, Loader2 } from 'lucide-react'
import { useState, type FormEvent, type ReactNode } from 'react' import { useEffect, useState, type FormEvent, type ReactNode } from 'react'
import { PASSWORD_MIN, requestPasswordReset, signIn, signInWithGoogle, signUp, updatePassword } from '../lib/cloud/auth' import { PASSWORD_MIN, requestPasswordReset, signIn, signInWithGoogle, signUp, updatePassword } from '../lib/cloud/auth'
import { USERNAME_RE } from '../lib/cloud/social' import { USERNAME_RE } from '../lib/cloud/social'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
@@ -61,6 +61,15 @@ export default function AuthScreen({ notice, onExplore, initialMode = 'login' }:
const cleanUsername = username.trim().replace(/^@/, '').toLowerCase() const cleanUsername = username.trim().replace(/^@/, '').toLowerCase()
const usernameOk = USERNAME_RE.test(cleanUsername) && !RANDOM_USERNAME.test(cleanUsername) const usernameOk = USERNAME_RE.test(cleanUsername) && !RANDOM_USERNAME.test(cleanUsername)
// Retour arrière depuis Google (page restaurée du cache) : les boutons ne restent pas bloqués
useEffect(() => {
const onShow = (e: PageTransitionEvent) => {
if (e.persisted) setBusy(false)
}
window.addEventListener('pageshow', onShow)
return () => window.removeEventListener('pageshow', onShow)
}, [])
const switchTo = (m: Mode) => { const switchTo = (m: Mode) => {
setMode(m) setMode(m)
setError(undefined) setError(undefined)
+45 -8
View File
@@ -3,7 +3,7 @@ import { Check, ChevronLeft, ChevronRight, Loader2, Plus, RefreshCw, X } from 'l
import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { loadAiring, refreshAiring, saveAiring } from '../lib/airing' import { loadAiring, refreshAiring, saveAiring } from '../lib/airing'
import { findTmdbSeries, getAniListById, getTmdbDetails, releaseToResult, type GlobalRelease, type ReleaseCategory } from '../lib/catalogApi' import { findTmdbSeries, getAniListById, getTmdbDetails, releaseToResult, type GlobalRelease, type ReleaseCategory } from '../lib/catalogApi'
import { findFranchiseItem } from '../lib/franchise' import { franchiseKey } from '../lib/franchise'
import { cachedMonth, isBrowsableMonth, loadMonth, RELEASE_CATEGORIES } from '../lib/globalReleases' import { cachedMonth, isBrowsableMonth, loadMonth, RELEASE_CATEGORIES } from '../lib/globalReleases'
import { remotePosterToLocal } from '../lib/image' import { remotePosterToLocal } from '../lib/image'
import { calendarEvents, loadReleases, refreshReleases } from '../lib/releases' import { calendarEvents, loadReleases, refreshReleases } from '../lib/releases'
@@ -13,6 +13,7 @@ import { useEscape } from '../lib/escape'
import { useScrollLock } from '../lib/scrollLock' import { useScrollLock } from '../lib/scrollLock'
import { cx, normalizeText, todayISO } from '../lib/utils' import { cx, normalizeText, todayISO } from '../lib/utils'
import { useMedia } from '../store' import { useMedia } from '../store'
import { TYPE_BY_VALUE } from '../lib/constants'
import type { MediaInput, MediaItem, MediaType } from '../types' import type { MediaInput, MediaItem, MediaType } from '../types'
import { TypeBadge } from './Badges' import { TypeBadge } from './Badges'
import Poster from './Poster' import Poster from './Poster'
@@ -21,6 +22,11 @@ import Poster from './Poster'
const weekdays = () => Array.from({ length: 7 }, (_, k) => new Date(2024, 0, 1 + k).toLocaleDateString(locale(), { weekday: 'narrow' })) const weekdays = () => Array.from({ length: 7 }, (_, k) => new Date(2024, 0, 1 + k).toLocaleDateString(locale(), { weekday: 'narrow' }))
const PER_DAY = 20 const PER_DAY = 20
const PREFS_KEY = 'azuucine:calendar-prefs' const PREFS_KEY = 'azuucine:calendar-prefs'
/** Jour local décalé de n jours (sans « + n × 24 h », faux aux changements d'heure). */
const plusDays = (n: number) => {
const d = new Date()
return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n)
}
const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
const monthId = (d: Date) => iso(d).slice(0, 7) const monthId = (d: Date) => iso(d).slice(0, 7)
const niceDate = (d: string) => new Date(d + 'T12:00:00').toLocaleDateString(locale(), { weekday: 'long', day: 'numeric', month: 'long' }) const niceDate = (d: string) => new Date(d + 'T12:00:00').toLocaleDateString(locale(), { weekday: 'long', day: 'numeric', month: 'long' })
@@ -132,8 +138,9 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
const [airing, rel] = await Promise.all([refreshAiring(items, loadAiring(), settings.tmdbKey, force), refreshReleases(items, settings.tmdbKey, force)]) const [airing, rel] = await Promise.all([refreshAiring(items, loadAiring(), settings.tmdbKey, force), refreshReleases(items, settings.tmdbKey, force)])
saveAiring(airing) saveAiring(airing)
setReleases(rel) setReleases(rel)
// Comme à l'accueil : aussi les fiches « Terminé » dont la série continue (statut inchangé)
const patches = items const patches = items
.filter((i) => i.status !== 'termine' && airing[i.id] && airing[i.id].aired > (i.episodesTotal ?? 0)) .filter((i) => airing[i.id] && (i.status !== 'termine' || !airing[i.id].ended) && airing[i.id].aired > (i.episodesTotal ?? 0))
.map((i) => ({ id: i.id, patch: { episodesTotal: airing[i.id].aired } })) .map((i) => ({ id: i.id, patch: { episodesTotal: airing[i.id].aired } }))
if (patches.length) await patchMany(patches) if (patches.length) await patchMany(patches)
} finally { } finally {
@@ -194,6 +201,32 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
for (const i of items) for (const t of [i.title, i.originalTitle]) if (t) m.set(normalizeText(t), i) for (const i of items) for (const t of [i.title, i.originalTitle]) if (t) m.set(normalizeText(t), i)
return m return m
}, [items]) }, [items])
// Même série, autre saison (comme findFranchiseItem) : index calculé une fois par bibliothèque,
// au lieu de parcourir toute la bibliothèque pour chaque sortie
const byFranchise = useMemo(() => {
const m = new Map<string, { item: MediaItem; index: number }>()
items.forEach((item, index) => {
if (!TYPE_BY_VALUE[item.type]?.episodic) return
for (const x of [item.title, item.originalTitle]) {
const k = x && franchiseKey(x)
if (k && k.length >= 2 && !m.has(k)) m.set(k, { item, index })
}
})
return m
}, [items])
const franchiseItem = useCallback(
(titles: (string | undefined)[], type: MediaType) => {
if (!TYPE_BY_VALUE[type]?.episodic) return undefined
let best: { item: MediaItem; index: number } | undefined
for (const x of titles) {
const k = x && franchiseKey(x)
const hit = k && k.length >= 2 ? byFranchise.get(k) : undefined
if (hit && (!best || hit.index < best.index)) best = hit
}
return best?.item
},
[byFranchise],
)
const entries = useMemo(() => { const entries = useMemo(() => {
const map = new Map<string, Entry>() const map = new Map<string, Entry>()
@@ -208,7 +241,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
byTitle.get(normalizeText(r.title)) ?? byTitle.get(normalizeText(r.title)) ??
(r.originalTitle ? byTitle.get(normalizeText(r.originalTitle)) : undefined) ?? (r.originalTitle ? byTitle.get(normalizeText(r.originalTitle)) : undefined) ??
// « Black Clover Season 2 » sur AniList = ma fiche « Black Clover » // « Black Clover Season 2 » sur AniList = ma fiche « Black Clover »
(r.cat !== 'film' ? findFranchiseItem(items, [r.title, r.originalTitle], { type: r.cat }) : undefined) (r.cat !== 'film' ? franchiseItem([r.title, r.originalTitle], r.cat) : undefined)
map.set(key, { map.set(key, {
key, key,
date: r.date, date: r.date,
@@ -226,11 +259,15 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
.filter((e) => (prefs.mode === 'mine' ? !!e.item : true)) .filter((e) => (prefs.mode === 'mine' ? !!e.item : true))
.filter((e) => e.type === 'autre' || cats.has(e.type)) .filter((e) => e.type === 'autre' || cats.has(e.type))
.sort((a, b) => a.date.localeCompare(b.date) || b.pop - a.pop || a.title.localeCompare(b.title, locale())) .sort((a, b) => a.date.localeCompare(b.date) || b.pop - a.pop || a.title.localeCompare(b.title, locale()))
}, [items, releases, global, byExt, byTitle, prefs]) }, [items, releases, global, byExt, byTitle, franchiseItem, prefs])
const byDay = useMemo(() => { const byDay = useMemo(() => {
const m = new Map<string, Entry[]>() const m = new Map<string, Entry[]>()
for (const e of entries) m.set(e.date, [...(m.get(e.date) ?? []), e]) for (const e of entries) {
const list = m.get(e.date)
if (list) list.push(e)
else m.set(e.date, [e])
}
return m return m
}, [entries]) }, [entries])
@@ -248,9 +285,9 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
const mid = monthId(month) const mid = monthId(month)
const isCurrent = mid === today.slice(0, 7) const isCurrent = mid === today.slice(0, 7)
// Mois en cours : les 14 prochains jours (même s'ils débordent sur le mois suivant) ; sinon tout le mois // Mois en cours : les 14 prochains jours (même s'ils débordent sur le mois suivant) ; sinon tout le mois
const lastDay = isCurrent ? iso(new Date(Date.now() + 13 * 86400000)) : `${mid}-31` const lastDay = isCurrent ? iso(plusDays(13)) : `${mid}-31`
const days = [...byDay.keys()].filter((d) => (isCurrent ? d >= today : d.startsWith(mid)) && d <= lastDay).sort() const days = [...byDay.keys()].filter((d) => (isCurrent ? d >= today : d.startsWith(mid)) && d <= lastDay).sort()
const tomorrow = iso(new Date(Date.now() + 86400000)) const tomorrow = iso(plusDays(1))
const dayTitle = (d: string) => (d === today ? t('time.today') : d === tomorrow ? t('time.tomorrow') : niceDate(d)) const dayTitle = (d: string) => (d === today ? t('time.today') : d === tomorrow ? t('time.tomorrow') : niceDate(d))
const changeMonth = (delta: number) => { const changeMonth = (delta: number) => {
@@ -318,7 +355,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
</div> </div>
{list.length > shown.length && ( {list.length > shown.length && (
<button onClick={() => setExpanded((s) => new Set(s).add(day))} className="mt-1 w-full py-2 text-xs font-medium text-ink-3"> <button onClick={() => setExpanded((s) => new Set(s).add(day))} className="mt-1 w-full py-2 text-xs font-medium text-ink-3">
{t('calendar.seeMore', { count: list.length - shown.length })} <span className="text-accent">→</span> {t('calendar.seeMore', { count: list.length - shown.length })} <span className="inline-block text-accent rtl:-scale-x-100">→</span>
</button> </button>
)} )}
</> </>
+7 -5
View File
@@ -1,3 +1,4 @@
import { useId } from 'react'
import { t } from '../i18n' import { t } from '../i18n'
import { useBackToClose } from '../lib/backNav' import { useBackToClose } from '../lib/backNav'
import { useEscape } from '../lib/escape' import { useEscape } from '../lib/escape'
@@ -15,26 +16,27 @@ interface Props {
export default function ConfirmDialog({ open, title, message, confirmLabel = t('common.confirm'), onConfirm, onCancel }: Props) { export default function ConfirmDialog({ open, title, message, confirmLabel = t('common.confirm'), onConfirm, onCancel }: Props) {
useEscape(onCancel, open) useEscape(onCancel, open)
useBackToClose(onCancel, open) useBackToClose(onCancel, open)
const titleId = useId()
if (!open) return null if (!open) return null
return ( return (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 p-4 sm:items-center" onClick={onCancel}> <div className="fixed inset-0 z-[60] flex items-end justify-center bg-scrim p-4 sm:items-center" onClick={onCancel}>
<div <div
role="alertdialog" role="alertdialog"
aria-modal="true" aria-modal="true"
aria-labelledby="confirm-title" aria-labelledby={titleId}
className="sheet-in safe-bottom w-full max-w-sm rounded-3xl border border-line-strong bg-surface p-5" className="sheet-in safe-bottom w-full max-w-sm rounded-3xl border border-line-strong bg-surface p-5"
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
> >
<h2 id="confirm-title" className="text-lg"> <h2 id={titleId} className="text-lg">
{title} {title}
</h2> </h2>
{message && <p className="mt-2 text-sm leading-relaxed text-ink-2">{message}</p>} {message && <p className="mt-2 text-sm leading-relaxed text-ink-2">{message}</p>}
<div className="mt-5 grid grid-cols-2 gap-2"> <div className="mt-5 grid grid-cols-2 gap-2">
<button onClick={onCancel} className="btn btn-ghost"> <button onClick={onCancel} className="btn btn-ghost" autoFocus>
{t('common.cancel')} {t('common.cancel')}
</button> </button>
<button onClick={onConfirm} className="btn btn-primary" autoFocus> <button onClick={onConfirm} className="btn btn-primary">
{confirmLabel} {confirmLabel}
</button> </button>
</div> </div>
+4 -1
View File
@@ -41,7 +41,10 @@ export default function EpisodeList({ form, aired, onChange }: Props) {
// Taille de la saison affichée (ou de toute la série si on ne connaît pas le découpage) // Taille de la saison affichée (ou de toute la série si on ne connaît pas le découpage)
const before = seasons ? episodesBeforeSeason(seasons, viewSeason) : 0 const before = seasons ? episodesBeforeSeason(seasons, viewSeason) : 0
const size = seasons ? (seasons[viewSeason - 1] ?? 0) : Math.min(episodeCap(form) ?? 0, MAX_GENERIC) // Total enregistré plus grand que la somme des saisons : le surplus va à la dernière saison
// (sinon les derniers épisodes ne pouvaient jamais être cochés)
const extra = seasons && viewSeason === seasons.length ? Math.max(0, (episodeCap(form) ?? 0) - episodesBeforeSeason(seasons, seasons.length + 1)) : 0
const size = seasons ? Math.min((seasons[viewSeason - 1] ?? 0) + extra, MAX_GENERIC) : Math.min(episodeCap(form) ?? 0, MAX_GENERIC)
useEffect(() => { useEffect(() => {
if (!isTmdb || !navigator.onLine) return setEpisodes(undefined) if (!isTmdb || !navigator.onLine) return setEpisodes(undefined)
+5 -1
View File
@@ -43,7 +43,11 @@ export default function JournalView({ onOpen }: { onOpen: (item: MediaItem) => v
const months = useMemo(() => { const months = useMemo(() => {
const list = year ? entries.filter((e) => e.date.startsWith(year)) : entries const list = year ? entries.filter((e) => e.date.startsWith(year)) : entries
const map = new Map<string, Entry[]>() const map = new Map<string, Entry[]>()
for (const e of list) map.set(e.date.slice(0, 7), [...(map.get(e.date.slice(0, 7)) ?? []), e]) for (const e of list) {
const month = map.get(e.date.slice(0, 7))
if (month) month.push(e)
else map.set(e.date.slice(0, 7), [e])
}
return [...map.entries()] return [...map.entries()]
}, [entries, year]) }, [entries, year])
+1 -1
View File
@@ -81,7 +81,7 @@ function ListDetail({ list, onBack, onOpen }: { list: CustomList; onBack: () =>
return ( return (
<> <>
<button onClick={onBack} className="mt-2 flex items-center gap-1.5 text-sm text-ink-3"> <button onClick={onBack} className="mt-2 flex items-center gap-1.5 text-sm text-ink-3">
<ArrowLeft size={16} /> {t('lists.myLists')} <ArrowLeft size={16} className="rtl:rotate-180" /> {t('lists.myLists')}
</button> </button>
<div className="mb-5 mt-3 flex items-start justify-between gap-3"> <div className="mb-5 mt-3 flex items-start justify-between gap-3">
+8 -3
View File
@@ -1,5 +1,6 @@
import { t } from '../i18n' import { t } from '../i18n'
import { Heart, Plus } from 'lucide-react' import { Heart, Plus } from 'lucide-react'
import { memo } from 'react'
import { TYPE_BY_VALUE } from '../lib/constants' import { TYPE_BY_VALUE } from '../lib/constants'
import { canWatchMore } from '../lib/airing' import { canWatchMore } from '../lib/airing'
import { episodeCap, seasonPosition } from '../lib/franchise' import { episodeCap, seasonPosition } from '../lib/franchise'
@@ -36,8 +37,12 @@ function Progress({ item }: { item: MediaItem }) {
) )
} }
/** Carte verticale (grille du catalogue). */ /**
export function MediaCard({ item, onOpen }: { item: MediaItem; onOpen: (item: MediaItem) => void }) { * Carte verticale (grille du catalogue).
* Mémorisée : taper dans la recherche ou cocher une fiche ne redessine plus toute la grille
* (elle se redessine quand même si la bibliothèque ou les réglages changent, via useMedia).
*/
export const MediaCard = memo(function MediaCard({ item, onOpen }: { item: MediaItem; onOpen: (item: MediaItem) => void }) {
const { settings, incrementEpisode } = useMedia() const { settings, incrementEpisode } = useMedia()
// Revisionnage en cours : la progression montrée est celle du revisionnage // Revisionnage en cours : la progression montrée est celle du revisionnage
const view = progressView(item) const view = progressView(item)
@@ -76,4 +81,4 @@ export function MediaCard({ item, onOpen }: { item: MediaItem; onOpen: (item: Me
</button> </button>
</article> </article>
) )
} })
+4 -1
View File
@@ -62,7 +62,10 @@ export function RatingInput({ value, onChange, scale, size = 'lg', label }: Inpu
const pick = (e: MouseEvent<HTMLButtonElement>, index: number) => { const pick = (e: MouseEvent<HTMLButtonElement>, index: number) => {
const rect = e.currentTarget.getBoundingClientRect() const rect = e.currentTarget.getBoundingClientRect()
// Clavier (Entrée / Espace) : pas de position de clic, on donne l'étoile entière // Clavier (Entrée / Espace) : pas de position de clic, on donne l'étoile entière
const half = e.detail !== 0 && e.clientX - rect.left < rect.width / 2 // En arabe (RTL), l'étoile se remplit depuis la droite : la demi-étoile est la moitié droite
const rtl = getComputedStyle(e.currentTarget).direction === 'rtl'
const fromStart = rtl ? rect.right - e.clientX : e.clientX - rect.left
const half = e.detail !== 0 && fromStart < rect.width / 2
const next = (index + (half ? 0.5 : 1)) * 2 const next = (index + (half ? 0.5 : 1)) * 2
onChange(next === value ? undefined : next) // retoucher la même valeur efface la note onChange(next === value ? undefined : next) // retoucher la même valeur efface la note
} }
+6 -1
View File
@@ -4,9 +4,10 @@ import { useEffect, useMemo, useState } from 'react'
import { aniListRecommendations, getTmdbDetails, searchAniList, tmdbRecommendations, type SearchResult } from '../lib/catalogApi' import { aniListRecommendations, getTmdbDetails, searchAniList, tmdbRecommendations, type SearchResult } from '../lib/catalogApi'
import { remotePosterToLocal } from '../lib/image' import { remotePosterToLocal } from '../lib/image'
import { normalizeText } from '../lib/utils' import { normalizeText } from '../lib/utils'
import { useMedia } from '../store' import { GuestError, useMedia } from '../store'
import type { MediaInput, MediaItem } from '../types' import type { MediaInput, MediaItem } from '../types'
import Poster from './Poster' import Poster from './Poster'
import { useToast } from './Toast'
import { LinkArrow, SectionTitle } from './ui' import { LinkArrow, SectionTitle } from './ui'
// Cache en mémoire le temps de la session (évite de refaire les requêtes) // Cache en mémoire le temps de la session (évite de refaire les requêtes)
@@ -33,6 +34,7 @@ async function recommendationsFor(seed: MediaItem, tmdbKey?: string): Promise<Se
/** « Si tu as aimé X » : suggestions à partir de mes titres préférés, ajoutables en un clic. */ /** « Si tu as aimé X » : suggestions à partir de mes titres préférés, ajoutables en un clic. */
export default function Recommendations() { export default function Recommendations() {
const { items, settings, add } = useMedia() const { items, settings, add } = useMedia()
const toast = useToast()
const hasKey = !!settings.tmdbKey?.trim() const hasKey = !!settings.tmdbKey?.trim()
// Titres « graines » : mes préférés, dans un ordre aléatoire fixé pour la session // Titres « graines » : mes préférés, dans un ordre aléatoire fixé pour la session
@@ -104,6 +106,9 @@ export default function Recommendations() {
} }
await add(input) await add(input)
setAdded((s) => new Set(s).add(r.externalId)) setAdded((s) => new Set(s).add(r.externalId))
} catch (e) {
// Hors ligne, TMDB injoignable, stockage plein… : on le dit (mode visiteur : déjà signalé ailleurs)
if (!(e instanceof GuestError)) toast.show((e as Error)?.message || t('reco.error'))
} finally { } finally {
setBusy(undefined) setBusy(undefined)
} }
+2
View File
@@ -4,6 +4,7 @@ import { useEffect, useMemo, useState } from 'react'
import { shareImage } from '../lib/shareCard' import { shareImage } from '../lib/shareCard'
import { useBackToClose } from '../lib/backNav' import { useBackToClose } from '../lib/backNav'
import { useEscape } from '../lib/escape' import { useEscape } from '../lib/escape'
import { useScrollLock } from '../lib/scrollLock'
interface Props { interface Props {
blob: Blob blob: Blob
@@ -30,6 +31,7 @@ export default function SharePreview({ blob, filename, title, onClose }: Props)
setUrl(u) setUrl(u)
return () => URL.revokeObjectURL(u) return () => URL.revokeObjectURL(u)
}, [blob]) }, [blob])
useScrollLock()
useEscape(onClose) useEscape(onClose)
useBackToClose(onClose) useBackToClose(onClose)
+6 -7
View File
@@ -9,13 +9,10 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, use
export interface ToastOptions { export interface ToastOptions {
/** Bouton « Annuler » : remet les choses comme avant. */ /** Bouton « Annuler » : remet les choses comme avant. */
undo?: () => void | Promise<void> undo?: () => void | Promise<void>
/** Durée d'affichage en ms (6 s avec « Annuler », 3 s sinon). */
duration?: number
} }
interface ToastApi { interface ToastApi {
show: (message: string, opts?: ToastOptions) => void show: (message: string, opts?: ToastOptions) => void
dismiss: () => void
} }
interface ToastState extends ToastOptions { interface ToastState extends ToastOptions {
@@ -35,7 +32,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
setToast({ id: seq.current, message, ...opts }) setToast({ id: seq.current, message, ...opts })
}, []) }, [])
const api = useMemo(() => ({ show, dismiss }), [show, dismiss]) const api = useMemo(() => ({ show }), [show])
return ( return (
<ToastContext.Provider value={api}> <ToastContext.Provider value={api}>
@@ -49,7 +46,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
export function useToast(): ToastApi { export function useToast(): ToastApi {
return useContext(ToastContext) ?? NOOP return useContext(ToastContext) ?? NOOP
} }
const NOOP: ToastApi = { show: () => {}, dismiss: () => {} } const NOOP: ToastApi = { show: () => {} }
function ToastViewport({ toast, onDismiss, onShow }: { toast: ToastState | null; onDismiss: () => void; onShow: ToastApi['show'] }) { function ToastViewport({ toast, onDismiss, onShow }: { toast: ToastState | null; onDismiss: () => void; onShow: ToastApi['show'] }) {
const [paused, setPaused] = useState(false) const [paused, setPaused] = useState(false)
@@ -57,10 +54,12 @@ function ToastViewport({ toast, onDismiss, onShow }: { toast: ToastState | null;
const remaining = useRef(0) const remaining = useRef(0)
const startedAt = useRef(0) const startedAt = useRef(0)
// Nouveau message : compte à rebours complet // Nouveau message : compte à rebours complet. La pause est remise à zéro : un message fermé
// sous le doigt / la souris ne reçoit jamais « pointerleave », et les suivants ne partaient plus.
useEffect(() => { useEffect(() => {
setPaused(false)
if (!toast) return if (!toast) return
remaining.current = toast.duration ?? (toast.undo ? 6000 : 3000) remaining.current = toast.undo ? 6000 : 3000
setUndoing(false) setUndoing(false)
}, [toast]) }, [toast])
+12 -4
View File
@@ -3,7 +3,8 @@ import { ChevronDown, ChevronUp, Search, X } from 'lucide-react'
import { useMemo, useState } from 'react' import { useMemo, useState } from 'react'
import { TOP_CATEGORIES } from '../lib/constants' import { TOP_CATEGORIES } from '../lib/constants'
import { cx, formatRating, normalizeText } from '../lib/utils' import { cx, formatRating, normalizeText } from '../lib/utils'
import { useMedia } from '../store' import { GuestError, useMedia } from '../store'
import { useToast } from './Toast'
import type { TopCategory } from '../types' import type { TopCategory } from '../types'
import { TypeBadge } from './Badges' import { TypeBadge } from './Badges'
import Poster from './Poster' import Poster from './Poster'
@@ -29,6 +30,7 @@ export default function TopFiveEditor({ category: initialCategory, onClose }: Pr
const [query, setQuery] = useState('') const [query, setQuery] = useState('')
const [allTypes, setAllTypes] = useState(false) const [allTypes, setAllTypes] = useState(false)
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const toast = useToast()
const catInfo = TOP_CATEGORIES.find((c) => c.value === category)! const catInfo = TOP_CATEGORIES.find((c) => c.value === category)!
const byId = useMemo(() => new Map(items.map((i) => [i.id, i])), [items]) const byId = useMemo(() => new Map(items.map((i) => [i.id, i])), [items])
@@ -66,9 +68,15 @@ export default function TopFiveEditor({ category: initialCategory, onClose }: Pr
const save = async () => { const save = async () => {
setSaving(true) setSaving(true)
await setTopList(category, ids) // Échec (hors-ligne, mode découverte…) : le bouton ne reste pas bloqué et la fenêtre reste ouverte
setSaving(false) try {
onClose() await setTopList(category, ids)
onClose()
} catch (e) {
if (!(e instanceof GuestError)) toast.show((e as Error).message)
} finally {
setSaving(false)
}
} }
return ( return (
+4 -1
View File
@@ -1,6 +1,6 @@
import { t } from '../../i18n' import { t } from '../../i18n'
import { Check } from 'lucide-react' import { Check } from 'lucide-react'
import { useRef, type ReactNode } from 'react' import { useEffect, useRef, type ReactNode } from 'react'
import { cx } from '../../lib/utils' import { cx } from '../../lib/utils'
interface Props { interface Props {
@@ -32,6 +32,9 @@ export default function SelectableCard({ title, selecting, selected, onToggle, o
origin.current = undefined origin.current = undefined
} }
// Carte retirée pendant l'appui (filtre, suppression…) : le minuteur ne doit plus se déclencher
useEffect(() => () => clearTimeout(timer.current), [])
return ( return (
<div <div
className="group relative select-none [-webkit-touch-callout:none]" className="group relative select-none [-webkit-touch-callout:none]"
+15 -4
View File
@@ -5,12 +5,14 @@ import { useBackToClose } from '../../lib/backNav'
import { allTags, cleanTag, hasTag } from '../../lib/bulk' import { allTags, cleanTag, hasTag } from '../../lib/bulk'
import { STATUSES } from '../../lib/constants' import { STATUSES } from '../../lib/constants'
import { useEscape } from '../../lib/escape' import { useEscape } from '../../lib/escape'
import { useScrollLock } from '../../lib/scrollLock'
import { cx, normalizeText } from '../../lib/utils' import { cx, normalizeText } from '../../lib/utils'
import { useMedia } from '../../store' import { GuestError, useMedia } from '../../store'
import type { MediaItem, WatchStatus } from '../../types' import type { MediaItem, WatchStatus } from '../../types'
import { StatusDot } from '../Badges' import { StatusDot } from '../Badges'
import ConfirmDialog from '../ConfirmDialog' import ConfirmDialog from '../ConfirmDialog'
import { NewListForm } from '../ListsView' import { NewListForm } from '../ListsView'
import { useToast } from '../Toast'
import { useLibraryActions } from './useLibraryActions' import { useLibraryActions } from './useLibraryActions'
type Panel = null | 'status' | 'list' | 'tag' | 'delete' type Panel = null | 'status' | 'list' | 'tag' | 'delete'
@@ -29,10 +31,18 @@ export default function SelectionBar({ selected, onDone }: Props) {
const ids = selected.map((i) => i.id) const ids = selected.map((i) => i.id)
const none = selected.length === 0 const none = selected.length === 0
const toast = useToast()
const run = async (fn: () => Promise<void>) => { const run = async (fn: () => Promise<void>) => {
setPanel(null) setPanel(null)
await fn() // Même en cas d'échec, la sélection se ferme (sinon la barre restait bloquée)
onDone() try {
await fn()
} catch (e) {
// Mode découverte : la demande de compte est déjà ouverte
if (!(e instanceof GuestError)) toast.show((e as Error).message)
} finally {
onDone()
}
} }
return ( return (
@@ -95,10 +105,11 @@ function BarButton({ icon, label, onClick, disabled, danger }: { icon: ReactNode
/** Petite feuille en bas de l'écran ; Échap ou le geste retour la ferment sans quitter la sélection. */ /** Petite feuille en bas de l'écran ; Échap ou le geste retour la ferment sans quitter la sélection. */
function PickerSheet({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) { function PickerSheet({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
useScrollLock()
useEscape(onClose) useEscape(onClose)
useBackToClose(onClose) useBackToClose(onClose)
return ( return (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 sm:items-center" onClick={onClose}> <div className="fixed inset-0 z-[60] flex items-end justify-center bg-scrim sm:items-center" onClick={onClose}>
<div <div
role="dialog" role="dialog"
aria-modal="true" aria-modal="true"
+1 -1
View File
@@ -85,7 +85,7 @@ export default function BugReportDialog({ onClose }: { onClose: () => void }) {
} }
return ( return (
<div className="fixed inset-0 z-[80] flex touch-none items-end justify-center overscroll-none bg-black/70 sm:items-center sm:p-4" onClick={onClose}> <div className="fixed inset-0 z-[80] flex touch-none items-end justify-center overscroll-none bg-scrim sm:items-center sm:p-4" onClick={onClose}>
<div <div
role="dialog" role="dialog"
aria-modal="true" aria-modal="true"
+2 -7
View File
@@ -12,7 +12,6 @@ export interface MenuAction {
icon: ReactNode icon: ReactNode
label: string label: string
onClick: () => void onClick: () => void
danger?: boolean
} }
/** /**
@@ -24,14 +23,11 @@ export default function ReportButton({
actions = [], actions = [],
className, className,
size = 18, size = 18,
label,
}: { }: {
target: ReportTarget target: ReportTarget
actions?: MenuAction[] actions?: MenuAction[]
className?: string className?: string
size?: number size?: number
/** Nom accessible du bouton (par défaut « Plus d'options ») */
label?: string
}) { }) {
const [menu, setMenu] = useState(false) const [menu, setMenu] = useState(false)
const [report, setReport] = useState(false) const [report, setReport] = useState(false)
@@ -43,7 +39,7 @@ export default function ReportButton({
e.stopPropagation() e.stopPropagation()
setMenu(true) setMenu(true)
}} }}
aria-label={label ?? t('report.more')} aria-label={t('report.more')}
aria-haspopup="menu" aria-haspopup="menu"
className={cx('grid size-9 shrink-0 place-items-center rounded-full text-ink-3 transition-colors hover:text-ink active:bg-surface-2', className)} className={cx('grid size-9 shrink-0 place-items-center rounded-full text-ink-3 transition-colors hover:text-ink active:bg-surface-2', className)}
> >
@@ -57,7 +53,6 @@ export default function ReportButton({
<MenuItem <MenuItem
key={a.label} key={a.label}
icon={a.icon} icon={a.icon}
danger={a.danger}
onClick={() => { onClick={() => {
setMenu(false) setMenu(false)
a.onClick() a.onClick()
@@ -89,7 +84,7 @@ function ActionMenu({ onClose, children }: { onClose: () => void; children: Reac
useEscape(onClose) useEscape(onClose)
useBackToClose(onClose) useBackToClose(onClose)
return ( return (
<div className="fixed inset-0 z-[80] flex items-end justify-center bg-black/70 sm:items-center" onClick={onClose}> <div className="fixed inset-0 z-[80] flex items-end justify-center bg-scrim sm:items-center" onClick={onClose}>
<div role="menu" className="sheet-in safe-bottom w-full max-w-md rounded-t-3xl border border-line-strong bg-surface p-3 sm:rounded-3xl" onClick={(e) => e.stopPropagation()}> <div role="menu" className="sheet-in safe-bottom w-full max-w-md rounded-t-3xl border border-line-strong bg-surface p-3 sm:rounded-3xl" onClick={(e) => e.stopPropagation()}>
{children} {children}
<button type="button" onClick={onClose} className="mt-1 w-full rounded-xl px-3 py-3 text-center text-sm text-ink-3 active:bg-surface-2"> <button type="button" onClick={onClose} className="mt-1 w-full rounded-xl px-3 py-3 text-center text-sm text-ink-3 active:bg-surface-2">
+1 -1
View File
@@ -54,7 +54,7 @@ export default function ReportDialog({ target, onClose }: { target: ReportTarget
} }
return ( return (
<div className="fixed inset-0 z-[80] flex touch-none items-end justify-center overscroll-none bg-black/70 sm:items-center sm:p-4" onClick={onClose}> <div className="fixed inset-0 z-[80] flex touch-none items-end justify-center overscroll-none bg-scrim sm:items-center sm:p-4" onClick={onClose}>
<div <div
role="dialog" role="dialog"
aria-modal="true" aria-modal="true"
-26
View File
@@ -1,26 +0,0 @@
import { t } from '../../i18n'
import { useMedia } from '../../store'
import ReviewComments from './ReviewComments'
import ReviewText from './ReviewText'
import Sheet from './Sheet'
/** Commentaires sous un de mes avis, en plein écran (ouvert depuis une notification). */
export default function CommentsSheet({ authorId, itemId, title, onClose }: { authorId: string; itemId: string; title: string; onClose: () => void }) {
const { items } = useMedia()
// Mon avis tel qu'il est sur cet appareil (les commentaires viennent du serveur)
const mine = items.find((i) => i.id === itemId)
return (
<Sheet title={title || t('comments.title')} label={t('comments.title')} onClose={onClose} elevated>
<div className="px-4 pt-4">
{mine?.notes && (
<article className="card mb-4 p-3.5">
<p className="eyebrow">{t('form.review')}</p>
<ReviewText text={mine.notes} spoiler={mine.notesSpoiler} revealed clamp />
</article>
)}
<p className="eyebrow mb-1">{t('comments.title')}</p>
<ReviewComments authorId={authorId} itemId={itemId} defaultOpen />
</div>
</Sheet>
)
}
+51 -8
View File
@@ -1,8 +1,10 @@
import { Loader2 } from 'lucide-react' import { Loader2 } from 'lucide-react'
import { useEffect, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { t } from '../../i18n' import { t } from '../../i18n'
import { acceptFollower, getFollowList, removeFollower, type Profile, type ProfileCard } from '../../lib/cloud/social' import { acceptFollower, FOLLOW_PAGE, getFollowList, removeFollower, type Profile, type ProfileCard } from '../../lib/cloud/social'
import { cx } from '../../lib/utils' import { cx } from '../../lib/utils'
import { GuestError } from '../../store'
import { useToast } from '../Toast'
import PersonRow from './PersonRow' import PersonRow from './PersonRow'
import Sheet from './Sheet' import Sheet from './Sheet'
import { useSocial } from './SocialProvider' import { useSocial } from './SocialProvider'
@@ -18,19 +20,53 @@ export default function FollowList({ profile, initial, onClose }: { profile: Pro
const tab: Tab = picked === 'requests' && !showRequests ? 'followers' : picked const tab: Tab = picked === 'requests' && !showRequests ? 'followers' : picked
const [list, setList] = useState<ProfileCard[]>() const [list, setList] = useState<ProfileCard[]>()
const [busy, setBusy] = useState<string>() const [busy, setBusy] = useState<string>()
const toast = useToast()
// Le serveur renvoie les comptes par pages : lignes reçues (décalage de la suivante) et page suivante possible
const received = useRef(0)
const [more, setMore] = useState(false)
const [loadingMore, setLoadingMore] = useState(false)
// Numéro du dernier chargement : une page arrivée après un changement d'onglet est ignorée
const request = useRef(0)
useEffect(() => { useEffect(() => {
const id = ++request.current
received.current = 0
setMore(false)
setLoadingMore(false)
if (tab === 'requests') return setList(social.requests) if (tab === 'requests') return setList(social.requests)
let alive = true
setList(undefined) setList(undefined)
getFollowList(profile.id, tab) getFollowList(profile.id, tab)
.then((l) => alive && setList(l)) .then((page) => {
.catch(() => alive && setList([])) if (id !== request.current) return
return () => { received.current = page.received
alive = false setList(page.cards)
} setMore(page.received >= FOLLOW_PAGE)
})
.catch(() => id === request.current && setList([]))
}, [tab, profile.id, social.requests]) }, [tab, profile.id, social.requests])
const loadMore = async () => {
if (tab === 'requests' || loadingMore) return
const id = request.current
setLoadingMore(true)
try {
const page = await getFollowList(profile.id, tab, received.current)
if (id !== request.current) return
received.current += page.received
// Sans doublon (même clé React) si la liste a bougé entre deux pages
setList((l) => {
const base = l ?? []
const seen = new Set(base.map((p) => p.id))
return [...base, ...page.cards.filter((p) => !seen.has(p.id) && !!seen.add(p.id))]
})
setMore(page.received >= FOLLOW_PAGE)
} catch (e) {
if (id === request.current) toast.show((e as Error).message)
} finally {
if (id === request.current) setLoadingMore(false)
}
}
const act = async (person: ProfileCard, action: 'accept' | 'remove') => { const act = async (person: ProfileCard, action: 'accept' | 'remove') => {
setBusy(person.id) setBusy(person.id)
try { try {
@@ -38,6 +74,8 @@ export default function FollowList({ profile, initial, onClose }: { profile: Pro
else await removeFollower(person.id) else await removeFollower(person.id)
setList((l) => l?.filter((p) => p.id !== person.id)) setList((l) => l?.filter((p) => p.id !== person.id))
await social.refresh() await social.refresh()
} catch (e) {
if (!(e instanceof GuestError)) toast.show((e as Error).message)
} finally { } finally {
setBusy(undefined) setBusy(undefined)
} }
@@ -92,6 +130,11 @@ export default function FollowList({ profile, initial, onClose }: { profile: Pro
))} ))}
</div> </div>
)} )}
{list !== undefined && list.length > 0 && more && tab !== 'requests' && (
<button onClick={() => void loadMore()} disabled={loadingMore} className="btn btn-ghost mt-3 w-full">
{loadingMore ? <Loader2 size={16} className="animate-spin" /> : t('social.loadMore')}
</button>
)}
</div> </div>
</Sheet> </Sheet>
) )
+60 -13
View File
@@ -1,7 +1,7 @@
import { Loader2, Star, UserPlus } from 'lucide-react' import { Loader2, Star, UserPlus } from 'lucide-react'
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { t } from '../../i18n' import { t } from '../../i18n'
import { getFeed, type FeedEntry } from '../../lib/cloud/social' import { FEED_PAGE, getFeed, type FeedEntry } from '../../lib/cloud/social'
import { useOnResume } from '../../lib/onResume' import { useOnResume } from '../../lib/onResume'
import { timeAgo } from '../../lib/timeAgo' import { timeAgo } from '../../lib/timeAgo'
import { formatRating } from '../../lib/utils' import { formatRating } from '../../lib/utils'
@@ -11,6 +11,20 @@ import { LinkArrow, SectionTitle } from '../ui'
import Avatar from './Avatar' import Avatar from './Avatar'
import { useSocial } from './SocialProvider' import { useSocial } from './SocialProvider'
const feedKey = (e: FeedEntry) => `${e.id}-${e.createdAt}`
/** Ajoute une page sans doublon (même entrée reçue deux fois = même clé React). */
function append(list: FeedEntry[], page: FeedEntry[]): FeedEntry[] {
const seen = new Set(list.map(feedKey))
const out = [...list]
for (const e of page) {
if (seen.has(feedKey(e))) continue
seen.add(feedKey(e))
out.push(e)
}
return out
}
const VERB = { finished: 'feed.finished', started: 'feed.started', rewatched: 'feed.rewatched', added: 'feed.added' } as const const VERB = { finished: 'feed.finished', started: 'feed.started', rewatched: 'feed.rewatched', added: 'feed.added' } as const
/** Accueil : ce que regardent mes abonnements. */ /** Accueil : ce que regardent mes abonnements. */
@@ -21,20 +35,46 @@ export default function FriendsFeed() {
const [more, setMore] = useState(false) const [more, setMore] = useState(false)
const [loadingMore, setLoadingMore] = useState(false) const [loadingMore, setLoadingMore] = useState(false)
const [shown, setShown] = useState(6) const [shown, setShown] = useState(6)
// Hors-ligne avant le premier chargement : message au lieu d'un chargement sans fin
const [offline, setOffline] = useState(false)
// Date de la dernière ligne reçue : point de départ de la page suivante
const cursor = useRef<string | undefined>(undefined)
// Numéro du dernier chargement : une réponse arrivée après un plus récent est ignorée
const req = useRef(0)
const load = useCallback(async () => { const load = useCallback(async () => {
const id = ++req.current
setLoadingMore(false)
try { try {
const list = await getFeed() const page = await getFeed()
setEntries(list) if (id !== req.current) return
setMore(list.length >= 30) cursor.current = page.cursor
setEntries(append([], page.entries))
setMore(page.received >= FEED_PAGE)
setOffline(false)
} catch { } catch {
if (id !== req.current) return
// Hors-ligne : on garde ce qui est déjà affiché
if (!navigator.onLine) {
setOffline(true)
return
}
setEntries([]) setEntries([])
} }
}, []) }, [])
useEffect(() => { useEffect(() => {
if (social.enabled && navigator.onLine) void load() if (!social.enabled) return
if (navigator.onLine) void load()
else setOffline(true)
}, [social.enabled, load]) }, [social.enabled, load])
// Réseau retrouvé alors que le fil n'a jamais pu être chargé : on le charge
useEffect(() => {
if (!social.enabled || !offline) return
const on = () => void load()
window.addEventListener('online', on)
return () => window.removeEventListener('online', on)
}, [social.enabled, offline, load])
// Retour sur l'app : on récupère ce que les abonnements ont ajouté entre-temps // Retour sur l'app : on récupère ce que les abonnements ont ajouté entre-temps
useOnResume(() => void load(), social.enabled) useOnResume(() => void load(), social.enabled)
// Abonnement / désabonnement : le fil change aussi // Abonnement / désabonnement : le fil change aussi
@@ -46,23 +86,30 @@ export default function FriendsFeed() {
if (!social.enabled) return null if (!social.enabled) return null
const loadMore = async () => { const loadMore = async () => {
if (!entries) return if (!entries || loadingMore) return
if (shown < entries.length) return setShown((n) => n + 10) if (shown < entries.length) return setShown((n) => n + 10)
const id = req.current
setLoadingMore(true) setLoadingMore(true)
try { try {
const next = await getFeed(entries[entries.length - 1]?.createdAt) const page = await getFeed(cursor.current ?? entries[entries.length - 1]?.createdAt)
setEntries([...entries, ...next]) if (id !== req.current) return
setMore(next.length >= 30) cursor.current = page.cursor ?? cursor.current
setEntries((list) => append(list ?? [], page.entries))
setMore(page.received >= FEED_PAGE)
setShown((n) => n + 10) setShown((n) => n + 10)
} catch {
/* hors-ligne / serveur indisponible : le bouton reste là pour réessayer */
} finally { } finally {
setLoadingMore(false) if (id === req.current) setLoadingMore(false)
} }
} }
return ( return (
<> <>
<SectionTitle action={<LinkArrow onClick={social.openSearch}>{t('social.findFriends')}</LinkArrow>}>{t('feed.title')}</SectionTitle> <SectionTitle action={<LinkArrow onClick={social.openSearch}>{t('social.findFriends')}</LinkArrow>}>{t('feed.title')}</SectionTitle>
{entries === undefined ? ( {entries === undefined && offline ? (
<p className="text-sm text-ink-3">{t('common.offline')}</p>
) : entries === undefined ? (
<p className="flex items-center gap-2 text-sm text-ink-3"> <p className="flex items-center gap-2 text-sm text-ink-3">
<Loader2 size={14} className="animate-spin" /> {t('social.loading')} <Loader2 size={14} className="animate-spin" /> {t('social.loading')}
</p> </p>
@@ -77,7 +124,7 @@ export default function FriendsFeed() {
<> <>
<ul className="divide-y divide-line"> <ul className="divide-y divide-line">
{entries.slice(0, shown).map((e) => ( {entries.slice(0, shown).map((e) => (
<li key={`${e.id}-${e.createdAt}`} className="flex items-center gap-3 py-2.5"> <li key={feedKey(e)} className="flex items-center gap-3 py-2.5">
<button onClick={() => social.openProfile(e.user.username)} aria-label={e.user.displayName}> <button onClick={() => social.openProfile(e.user.username)} aria-label={e.user.displayName}>
<Avatar url={e.user.avatarUrl} name={e.user.displayName} size={36} /> <Avatar url={e.user.avatarUrl} name={e.user.displayName} size={36} />
</button> </button>
+7 -2
View File
@@ -7,7 +7,8 @@ import { useScrollLock } from '../../lib/scrollLock'
import { titleReviews, type TitleReview } from '../../lib/cloud/reviews' import { titleReviews, type TitleReview } from '../../lib/cloud/reviews'
import { useSocial } from './SocialProvider' import { useSocial } from './SocialProvider'
import { cx, formatDate, formatRating, normalizeText } from '../../lib/utils' import { cx, formatDate, formatRating, normalizeText } from '../../lib/utils'
import { useMedia } from '../../store' import { GuestError, useMedia } from '../../store'
import { useToast } from '../Toast'
import type { MediaInput, MediaItem } from '../../types' import type { MediaInput, MediaItem } from '../../types'
import { StatusPill, TypeBadge } from '../Badges' import { StatusPill, TypeBadge } from '../Badges'
import Poster from '../Poster' import Poster from '../Poster'
@@ -30,6 +31,7 @@ export default function ItemPeek({ item, owner, onClose }: { item: MediaItem; ow
const social = useSocial() const social = useSocial()
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [added, setAdded] = useState(false) const [added, setAdded] = useState(false)
const toast = useToast()
// Avis d'un autre membre : on récupère les réactions pour pouvoir réagir ici même // Avis d'un autre membre : on récupère les réactions pour pouvoir réagir ici même
const [review, setReview] = useState<TitleReview>() const [review, setReview] = useState<TitleReview>()
const canReact = !!owner && owner.username !== social.me?.username && !!item.notes && !!item.externalId const canReact = !!owner && owner.username !== social.me?.username && !!item.notes && !!item.externalId
@@ -83,13 +85,16 @@ export default function ItemPeek({ item, owner, onClose }: { item: MediaItem; ow
} }
await add(input) await add(input)
setAdded(true) setAdded(true)
} catch (e) {
// Mode découverte : l'invitation à créer un compte est déjà affichée
if (!(e instanceof GuestError)) toast.show((e as Error).message)
} finally { } finally {
setBusy(false) setBusy(false)
} }
} }
return ( return (
<div className="fixed inset-0 z-[60] flex touch-none items-end justify-center overscroll-none bg-black/70 sm:items-center sm:p-4" onClick={onClose}> <div className="fixed inset-0 z-[60] flex touch-none items-end justify-center overscroll-none bg-scrim sm:items-center sm:p-4" onClick={onClose}>
<div <div
role="dialog" role="dialog"
aria-modal="true" aria-modal="true"
+36 -18
View File
@@ -1,7 +1,7 @@
import { Ban, Check, Loader2, Lock, Share2, Star, UserCheck, UserPlus } from 'lucide-react' import { Ban, Check, Loader2, Lock, Share2, Star, UserCheck, UserPlus } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { fmtNumber, t } from '../../i18n' import { fmtNumber, t } from '../../i18n'
import { follow, getProfile, getProfileItems, profileLink, unfollow, type Profile } from '../../lib/cloud/social' import { follow, getProfile, getProfileItems, PROFILE_ITEMS_PAGE, profileLink, unfollow, type Profile } from '../../lib/cloud/social'
import { STATUSES, TOP_CATEGORIES } from '../../lib/constants' import { STATUSES, TOP_CATEGORIES } from '../../lib/constants'
import { cx, formatRating } from '../../lib/utils' import { cx, formatRating } from '../../lib/utils'
import { useMedia } from '../../store' import { useMedia } from '../../store'
@@ -64,15 +64,22 @@ export default function ProfileView({ username, onClose }: { username: string; o
const { isBlocked } = useBlocked(!!profile && !profile.isMe) const { isBlocked } = useBlocked(!!profile && !profile.isMe)
const blocked = !!profile && !profile.isMe && isBlocked(profile.id) const blocked = !!profile && !profile.isMe && isBlocked(profile.id)
const load = useCallback(async () => { /** `reload` : rechargement après une action (s'abonner, bloquer…) — en cas d'échec, on garde le profil affiché. */
setError(undefined) const load = useCallback(
try { async (reload = false) => {
setProfile(await getProfile(username)) if (!reload) setError(undefined)
} catch (e) { try {
setError((e as Error).message) const next = await getProfile(username)
setProfile(null) if (reload) setError(undefined)
} setProfile(next)
}, [username]) } catch (e) {
if (reload) return setToast((e as Error).message)
setError((e as Error).message)
setProfile(null)
}
},
[username],
)
useEffect(() => { useEffect(() => {
void load() void load()
@@ -113,7 +120,7 @@ export default function ProfileView({ username, onClose }: { username: string; o
setBusy(true) setBusy(true)
try { try {
await follow(profile.id) await follow(profile.id)
await load() await load(true)
void social.refresh() void social.refresh()
} catch (e) { } catch (e) {
setToast((e as Error).message) setToast((e as Error).message)
@@ -128,7 +135,7 @@ export default function ProfileView({ username, onClose }: { username: string; o
setBusy(true) setBusy(true)
try { try {
await unfollow(profile.id) await unfollow(profile.id)
await load() await load(true)
void social.refresh() void social.refresh()
} catch (e) { } catch (e) {
setToast((e as Error).message) setToast((e as Error).message)
@@ -144,7 +151,7 @@ export default function ProfileView({ username, onClose }: { username: string; o
setBusy(true) setBusy(true)
try { try {
await blockUser({ id: profile.id, username: profile.username, displayName: profile.displayName, avatarUrl: profile.avatarUrl }) await blockUser({ id: profile.id, username: profile.username, displayName: profile.displayName, avatarUrl: profile.avatarUrl })
await load() await load(true)
void social.refresh() void social.refresh()
setToast(t('block.done', { name: profile.displayName })) setToast(t('block.done', { name: profile.displayName }))
} catch (e) { } catch (e) {
@@ -422,18 +429,29 @@ function LibraryTab({ profile, onOpen }: { profile: Profile; onOpen: (i: MediaIt
const [done, setDone] = useState(false) const [done, setDone] = useState(false)
const request = useRef(0) const request = useRef(0)
// Lignes reçues du serveur (y compris celles écartées à la relecture) : décalage de la page suivante
const received = useRef(0)
const loadPage = useCallback( const loadPage = useCallback(
async (reset: boolean) => { async (reset: boolean) => {
// Une réponse arrivée après un changement de filtre ne doit pas écraser la nouvelle liste // Une réponse arrivée après un changement de filtre ne doit pas écraser la nouvelle liste
const id = ++request.current const id = ++request.current
setLoading(true) setLoading(true)
if (reset) setList([]) if (reset) {
setList([])
received.current = 0
}
try { try {
const page = await getProfileItems(profile.id, status || null, reset ? 0 : list.length) const page = await getProfileItems(profile.id, status || null, reset ? 0 : received.current)
if (id !== request.current) return if (id !== request.current) return
setList((prev) => (reset ? page : [...prev, ...page])) received.current += page.received
setDone(page.length < 48) setList((prev) => {
// Sans doublon (une fiche ne peut apparaître qu'une fois : même clé React)
const base = reset ? [] : prev
const seen = new Set(base.map((i) => i.id))
return [...base, ...page.items.filter((i) => !seen.has(i.id) && !!seen.add(i.id))]
})
setDone(page.received < PROFILE_ITEMS_PAGE)
} catch { } catch {
if (id === request.current) setDone(true) if (id === request.current) setDone(true)
} finally { } finally {
@@ -441,7 +459,7 @@ function LibraryTab({ profile, onOpen }: { profile: Profile; onOpen: (i: MediaIt
} }
}, },
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
[profile.id, status, list.length], [profile.id, status],
) )
useEffect(() => { useEffect(() => {
+1 -3
View File
@@ -17,7 +17,6 @@ export default function ReviewComments({
authorId, authorId,
itemId, itemId,
count: initialCount, count: initialCount,
defaultOpen,
hidden, hidden,
children, children,
}: { }: {
@@ -25,14 +24,13 @@ export default function ReviewComments({
itemId: string itemId: string
/** Nombre connu (sinon chargé à l'ouverture) */ /** Nombre connu (sinon chargé à l'ouverture) */
count?: number | null count?: number | null
defaultOpen?: boolean
/** Serveur sans les commentaires (migration pas encore appliquée) : seules les autres actions s'affichent */ /** Serveur sans les commentaires (migration pas encore appliquée) : seules les autres actions s'affichent */
hidden?: boolean hidden?: boolean
children?: ReactNode children?: ReactNode
}) { }) {
const social = useSocial() const social = useSocial()
const { isBlocked } = useBlocked(social.enabled) const { isBlocked } = useBlocked(social.enabled)
const [open, setOpen] = useState(!!defaultOpen) const [open, setOpen] = useState(false)
const [count, setCount] = useState(initialCount ?? undefined) const [count, setCount] = useState(initialCount ?? undefined)
const [comments, setComments] = useState<ReviewComment[]>() const [comments, setComments] = useState<ReviewComment[]>()
const [unavailable, setUnavailable] = useState(false) const [unavailable, setUnavailable] = useState(false)
+2 -7
View File
@@ -11,17 +11,12 @@ export default function ReviewText({
text, text,
spoiler, spoiler,
className, className,
clamp,
revealed,
}: { }: {
text: string text: string
spoiler?: boolean spoiler?: boolean
className?: string className?: string
clamp?: boolean
/** Déjà dévoilé (mon propre avis) : seul le badge « Spoiler » reste */
revealed?: boolean
}) { }) {
const [shown, setShown] = useState(!spoiler || !!revealed) const [shown, setShown] = useState(!spoiler)
if (!shown) { if (!shown) {
return ( return (
@@ -51,7 +46,7 @@ export default function ReviewText({
<EyeOff size={11} aria-hidden="true" /> {t('spoiler.badge')} <EyeOff size={11} aria-hidden="true" /> {t('spoiler.badge')}
</span> </span>
)} )}
<p className={cx('whitespace-pre-line break-words text-sm leading-relaxed text-ink-2', clamp && 'line-clamp-6')}>{text}</p> <p className="whitespace-pre-line break-words text-sm leading-relaxed text-ink-2">{text}</p>
</div> </div>
) )
} }
+14 -22
View File
@@ -10,7 +10,6 @@ import ProfileView from './ProfileView'
import TitleReviews from './TitleReviews' import TitleReviews from './TitleReviews'
import { useOnResume } from '../../lib/onResume' import { useOnResume } from '../../lib/onResume'
import WelcomeProfile, { RANDOM_USERNAME } from './WelcomeProfile' import WelcomeProfile, { RANDOM_USERNAME } from './WelcomeProfile'
import CommentsSheet from './CommentsSheet'
import { InvitePeople, SharedListSheet } from './SharedLists' import { InvitePeople, SharedListSheet } from './SharedLists'
import { getAniListById, type SearchResult } from '../../lib/catalogApi' import { getAniListById, type SearchResult } from '../../lib/catalogApi'
import { TYPE_BY_VALUE } from '../../lib/constants' import { TYPE_BY_VALUE } from '../../lib/constants'
@@ -28,11 +27,8 @@ interface SocialApi {
openFollowList: (profile: Profile, kind: 'followers' | 'following') => void openFollowList: (profile: Profile, kind: 'followers' | 'following') => void
/** Tous les avis sur un titre (amis / autres) */ /** Tous les avis sur un titre (amis / autres) */
openReviews: (externalId: string, title: string) => void openReviews: (externalId: string, title: string) => void
peek: (item: MediaItem, owner?: PeekOwner) => void
/** Ouvre la fiche si elle est à moi, sinon l'aperçu */ /** Ouvre la fiche si elle est à moi, sinon l'aperçu */
openItem: (item: MediaItem, owner?: PeekOwner) => void openItem: (item: MediaItem, owner?: PeekOwner) => void
/** Fil de commentaires d'un avis, en plein écran (depuis une notification) */
openComments: (authorId: string, itemId: string, title: string) => void
/** Liste partagée */ /** Liste partagée */
openSharedList: (id: string) => void openSharedList: (id: string) => void
/** Inviter des membres dans une liste partagée */ /** Inviter des membres dans une liste partagée */
@@ -54,9 +50,7 @@ const SocialContext = createContext<SocialApi>({
openEdit: () => {}, openEdit: () => {},
openFollowList: () => {}, openFollowList: () => {},
openReviews: () => {}, openReviews: () => {},
peek: () => {},
openItem: () => {}, openItem: () => {},
openComments: () => {},
openSharedList: () => {}, openSharedList: () => {},
openInvite: () => {}, openInvite: () => {},
openTitle: () => {}, openTitle: () => {},
@@ -66,13 +60,14 @@ const SocialContext = createContext<SocialApi>({
export const useSocial = () => useContext(SocialContext) export const useSocial = () => useContext(SocialContext)
let overlayUid = 0
type Overlay = type Overlay =
| { kind: 'profile'; username: string } | { kind: 'profile'; username: string }
| { kind: 'search' } | { kind: 'search' }
| { kind: 'edit' } | { kind: 'edit' }
| { kind: 'follows'; profile: Profile; list: 'followers' | 'following' } | { kind: 'follows'; profile: Profile; list: 'followers' | 'following' }
| { kind: 'reviews'; externalId: string; title: string } | { kind: 'reviews'; externalId: string; title: string }
| { kind: 'comments'; authorId: string; itemId: string; title: string }
| { kind: 'sharedList'; id: string } | { kind: 'sharedList'; id: string }
| { kind: 'invite'; listId: string; listName: string } | { kind: 'invite'; listId: string; listName: string }
@@ -91,7 +86,7 @@ export function SocialProvider({
const enabled = !!account const enabled = !!account
const [me, setMe] = useState<Profile | null>(null) const [me, setMe] = useState<Profile | null>(null)
const [requests, setRequests] = useState<ProfileCard[]>([]) const [requests, setRequests] = useState<ProfileCard[]>([])
const [stack, setStack] = useState<Overlay[]>([]) const [stack, setStack] = useState<(Overlay & { uid: number })[]>([])
const [peeked, setPeeked] = useState<{ item: MediaItem; owner?: PeekOwner }>() const [peeked, setPeeked] = useState<{ item: MediaItem; owner?: PeekOwner }>()
const [sharedTick, setSharedTick] = useState(0) const [sharedTick, setSharedTick] = useState(0)
const bumpShared = useCallback(() => setSharedTick((n) => n + 1), []) const bumpShared = useCallback(() => setSharedTick((n) => n + 1), [])
@@ -129,8 +124,9 @@ export function SocialProvider({
// Nouvelles demandes d'abonnement, compteurs… mis à jour au retour sur l'app // Nouvelles demandes d'abonnement, compteurs… mis à jour au retour sur l'app
useOnResume(() => void refresh(), enabled) useOnResume(() => void refresh(), enabled)
const push = useCallback((o: Overlay) => setStack((s) => [...s.slice(-8), o]), []) // Clé stable par écran (et non sa place dans la pile, qui change quand la pile est écourtée)
const pop = useCallback(() => setStack((s) => s.slice(0, -1)), []) const push = useCallback((o: Overlay) => setStack((s) => [...s.slice(-8), { ...o, uid: ++overlayUid }]), [])
const close = useCallback((uid: number) => setStack((s) => s.filter((x) => x.uid !== uid)), [])
// Lien partagé « #/u/pseudo » // Lien partagé « #/u/pseudo »
useEffect(() => { useEffect(() => {
@@ -191,9 +187,7 @@ export function SocialProvider({
openEdit: () => push({ kind: 'edit' }), openEdit: () => push({ kind: 'edit' }),
openFollowList: (profile, list) => push({ kind: 'follows', profile, list }), openFollowList: (profile, list) => push({ kind: 'follows', profile, list }),
openReviews: (externalId, title) => push({ kind: 'reviews', externalId, title }), openReviews: (externalId, title) => push({ kind: 'reviews', externalId, title }),
peek: (item, owner) => setPeeked({ item, owner }),
openItem, openItem,
openComments: (authorId, itemId, title) => push({ kind: 'comments', authorId, itemId, title }),
openSharedList: (id) => push({ kind: 'sharedList', id }), openSharedList: (id) => push({ kind: 'sharedList', id }),
openInvite: (listId, listName) => push({ kind: 'invite', listId, listName }), openInvite: (listId, listName) => push({ kind: 'invite', listId, listName }),
openTitle: (s) => void openTitle(s), openTitle: (s) => void openTitle(s),
@@ -207,23 +201,21 @@ export function SocialProvider({
<SocialContext.Provider value={api}> <SocialContext.Provider value={api}>
{/* Les écrans sociaux sont placés avant l'app : une fiche ouverte depuis un profil passe au-dessus */} {/* Les écrans sociaux sont placés avant l'app : une fiche ouverte depuis un profil passe au-dessus */}
{enabled && {enabled &&
stack.map((o, k) => stack.map((o) =>
o.kind === 'profile' ? ( o.kind === 'profile' ? (
<ProfileView key={k} username={o.username} onClose={pop} /> <ProfileView key={o.uid} username={o.username} onClose={() => close(o.uid)} />
) : o.kind === 'search' ? ( ) : o.kind === 'search' ? (
<PeopleSearch key={k} onClose={pop} /> <PeopleSearch key={o.uid} onClose={() => close(o.uid)} />
) : o.kind === 'edit' ? ( ) : o.kind === 'edit' ? (
<EditProfile key={k} onClose={pop} /> <EditProfile key={o.uid} onClose={() => close(o.uid)} />
) : o.kind === 'follows' ? ( ) : o.kind === 'follows' ? (
<FollowList key={k} profile={o.profile} initial={o.list} onClose={pop} /> <FollowList key={o.uid} profile={o.profile} initial={o.list} onClose={() => close(o.uid)} />
) : o.kind === 'reviews' ? ( ) : o.kind === 'reviews' ? (
<TitleReviews key={k} externalId={o.externalId} title={o.title} onClose={pop} onOpenProfile={(u) => push({ kind: 'profile', username: u })} /> <TitleReviews key={o.uid} externalId={o.externalId} title={o.title} onClose={() => close(o.uid)} onOpenProfile={(u) => push({ kind: 'profile', username: u })} />
) : o.kind === 'comments' ? (
<CommentsSheet key={k} authorId={o.authorId} itemId={o.itemId} title={o.title} onClose={pop} />
) : o.kind === 'sharedList' ? ( ) : o.kind === 'sharedList' ? (
<SharedListSheet key={k} id={o.id} onClose={pop} /> <SharedListSheet key={o.uid} id={o.id} onClose={() => close(o.uid)} />
) : ( ) : (
<InvitePeople key={k} listId={o.listId} listName={o.listName} onClose={pop} /> <InvitePeople key={o.uid} listId={o.listId} listName={o.listName} onClose={() => close(o.uid)} />
), ),
)} )}
{children} {children}
+5 -2
View File
@@ -1,6 +1,7 @@
import { Loader2, Star } from 'lucide-react' import { Loader2, Star } from 'lucide-react'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { t } from '../../i18n' import { t } from '../../i18n'
import { getSession } from '../../lib/cloud/auth'
import { useBlocked } from '../../lib/cloud/moderation' import { useBlocked } from '../../lib/cloud/moderation'
import { titleReviews, type TitleReview, type TitleReviews as TitleReviewsData } from '../../lib/cloud/reviews' import { titleReviews, type TitleReview, type TitleReviews as TitleReviewsData } from '../../lib/cloud/reviews'
import { formatRating } from '../../lib/utils' import { formatRating } from '../../lib/utils'
@@ -71,6 +72,8 @@ function ReviewColumn({ heading, empty, list, onOpenProfile }: { heading: string
function ReviewCard({ r, onOpenProfile }: { r: TitleReview; onOpenProfile: (username: string) => void }) { function ReviewCard({ r, onOpenProfile }: { r: TitleReview; onOpenProfile: (username: string) => void }) {
const { settings } = useMedia() const { settings } = useMedia()
// Mon propre avis : ni signalement ni réaction (seuls les commentaires restent)
const mine = r.user_id === getSession()?.user.id
return ( return (
<article className="card p-3.5"> <article className="card p-3.5">
<div className="flex items-center gap-2.5"> <div className="flex items-center gap-2.5">
@@ -85,12 +88,12 @@ function ReviewCard({ r, onOpenProfile }: { r: TitleReview; onOpenProfile: (user
{formatRating(r.rating, settings.ratingScale)} {formatRating(r.rating, settings.ratingScale)}
</span> </span>
)} )}
<ReportButton target={{ type: 'review', id: r.item_id, userId: r.user_id }} className="-me-1.5" size={16} /> {!mine && <ReportButton target={{ type: 'review', id: r.item_id, userId: r.user_id }} className="-me-1.5" size={16} />}
</div> </div>
{r.notes && <ReviewText text={r.notes} spoiler={r.spoiler} />} {r.notes && <ReviewText text={r.notes} spoiler={r.spoiler} />}
<div className="mt-3"> <div className="mt-3">
<ReviewComments authorId={r.user_id} itemId={r.item_id} count={r.comments} hidden={r.comments === null}> <ReviewComments authorId={r.user_id} itemId={r.item_id} count={r.comments} hidden={r.comments === null}>
<Reactions authorId={r.user_id} itemId={r.item_id} reactions={r.reactions} mine={r.mine} /> {!mine && <Reactions authorId={r.user_id} itemId={r.item_id} reactions={r.reactions} mine={r.mine} />}
</ReviewComments> </ReviewComments>
</div> </div>
</article> </article>
+9 -2
View File
@@ -99,6 +99,13 @@ function SeasonRow({
if (highlight) ref.current?.scrollIntoView({ behavior: 'smooth', block: 'center' }) if (highlight) ref.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [highlight]) }, [highlight])
// À l'ouverture de l'éditeur : on repart de l'avis enregistré (il a pu changer depuis, ex. synchro)
const openEditor = () => {
setDraft(value?.notes ?? '')
setSpoiler(!!value?.spoiler)
setWriting(true)
}
return ( return (
<li ref={ref} id={`season-${n}`} className={cx('card p-3.5 transition-shadow', highlight && 'ring-2 ring-accent')}> <li ref={ref} id={`season-${n}`} className={cx('card p-3.5 transition-shadow', highlight && 'ring-2 ring-accent')}>
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
@@ -164,7 +171,7 @@ function SeasonRow({
</div> </div>
</div> </div>
) : value?.notes ? ( ) : value?.notes ? (
<button onClick={() => setWriting(true)} className="mt-3 block w-full text-start"> <button onClick={openEditor} className="mt-3 block w-full text-start">
<span className="flex items-center gap-1.5 text-xs text-ink-3"> <span className="flex items-center gap-1.5 text-xs text-ink-3">
{t('form.review')} {t('form.review')}
{value.spoiler && <span className="rounded-full border border-accent/50 px-1.5 py-px text-[10px] text-accent">{t('spoiler.badge')}</span>} {value.spoiler && <span className="rounded-full border border-accent/50 px-1.5 py-px text-[10px] text-accent">{t('spoiler.badge')}</span>}
@@ -173,7 +180,7 @@ function SeasonRow({
<p className="mt-1 line-clamp-4 whitespace-pre-line text-sm leading-relaxed">{value.notes}</p> <p className="mt-1 line-clamp-4 whitespace-pre-line text-sm leading-relaxed">{value.notes}</p>
</button> </button>
) : ( ) : (
<button onClick={() => setWriting(true)} className="mt-2.5 inline-flex items-center gap-1.5 text-xs font-medium text-ink-2"> <button onClick={openEditor} className="mt-2.5 inline-flex items-center gap-1.5 text-xs font-medium text-ink-2">
<Pencil size={12} /> {t('seasons.writeReview')} <Pencil size={12} /> {t('seasons.writeReview')}
</button> </button>
))} ))}
+18 -9
View File
@@ -67,6 +67,8 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
// La fiche suit la version à jour de la bibliothèque (ou celle créée depuis cette fiche) // La fiche suit la version à jour de la bibliothèque (ou celle créée depuis cette fiche)
const [itemId, setItemId] = useState<string | undefined>(() => initial?.id ?? (seed && items.find((i) => i.externalId === seed.externalId)?.id)) const [itemId, setItemId] = useState<string | undefined>(() => initial?.id ?? (seed && items.find((i) => i.externalId === seed.externalId)?.id))
const item = useMemo(() => (itemId ? items.find((i) => i.id === itemId) : undefined), [items, itemId]) const item = useMemo(() => (itemId ? items.find((i) => i.id === itemId) : undefined), [items, itemId])
// Étiquettes proposées : recalculées seulement quand la bibliothèque change
const tagSuggestions = useMemo(() => allTags(items), [items])
// Infos du catalogue pour un titre pas encore ajouté // Infos du catalogue pour un titre pas encore ajouté
const [meta, setMeta] = useState<Partial<MediaInput> | undefined>(() => (seed?.source === 'anilist' ? { ...seed.prefill } : undefined)) const [meta, setMeta] = useState<Partial<MediaInput> | undefined>(() => (seed?.source === 'anilist' ? { ...seed.prefill } : undefined))
@@ -201,9 +203,14 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
} }
// Changement de statut d'un titre déjà suivi : « Annuler » remet la fiche telle quelle (dates, épisodes…) // Changement de statut d'un titre déjà suivi : « Annuler » remet la fiche telle quelle (dates, épisodes…)
const before = item const before = item
void save(patch).then(() => { void save(patch)
if (before) actions.offerUndo(t('toast.status', { title: before.title, status: STATUS_BY_VALUE[s].label }), [before]) .then(() => {
}) if (before) actions.offerUndo(t('toast.status', { title: before.title, status: STATUS_BY_VALUE[s].label }), [before])
})
.catch((e) => {
// Mode découverte : la demande de compte est déjà ouverte
if (!(e instanceof GuestError)) setToast((e as Error).message)
})
} }
/** /**
@@ -287,6 +294,8 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
} }
const blob = await renderItemCard(item, settings.ratingScale, credits) const blob = await renderItemCard(item, settings.ratingScale, credits)
setPreview({ blob, filename: `kino-${slug(item.title)}.png` }) setPreview({ blob, filename: `kino-${slug(item.title)}.png` })
} catch {
setToast(t('share.err.create'))
} finally { } finally {
setSharing(false) setSharing(false)
} }
@@ -560,7 +569,7 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
)} )}
</div> </div>
) : ( ) : (
<button onClick={() => setReviewing(true)} disabled={busy} className="flex w-full items-center gap-2 rounded-2xl border border-dashed border-line-strong px-4 py-3.5 text-left text-sm text-ink-2"> <button onClick={() => setReviewing(true)} disabled={busy} className="flex w-full items-center gap-2 rounded-2xl border border-dashed border-line-strong px-4 py-3.5 text-start text-sm text-ink-2">
<Pencil size={16} className="text-accent" /> {t('title.writeReview')} <Pencil size={16} className="text-accent" /> {t('title.writeReview')}
</button> </button>
)} )}
@@ -621,7 +630,7 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
)} )}
{/* Mon suivi : dates, plateforme, listes, revisionnages */} {/* Mon suivi : dates, plateforme, listes, revisionnages */}
{item && <Tracking item={item} lists={lists} tagSuggestions={allTags(items)} onChange={changeTracking} />} {item && <Tracking item={item} lists={lists} tagSuggestions={tagSuggestions} onChange={changeTracking} />}
{/* Listes partagées avec d'autres membres (titre de ma bibliothèque ou pas encore ajouté) */} {/* Listes partagées avec d'autres membres (titre de ma bibliothèque ou pas encore ajouté) */}
{externalId && social.enabled && ( {externalId && social.enabled && (
@@ -701,8 +710,8 @@ function MoreMenu({ onClose, children }: { onClose: () => void; children: ReactN
useEscape(onClose) useEscape(onClose)
useBackToClose(onClose) useBackToClose(onClose)
return ( return (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 sm:items-center" onClick={onClose}> <div className="fixed inset-0 z-[60] flex items-end justify-center bg-scrim sm:items-center" onClick={onClose}>
<div role="menu" className="safe-bottom w-full max-w-md rounded-t-3xl border border-line-strong bg-surface p-3 sm:rounded-3xl" onClick={(e) => e.stopPropagation()}> <div className="safe-bottom w-full max-w-md rounded-t-3xl border border-line-strong bg-surface p-3 sm:rounded-3xl" onClick={(e) => e.stopPropagation()}>
{children} {children}
</div> </div>
</div> </div>
@@ -711,7 +720,7 @@ function MoreMenu({ onClose, children }: { onClose: () => void; children: ReactN
function MenuButton({ icon, children, onClick, danger }: { icon: ReactNode; children: ReactNode; onClick: () => void; danger?: boolean }) { function MenuButton({ icon, children, onClick, danger }: { icon: ReactNode; children: ReactNode; onClick: () => void; danger?: boolean }) {
return ( return (
<button onClick={onClick} className={cx('flex w-full items-center gap-3 rounded-xl px-3 py-3.5 text-left text-[15px] active:bg-surface-2', danger ? 'text-accent' : 'text-ink')}> <button onClick={onClick} className={cx('flex w-full items-center gap-3 rounded-xl px-3 py-3.5 text-start text-[15px] active:bg-surface-2', danger ? 'text-accent' : 'text-ink')}>
{icon} {icon}
{children} {children}
</button> </button>
@@ -832,7 +841,7 @@ function Tracking({ item, lists, tagSuggestions, onChange }: { item: MediaItem;
return ( return (
<section className="mx-4 mt-8 border-t border-line pt-5"> <section className="mx-4 mt-8 border-t border-line pt-5">
<button onClick={() => setOpen((v) => !v)} aria-expanded={open} className="flex w-full items-center justify-between text-left"> <button onClick={() => setOpen((v) => !v)} aria-expanded={open} className="flex w-full items-center justify-between text-start">
<span> <span>
<span className="eyebrow block text-ink-2">{t('title.myTracking')}</span> <span className="eyebrow block text-ink-2">{t('title.myTracking')}</span>
<span className="mt-1 block text-xs text-ink-3">{summary.length ? summary.join(' · ') : t('title.trackingHint')}</span> <span className="mt-1 block text-xs text-ink-3">{summary.length ? summary.join(' · ') : t('title.trackingHint')}</span>
+1 -1
View File
@@ -40,7 +40,7 @@ export function SectionTitle({ children, action }: { children: ReactNode; action
export function LinkArrow({ onClick, children }: { onClick: () => void; children: ReactNode }) { export function LinkArrow({ onClick, children }: { onClick: () => void; children: ReactNode }) {
return ( return (
<button onClick={onClick} className="shrink-0 text-xs font-medium text-ink-3 transition-colors hover:text-ink"> <button onClick={onClick} className="shrink-0 text-xs font-medium text-ink-3 transition-colors hover:text-ink">
{children} <span className="text-accent">→</span> {children} <span className="inline-block text-accent rtl:-scale-x-100">→</span>
</button> </button>
) )
} }
+26 -15
View File
@@ -1,4 +1,4 @@
import { Fragment, createContext, useCallback, useContext, useState, type ReactNode } from 'react' import { Fragment, createContext, useCallback, useContext, useRef, useState, type ReactNode } from 'react'
import { detectLang, getLang, isLangChosen, LANGS, loadLang, t, type Lang } from '.' import { detectLang, getLang, isLangChosen, LANGS, loadLang, t, type Lang } from '.'
interface LangApi { interface LangApi {
@@ -17,22 +17,33 @@ const TRANSLATED_CACHES = ['azuucine:releases', 'azuucine:global-releases']
export function LangProvider({ children }: { children: ReactNode }) { export function LangProvider({ children }: { children: ReactNode }) {
const [lang, setState] = useState<Lang>(getLang) const [lang, setState] = useState<Lang>(getLang)
const [auto, setAuto] = useState(() => !isLangChosen()) const [auto, setAuto] = useState(() => !isLangChosen())
const setLang = useCallback(async (choice: Lang | 'auto') => { // Changements de langue à la file, et seul le dernier demandé s'applique : un fichier de langue
const l = choice === 'auto' ? detectLang() : choice // lent (A) qui arrivait après un plus rapide (B) remettait l'app en A.
const queue = useRef<Promise<void>>(Promise.resolve())
const seq = useRef(0)
const setLang = useCallback((choice: Lang | 'auto') => {
const req = ++seq.current
setAuto(choice === 'auto') setAuto(choice === 'auto')
if (l === getLang()) { const run = queue.current.then(async () => {
await loadLang(l, choice === 'auto' ? null : true) if (req !== seq.current) return
return const l = choice === 'auto' ? detectLang() : choice
} if (l === getLang()) {
await loadLang(l, choice === 'auto' ? null : true) await loadLang(l, choice === 'auto' ? null : true)
for (const k of TRANSLATED_CACHES) { return
try {
localStorage.removeItem(k)
} catch {
/* ignore */
} }
} await loadLang(l, choice === 'auto' ? null : true)
setState(l) for (const k of TRANSLATED_CACHES) {
try {
localStorage.removeItem(k)
} catch {
/* ignore */
}
}
setState(l)
})
// Un fichier de langue qui ne se charge jamais ne bloque pas les choix suivants (10 s au plus)
queue.current = Promise.race([run.catch(() => {}), new Promise<void>((resolve) => setTimeout(resolve, 10_000))])
return run
}, []) }, [])
return ( return (
<LangContext.Provider value={{ lang, auto, setLang }}> <LangContext.Provider value={{ lang, auto, setLang }}>
+2
View File
@@ -20,6 +20,8 @@
--color-accent-fill: #d11f2f; --color-accent-fill: #d11f2f;
/* Texte posé sur un bouton plein (blanc ou noir selon le thème) */ /* Texte posé sur un bouton plein (blanc ou noir selon le thème) */
--color-on-accent: #ffffff; --color-on-accent: #ffffff;
/* Voile sombre derrière les fenêtres (identique dans toutes les apparences) */
--color-scrim: rgb(0 0 0 / 0.7);
--font-sans: 'Inter', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; --font-sans: 'Inter', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
} }
+24 -20
View File
@@ -39,21 +39,21 @@ const SEASONS_SINCE = '2026-10-04T10:00:00.000Z'
const n0 = (v: unknown, max = 100000) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v)) : 0) const n0 = (v: unknown, max = 100000) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v)) : 0)
// Dernière lecture (le cache est relu par chaque carte : on évite de le réanalyser à chaque fois) // Cache gardé en mémoire : loadAiring() est appelé par chaque carte à chaque rendu, on évite de relire
let memo: { raw: string | null; cache: AiringCache } | undefined // (et réanalyser) le stockage à chaque fois. Invalidé à l'enregistrement, sur CACHE_EVENT et quand
// un autre onglet modifie le stockage.
let memo: AiringCache | undefined
if (typeof window !== 'undefined') {
window.addEventListener('storage', (e) => {
if (e.key === null || e.key === KEY) memo = undefined
})
}
/** Relit le cache en ne gardant que des entrées bien formées. */ /** Relit le cache en ne gardant que des entrées bien formées. */
export function loadAiring(): AiringCache { export function loadAiring(): AiringCache {
let text: string | null = null memo ??= parseAiring()
try { return memo
text = localStorage.getItem(KEY)
} catch {
/* stockage indisponible */
}
if (memo && memo.raw === text) return memo.cache
const cache = parseAiring()
memo = { raw: text, cache }
return cache
} }
function parseAiring(): AiringCache { function parseAiring(): AiringCache {
@@ -73,12 +73,15 @@ function parseAiring(): AiringCache {
/** Émis quand le cache des sorties change (pastille du calendrier). */ /** Émis quand le cache des sorties change (pastille du calendrier). */
export const CACHE_EVENT = 'azuucine:schedule' export const CACHE_EVENT = 'azuucine:schedule'
if (typeof window !== 'undefined') window.addEventListener(CACHE_EVENT, () => (memo = undefined))
export function saveAiring(cache: AiringCache) { export function saveAiring(cache: AiringCache) {
try { try {
localStorage.setItem(KEY, JSON.stringify(cache)) localStorage.setItem(KEY, JSON.stringify(cache))
} catch { } catch {
/* ignore */ /* ignore */
} }
memo = undefined
window.dispatchEvent(new Event(CACHE_EVENT)) window.dispatchEvent(new Event(CACHE_EVENT))
} }
@@ -183,17 +186,18 @@ async function checkTmdb(tvId: string, key: string): Promise<Omit<AiringInfo, 'c
if (!res.ok) throw new Error(`TMDB ${res.status}`) if (!res.ok) throw new Error(`TMDB ${res.status}`)
d = (await res.json()) as TmdbTv d = (await res.json()) as TmdbTv
} }
// Épisodes diffusés = épisodes des saisons terminées + position du dernier épisode diffusé // Épisodes diffusés = épisodes des saisons terminées + position du dernier épisode diffusé.
// Les épisodes spéciaux (saison 0) ne comptent pas : un spécial diffusé en dernier ramenait
// le compte à son numéro (ex. 1). On se fie alors au prochain épisode régulier annoncé.
let aired = n0(d.number_of_episodes) let aired = n0(d.number_of_episodes)
const last = d.last_episode_to_air const last = d.last_episode_to_air
if (last && Array.isArray(d.seasons) && d.seasons.length) {
aired = n0(
d.seasons
.filter((s) => n0(s.season_number) > 0 && n0(s.season_number) < n0(last.season_number))
.reduce((sum, s) => sum + n0(s.episode_count), 0) + n0(last.episode_number),
)
}
const nx = d.next_episode_to_air const nx = d.next_episode_to_air
const before = (season: number) =>
(d.seasons ?? []).filter((s) => n0(s.season_number) > 0 && n0(s.season_number) < season).reduce((sum, s) => sum + n0(s.episode_count), 0)
if (last && Array.isArray(d.seasons) && d.seasons.length) {
if (n0(last.season_number) > 0) aired = n0(before(n0(last.season_number)) + n0(last.episode_number))
else if (nx && n0(nx.season_number) > 0 && n0(nx.episode_number) > 0) aired = n0(before(n0(nx.season_number)) + n0(nx.episode_number) - 1)
}
const nextDate = safeDay(nx?.air_date) const nextDate = safeDay(nx?.air_date)
// Rien encore diffusé (série annoncée) : les épisodes prévus ne sont pas « sortis » // Rien encore diffusé (série annoncée) : les épisodes prévus ne sont pas « sortis »
if (!last && (nx || d.status === 'Planned' || d.status === 'In Production')) aired = 0 if (!last && (nx || d.status === 'Planned' || d.status === 'In Production')) aired = 0
+7 -1
View File
@@ -34,6 +34,11 @@ const int = (v: unknown, min = 0, max = 1e6) => {
const n = num(v, min, max) const n = num(v, min, max)
return n == null ? undefined : Math.round(n) return n == null ? undefined : Math.round(n)
} }
/** Année plausible, sinon absente (une valeur aberrante n'est pas ramenée à 1870 ou 2200). */
const year = (v: unknown) => {
const n = num(v, -Infinity, Infinity)
return n != null && n >= 1870 && n <= 2200 ? Math.round(n) : undefined
}
const rating = (v: unknown) => { const rating = (v: unknown) => {
const n = num(v, 0, 10) const n = num(v, 0, 10)
return n == null || n === 0 ? undefined : Math.round(n * 2) / 2 return n == null || n === 0 ? undefined : Math.round(n * 2) / 2
@@ -108,7 +113,7 @@ export function normalizeItem(raw: unknown): MediaItem | null {
originalTitle: cleanText(r.originalTitle, LIMITS.title), originalTitle: cleanText(r.originalTitle, LIMITS.title),
type, type,
subtype: type === 'autre' ? cleanText(r.subtype, LIMITS.shortText) : undefined, subtype: type === 'autre' ? cleanText(r.subtype, LIMITS.shortText) : undefined,
year: int(r.year, 1870, 2200), year: year(r.year),
status: (STATUS_SET.has(r.status as string) ? r.status : 'a_voir') as WatchStatus, status: (STATUS_SET.has(r.status as string) ? r.status : 'a_voir') as WatchStatus,
rating: rating(r.rating), rating: rating(r.rating),
criteria, criteria,
@@ -137,6 +142,7 @@ export function normalizeItem(raw: unknown): MediaItem | null {
rewatch: normalizeRewatch(r.rewatch), rewatch: normalizeRewatch(r.rewatch),
seasonRatings: normalizeSeasonRatings(r.seasonRatings), seasonRatings: normalizeSeasonRatings(r.seasonRatings),
episodeLog: normalizeEpisodeLog(r.episodeLog), episodeLog: normalizeEpisodeLog(r.episodeLog),
rewatchLog: normalizeEpisodeLog(r.rewatchLog),
publicRating: (() => { publicRating: (() => {
const n = num(r.publicRating, 0, 10) const n = num(r.publicRating, 0, 10)
return n ? Math.round(n * 10) / 10 : undefined return n ? Math.round(n * 10) / 10 : undefined
+40 -16
View File
@@ -6,7 +6,7 @@ import { subtypeLabel, tmdbGenres } from './genres'
import { franchiseKey } from './franchise' import { franchiseKey } from './franchise'
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, remoteImage, safeCountries, safeDay, safePosterUrl, safeSeasons, safeStringList } from './security' import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, remoteImage, safeCountries, safeDay, safePosterUrl, safeSeasons, safeStringList } from './security'
import { localDay } from './utils' import { localDay } from './utils'
import { parseAniListLinks, parseTmdbProviders, type StreamLink, type WatchRegion } from './watchProviders' import { getWatchRegion, parseAniListLinks, parseTmdbProviders, type StreamLink, type WatchRegion } from './watchProviders'
/** /**
* Recherche dans les bases publiques : * Recherche dans les bases publiques :
@@ -120,12 +120,21 @@ export function isPlausibleTmdbKey(key: string): boolean {
/** Seules ces adresses de l'API TMDB peuvent être appelées. */ /** Seules ces adresses de l'API TMDB peuvent être appelées. */
const TMDB_PATHS = /^\/(search\/(multi|person)|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?|find\/(tt)?\d{1,10}|person\/\d{1,10})$/ const TMDB_PATHS = /^\/(search\/(multi|person)|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?|find\/(tt)?\d{1,10}|person\/\d{1,10})$/
/** Délai max d'une requête vers TMDB / AniList (réseau lent ou serveur muet). */
const FETCH_TIMEOUT = 12_000
const timeout = () => AbortSignal.timeout(FETCH_TIMEOUT)
/** Texte recherché : sans caractères de contrôle, et pas plus long que ce qu'accepte le proxy (100 caractères). */
// eslint-disable-next-line no-control-regex
const searchText = (q: string) => q.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, 100)
/** « Clé » spéciale : avec un compte, les requêtes passent par le serveur qui détient la vraie clé TMDB. */ /** « Clé » spéciale : avec un compte, les requêtes passent par le serveur qui détient la vraie clé TMDB. */
export const CLOUD_TMDB = 'cloud-proxy' export const CLOUD_TMDB = 'cloud-proxy'
async function tmdbFetch<T>(path: string, key: string, params: Record<string, string> = {}): Promise<T> { async function tmdbFetch<T>(path: string, key: string, params: Record<string, string> = {}): Promise<T> {
const k = key.trim() const k = key.trim()
if (!TMDB_PATHS.test(path)) throw new Error(t('err.tmdbRefused')) if (!TMDB_PATHS.test(path)) throw new Error(t('err.tmdbRefused'))
if (typeof params.query === 'string') params = { ...params, query: searchText(params.query) }
if (k === CLOUD_TMDB) return tmdbViaCloud<T>(path, { language: tmdbLanguage(), ...params }) if (k === CLOUD_TMDB) return tmdbViaCloud<T>(path, { language: tmdbLanguage(), ...params })
if (!isPlausibleTmdbKey(k)) throw new Error(t('err.tmdbKeyRefused')) if (!isPlausibleTmdbKey(k)) throw new Error(t('err.tmdbKeyRefused'))
const isBearer = k.length > 40 // jeton de lecture v4 (JWT) vs clé v3 (32 caractères) const isBearer = k.length > 40 // jeton de lecture v4 (JWT) vs clé v3 (32 caractères)
@@ -137,6 +146,7 @@ async function tmdbFetch<T>(path: string, key: string, params: Record<string, st
headers: isBearer ? { Authorization: `Bearer ${k}` } : {}, headers: isBearer ? { Authorization: `Bearer ${k}` } : {},
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
credentials: 'omit', credentials: 'omit',
signal: timeout(),
}) })
if (res.status === 401) throw new Error(t('err.tmdbKeyRefused')) if (res.status === 401) throw new Error(t('err.tmdbKeyRefused'))
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status })) if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
@@ -179,7 +189,7 @@ function tmdbToResult(r: TmdbItem, kind: 'movie' | 'tv'): SearchResult | null {
} }
export async function searchTmdb(query: string, key: string): Promise<SearchResult[]> { export async function searchTmdb(query: string, key: string): Promise<SearchResult[]> {
const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: query.slice(0, LIMITS.searchQuery), include_adult: 'false' }) const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: searchText(query), include_adult: 'false' })
return (Array.isArray(data.results) ? data.results : []) return (Array.isArray(data.results) ? data.results : [])
.filter((r) => r.media_type === 'movie' || r.media_type === 'tv') .filter((r) => r.media_type === 'movie' || r.media_type === 'tv')
.slice(0, 15) .slice(0, 15)
@@ -275,7 +285,8 @@ export async function getTmdbDetails(result: SearchResult, key: string): Promise
const d = await tmdbFetch<TmdbDetails>(`/${kind}/${id}`, key, { append_to_response: 'watch/providers' }) const d = await tmdbFetch<TmdbDetails>(`/${kind}/${id}`, key, { append_to_response: 'watch/providers' })
const guess = guessTmdbType(kind, (d.genres ?? []).map((g) => g.id), d.origin_country ?? [], d.original_language) const guess = guessTmdbType(kind, (d.genres ?? []).map((g) => g.id), d.origin_country ?? [], d.original_language)
const providers = d['watch/providers']?.results const providers = d['watch/providers']?.results
const provider = (providers?.[region()] ?? providers?.FR)?.flatrate?.[0]?.provider_name // Même pays que « Où regarder » (choisi à la main, sinon celui du navigateur)
const provider = (providers?.[getWatchRegion()] ?? providers?.FR)?.flatrate?.[0]?.provider_name
const title = (kind === 'movie' ? d.title : d.name) ?? result.title const title = (kind === 'movie' ? d.title : d.name) ?? result.title
const original = kind === 'movie' ? d.original_title : d.original_name const original = kind === 'movie' ? d.original_title : d.original_name
const epRuntime = d.episode_run_time?.[0] || d.last_episode_to_air?.runtime || undefined const epRuntime = d.episode_run_time?.[0] || d.last_episode_to_air?.runtime || undefined
@@ -403,11 +414,13 @@ interface AniMedia {
genres?: string[] genres?: string[]
seasonYear?: number | null seasonYear?: number | null
startDate?: { year?: number | null } startDate?: { year?: number | null }
title: { romaji?: string | null; english?: string | null; native?: string | null } title?: { romaji?: string | null; english?: string | null; native?: string | null } | null
coverImage?: { medium?: string | null; large?: string | null } coverImage?: { medium?: string | null; large?: string | null }
description?: string | null description?: string | null
countryOfOrigin?: string | null countryOfOrigin?: string | null
averageScore?: number | null averageScore?: number | null
/** Demandé seulement par certaines requêtes (recommandations, fiche par id) */
isAdult?: boolean
} }
const ANILIST_GENRES: Record<string, string> = { const ANILIST_GENRES: Record<string, string> = {
@@ -450,6 +463,7 @@ export async function searchAniList(query: string): Promise<SearchResult[]> {
body: JSON.stringify({ query: ANILIST_QUERY, variables: { search: query.slice(0, LIMITS.searchQuery) } }), body: JSON.stringify({ query: ANILIST_QUERY, variables: { search: query.slice(0, LIMITS.searchQuery) } }),
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
credentials: 'omit', credentials: 'omit',
signal: timeout(),
}) })
if (res.status === 429) throw new Error(t('err.anilistRate')) if (res.status === 429) throw new Error(t('err.anilistRate'))
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status })) if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
@@ -462,8 +476,8 @@ export async function searchAniList(query: string): Promise<SearchResult[]> {
function aniToResult(m: AniMedia): SearchResult | null { function aniToResult(m: AniMedia): SearchResult | null {
if (!m || !Number.isInteger(m.id)) return null if (!m || !Number.isInteger(m.id)) return null
const isMovie = m.format === 'MOVIE' const isMovie = m.format === 'MOVIE'
const title = m.title.english || m.title.romaji || m.title.native || '?' const title = m.title?.english || m.title?.romaji || m.title?.native || '?'
const original = m.title.native || m.title.romaji || undefined const original = m.title?.native || m.title?.romaji || undefined
const year = m.seasonYear ?? m.startDate?.year ?? undefined const year = m.seasonYear ?? m.startDate?.year ?? undefined
const type: MediaType = isMovie ? 'film' : 'anime' const type: MediaType = isMovie ? 'film' : 'anime'
return safeResult({ return safeResult({
@@ -471,7 +485,7 @@ function aniToResult(m: AniMedia): SearchResult | null {
externalId: `anilist:${m.id}`, externalId: `anilist:${m.id}`,
title, title,
originalTitle: original && original !== title ? original : undefined, originalTitle: original && original !== title ? original : undefined,
altTitles: [m.title.romaji, m.title.english, m.title.native].filter((x): x is string => !!x).slice(0, 3), altTitles: [m.title?.romaji, m.title?.english, m.title?.native].filter((x): x is string => !!x).slice(0, 3),
year: year ?? undefined, year: year ?? undefined,
thumb: m.coverImage?.medium ?? undefined, thumb: m.coverImage?.medium ?? undefined,
posterUrl: m.coverImage?.large ?? m.coverImage?.medium ?? undefined, posterUrl: m.coverImage?.large ?? m.coverImage?.medium ?? undefined,
@@ -540,18 +554,20 @@ export async function aniListRecommendations(externalId: string): Promise<Search
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
query: `query ($id: Int) { Media(id: $id) { recommendations(sort: RATING_DESC, perPage: 15) { nodes { mediaRecommendation { ${ANILIST_FIELDS} } } } } }`, query: `query ($id: Int) { Media(id: $id) { recommendations(sort: RATING_DESC, perPage: 15) { nodes { mediaRecommendation { isAdult ${ANILIST_FIELDS} } } } } }`,
variables: { id }, variables: { id },
}), }),
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
credentials: 'omit', credentials: 'omit',
signal: timeout(),
}) })
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status })) if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Media?: { recommendations?: { nodes?: { mediaRecommendation?: AniMedia | null }[] } } } } const json = (await res.json()) as { data?: { Media?: { recommendations?: { nodes?: { mediaRecommendation?: AniMedia | null }[] } } } }
const nodes = json.data?.Media?.recommendations?.nodes const nodes = json.data?.Media?.recommendations?.nodes
return (Array.isArray(nodes) ? nodes : []) return (Array.isArray(nodes) ? nodes : [])
.map((n) => n.mediaRecommendation) .map((n) => n.mediaRecommendation)
.filter((m): m is AniMedia => !!m) // Pas de contenu adulte (comme la recherche, qui demande isAdult: false)
.filter((m): m is AniMedia => !!m && !m.isAdult)
.map(aniToResult) .map(aniToResult)
.filter((r): r is SearchResult => r !== null) .filter((r): r is SearchResult => r !== null)
} }
@@ -675,6 +691,7 @@ export async function getAniListReleases(ids: number[]): Promise<Map<number, Rel
headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
credentials: 'omit', credentials: 'omit',
signal: timeout(),
body: JSON.stringify({ body: JSON.stringify({
query: query:
'query ($ids: [Int]) { Page(perPage: 50) { media(id_in: $ids, type: ANIME) { id startDate { year month day } nextAiringEpisode { episode airingAt } } } }', 'query ($ids: [Int]) { Page(perPage: 50) { media(id_in: $ids, type: ANIME) { id startDate { year month day } nextAiringEpisode { episode airingAt } } } }',
@@ -907,6 +924,7 @@ export async function aniListAiring(from: string, to: string, minPopularity = 40
headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
credentials: 'omit', credentials: 'omit',
signal: timeout(),
body: JSON.stringify({ body: JSON.stringify({
query: `query ($start: Int, $end: Int, $page: Int) { Page(page: $page, perPage: 50) { pageInfo { hasNextPage } query: `query ($start: Int, $end: Int, $page: Int) { Page(page: $page, perPage: 50) { pageInfo { hasNextPage }
airingSchedules(airingAt_greater: $start, airingAt_lesser: $end, sort: TIME) { airingAt episode airingSchedules(airingAt_greater: $start, airingAt_lesser: $end, sort: TIME) { airingAt episode
@@ -968,14 +986,16 @@ export async function getAniListById(externalId: string): Promise<SearchResult |
headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
credentials: 'omit', credentials: 'omit',
signal: timeout(),
body: JSON.stringify({ body: JSON.stringify({
query: `query ($id: Int) { Media(id: $id, type: ANIME) {${ANILIST_FIELDS} } }`, query: `query ($id: Int) { Media(id: $id, type: ANIME) { isAdult ${ANILIST_FIELDS} } }`,
variables: { id: Number(externalId.split(':')[1]) }, variables: { id: Number(externalId.split(':')[1]) },
}), }),
}) })
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status })) if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Media?: AniMedia } } const json = (await res.json()) as { data?: { Media?: AniMedia } }
return json.data?.Media ? aniToResult(json.data.Media) : null const m = json.data?.Media
return m && !m.isAdult ? aniToResult(m) : null
} }
/** Résultat « recherche » TMDB minimal à partir d'une sortie (pour l'ajout rapide). */ /** Résultat « recherche » TMDB minimal à partir d'une sortie (pour l'ajout rapide). */
@@ -1060,7 +1080,8 @@ async function tmdbExtras(externalId: string, key: string): Promise<TitleExtras>
// 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.
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) => {
if (key.trim() !== CLOUD_TMDB) throw e // 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
return tmdbFetch<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits' }) return tmdbFetch<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits' })
}) })
const cast = (Array.isArray(d.credits?.cast) ? d.credits!.cast! : []) const cast = (Array.isArray(d.credits?.cast) ? d.credits!.cast! : [])
@@ -1133,6 +1154,7 @@ async function aniListExtras(externalId: string): Promise<TitleExtras> {
body: JSON.stringify({ query: ANILIST_EXTRAS, variables: { id } }), body: JSON.stringify({ query: ANILIST_EXTRAS, variables: { id } }),
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
credentials: 'omit', credentials: 'omit',
signal: timeout(),
}) })
if (res.status === 429) throw new Error(t('err.anilistRate')) if (res.status === 429) throw new Error(t('err.anilistRate'))
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status })) if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
@@ -1175,11 +1197,13 @@ export function getTitleExtras(externalId: string, tmdbKey?: string): Promise<Ti
if (!isSafeExternalId(externalId)) return Promise.reject(new Error(t('err.tmdbRef'))) if (!isSafeExternalId(externalId)) return Promise.reject(new Error(t('err.tmdbRef')))
const isTmdb = externalId.startsWith('tmdb:') const isTmdb = externalId.startsWith('tmdb:')
if (isTmdb && !tmdbKey?.trim()) return Promise.reject(new Error(t('search.animeOnly'))) if (isTmdb && !tmdbKey?.trim()) return Promise.reject(new Error(t('search.animeOnly')))
const cached = extrasCache.get(externalId) // La langue fait partie de la clé : changer de langue ne doit pas resservir l'ancienne version
const cacheKey = `${externalId}:${tmdbLanguage()}`
const cached = extrasCache.get(cacheKey)
if (cached) return cached if (cached) return cached
const p = isTmdb ? tmdbExtras(externalId, tmdbKey!) : aniListExtras(externalId) const p = isTmdb ? tmdbExtras(externalId, tmdbKey!) : aniListExtras(externalId)
extrasCache.set(externalId, p) extrasCache.set(cacheKey, p)
p.catch(() => extrasCache.delete(externalId)) p.catch(() => extrasCache.delete(cacheKey))
return p return p
} }
@@ -1210,7 +1234,7 @@ function tmdbWithPrefill(r: TmdbItem, kind: 'movie' | 'tv'): SearchResult | null
/** Recherche TMDB (films et séries) avec métadonnées de base, dans l'ordre de pertinence de TMDB. */ /** Recherche TMDB (films et séries) avec métadonnées de base, dans l'ordre de pertinence de TMDB. */
export async function tmdbImportSearch(query: string, key: string): Promise<SearchResult[]> { export async function tmdbImportSearch(query: string, key: string): Promise<SearchResult[]> {
const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: query.slice(0, 100), include_adult: 'false' }) const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: searchText(query), include_adult: 'false' })
return (Array.isArray(data.results) ? data.results : []) return (Array.isArray(data.results) ? data.results : [])
.filter((r) => r && (r.media_type === 'movie' || r.media_type === 'tv')) .filter((r) => r && (r.media_type === 'movie' || r.media_type === 'tv'))
.slice(0, 20) .slice(0, 20)
+55 -14
View File
@@ -88,13 +88,25 @@ export const newChallengeId = () => Math.random().toString(36).slice(2, 12).padE
const LOG_MAX_DAYS = 400 const LOG_MAX_DAYS = 400
/** Nouveau journal après un changement du nombre d'épisodes vus (aujourd'hui). */ /**
* Nouveau journal après un changement du nombre d'épisodes vus (aujourd'hui).
* Épisodes décochés : on les retire des jours les plus récents d'abord (sinon cocher 10 un jour,
* en décocher 5 le lendemain puis les recocher compterait 15 épisodes).
*/
export function logEpisodes(log: Record<string, number> | undefined, delta: number, day = localDay()): Record<string, number> | undefined { export function logEpisodes(log: Record<string, number> | undefined, delta: number, day = localDay()): Record<string, number> | undefined {
if (!delta) return log if (!delta) return log
const next = { ...(log ?? {}) } const next = { ...(log ?? {}) }
const value = Math.max(0, (next[day] ?? 0) + delta) if (delta > 0) next[day] = Math.min((next[day] ?? 0) + delta, 100000)
if (value) next[day] = Math.min(value, 100000) else {
else delete next[day] let rest = -delta
for (const d of Object.keys(next).sort().reverse()) {
if (rest <= 0) break
const take = Math.min(rest, next[d])
rest -= take
if (next[d] - take > 0) next[d] -= take
else delete next[d]
}
}
const days = Object.keys(next).sort() const days = Object.keys(next).sort()
for (const d of days.slice(0, Math.max(0, days.length - LOG_MAX_DAYS))) delete next[d] for (const d of days.slice(0, Math.max(0, days.length - LOG_MAX_DAYS))) delete next[d]
return Object.keys(next).length ? next : undefined return Object.keys(next).length ? next : undefined
@@ -143,12 +155,21 @@ export interface ChallengeProgress {
const matches = (item: MediaItem, media: Media) => media === 'all' || item.type === media const matches = (item: MediaItem, media: Media) => media === 'all' || item.type === media
/** Nombre compté par jour (pour la date de réussite et le rythme). */ /**
* Nombre compté par jour (pour la date de réussite et le rythme) : valeurs ponctuelles (`perDay`)
* et, pour les estimations réparties sur une période, variations du débit quotidien (`rateDelta`,
* +débit au premier jour, −débit le lendemain du dernier) au lieu d'une valeur par jour.
*/
function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, items: MediaItem[]) { function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, items: MediaItem[]) {
const s = toNum(c.start) const s = toNum(c.start)
const e = toNum(c.end) const e = toNum(c.end)
const perDay = new Map<number, number>() const perDay = new Map<number, number>()
const rateDelta = new Map<number, number>()
const add = (day: number, n: number) => perDay.set(day, (perDay.get(day) ?? 0) + n) const add = (day: number, n: number) => perDay.set(day, (perDay.get(day) ?? 0) + n)
const addRange = (lo: number, hi: number, rate: number) => {
rateDelta.set(lo, (rateDelta.get(lo) ?? 0) + rate)
rateDelta.set(hi + 1, (rateDelta.get(hi + 1) ?? 0) - rate)
}
const entries: CountedEntry[] = [] const entries: CountedEntry[] = []
let estimated = false let estimated = false
@@ -169,7 +190,7 @@ function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, ite
} }
// Épisodes (les films n'en ont pas) // Épisodes (les films n'en ont pas)
if (!TYPE_BY_VALUE[item.type].episodic || item.episodesWatched <= 0) continue if (!TYPE_BY_VALUE[item.type].episodic || (item.episodesWatched <= 0 && !item.rewatchLog)) continue
let amount = 0 let amount = 0
let last = '' let last = ''
let partEstimated = false let partEstimated = false
@@ -184,10 +205,18 @@ function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, ite
if (d > last) last = d if (d > last) last = d
} }
} }
// Épisodes revus : comptés le jour où ils ont été vus, sans toucher à l'estimation du premier visionnage
for (const [d, n] of Object.entries(item.rewatchLog ?? {})) {
if (d >= c.start && d <= c.end) {
amount += n
add(toNum(d), n)
if (d > last) last = d
}
}
const unlogged = Math.max(0, item.episodesWatched - logged) const unlogged = Math.max(0, item.episodesWatched - logged)
const from = item.startDate ?? item.endDate const from = item.startDate ?? item.endDate
if (unlogged > 0 && from) { if (unlogged > 0 && from) {
let to = item.endDate ?? (logDays[0] ? fromNum(toNum(logDays[0]) - 1) : item.updatedAt.slice(0, 10)) let to = item.endDate ?? (logDays[0] ? fromNum(toNum(logDays[0]) - 1) : localDay(new Date(item.updatedAt)))
if (!safeDay(to) || to < from) to = from if (!safeDay(to) || to < from) to = from
const a = toNum(from) const a = toNum(from)
const b = toNum(to) const b = toNum(to)
@@ -195,7 +224,7 @@ function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, ite
const hi = Math.min(b, e) const hi = Math.min(b, e)
if (hi >= lo) { if (hi >= lo) {
const rate = unlogged / (b - a + 1) const rate = unlogged / (b - a + 1)
for (let d = lo; d <= hi; d++) add(d, rate) addRange(lo, hi, rate)
amount += rate * (hi - lo + 1) amount += rate * (hi - lo + 1)
partEstimated = true partEstimated = true
const lastEst = fromNum(hi) const lastEst = fromNum(hi)
@@ -207,22 +236,34 @@ function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, ite
entries.push({ item, date: last, amount: partEstimated ? Math.max(1, Math.round(amount)) : amount, estimated: partEstimated }) entries.push({ item, date: last, amount: partEstimated ? Math.max(1, Math.round(amount)) : amount, estimated: partEstimated })
} }
} }
return { perDay, entries, estimated } return { perDay, rateDelta, entries, estimated }
} }
export function computeProgress(c: Challenge, items: MediaItem[], today = localDay()): ChallengeProgress { export function computeProgress(c: Challenge, items: MediaItem[], today = localDay()): ChallengeProgress {
const { perDay, entries, estimated } = dailyCounts(c, items) const { perDay, rateDelta, entries, estimated } = dailyCounts(c, items)
const s = toNum(c.start) const s = toNum(c.start)
const e = toNum(c.end) const e = toNum(c.end)
const now = toNum(today) const now = toNum(today)
// Cumul jour par jour : date de réussite // Cumul jour par jour : date de réussite. Le total affiché est arrondi : l'objectif est atteint
// dès que le cumul arrondi y arrive (même règle que `count`, sinon la date ne correspondrait pas).
const goal = c.target - 0.5 - 1e-6
let total = 0 let total = 0
let rate = 0
let next: number | undefined // premier jour pas encore compté
let doneAt: string | undefined let doneAt: string | undefined
const days = [...perDay.keys()].sort((a, b) => a - b) const days = [...new Set([...perDay.keys(), ...rateDelta.keys()])].sort((a, b) => a - b)
for (const d of days) { for (const d of days) {
total += perDay.get(d)! // Jours sans événement depuis le précédent : seul le débit estimé s'ajoute
if (!doneAt && total + 1e-6 >= c.target) doneAt = fromNum(d) if (next !== undefined && d > next && rate > 1e-12) {
const span = d - next
if (!doneAt && total + rate * span >= goal) doneAt = fromNum(next + Math.max(1, Math.ceil((goal - total) / rate)) - 1)
total += rate * span
}
rate += rateDelta.get(d) ?? 0
total += (perDay.get(d) ?? 0) + Math.max(0, rate)
if (!doneAt && total >= goal) doneAt = fromNum(d)
next = d + 1
} }
const count = Math.round(total) const count = Math.round(total)
const done = count >= c.target const done = count >= c.target
+36 -8
View File
@@ -1,19 +1,37 @@
import { t } from '../../i18n' import { t } from '../../i18n'
import { AuthError, getAccessToken } from './auth' import { AuthError, getAccessToken, getSession } from './auth'
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config' import { SUPABASE_ANON_KEY, SUPABASE_URL, TimeoutError, withTimeout } from './config'
/** fetch avec un délai maximal (le serveur qui ne répond pas ne bloque jamais l'app). */
async function timedFetch(url: string, init: RequestInit = {}): Promise<Response> {
try {
// Délai proportionnel à la taille de l'envoi (photo, grosse synchro sur une connexion lente : ~5 Ko/s minimum),
// et long pour la suppression de compte (le serveur efface tout avant de répondre)
const bytes = init.body instanceof Blob ? init.body.size : typeof init.body === 'string' ? init.body.length : 0
const ms = url.includes('/functions/v1/delete-account') ? 120_000 : Math.max(20_000, 20_000 + bytes / 5)
return await withTimeout((signal) => fetch(url, { ...init, signal }), init.signal, ms)
} catch (e) {
if (e instanceof TimeoutError) throw new Error(t('common.offline'))
throw e
}
}
/** Appel authentifié à Supabase (base de données ou fonctions serveur). Réessaie une fois si le jeton a expiré. */ /** Appel authentifié à Supabase (base de données ou fonctions serveur). Réessaie une fois si le jeton a expiré. */
export async function cloudFetch(path: string, init: RequestInit = {}): Promise<Response> { export async function cloudFetch(path: string, init: RequestInit = {}): Promise<Response> {
let failed: string | undefined
for (let attempt = 0; attempt < 2; attempt++) { for (let attempt = 0; attempt < 2; attempt++) {
const token = await getAccessToken(attempt > 0) // Après un refus : on ne force le renouvellement que si le jeton refusé est toujours le jeton courant
// (plusieurs appels refusés en même temps ne déclenchent qu'un renouvellement, les autres reprennent le nouveau)
const token = await getAccessToken(failed !== undefined && getSession()?.accessToken === failed)
if (!token) throw new AuthError(t('auth.err.session')) if (!token) throw new AuthError(t('auth.err.session'))
const res = await fetch(SUPABASE_URL + path, { const res = await timedFetch(SUPABASE_URL + path, {
...init, ...init,
headers: { apikey: SUPABASE_ANON_KEY, Authorization: `Bearer ${token}`, ...(init.headers ?? {}) }, headers: { apikey: SUPABASE_ANON_KEY, Authorization: `Bearer ${token}`, ...(init.headers ?? {}) },
credentials: 'omit', credentials: 'omit',
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
}) })
if (res.status !== 401) return res if (res.status !== 401) return res
failed = token
} }
throw new AuthError(t('auth.err.session')) throw new AuthError(t('auth.err.session'))
} }
@@ -24,7 +42,7 @@ export async function tmdbViaCloud<T>(path: string, params: Record<string, strin
// Sans compte (mode découverte) : appel anonyme, limité côté serveur par adresse IP // Sans compte (mode découverte) : appel anonyme, limité côté serveur par adresse IP
const res = (await getAccessToken()) const res = (await getAccessToken())
? await cloudFetch(`/functions/v1/tmdb?${q}`) ? await cloudFetch(`/functions/v1/tmdb?${q}`)
: await fetch(`${SUPABASE_URL}/functions/v1/tmdb?${q}`, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' }) : await timedFetch(`${SUPABASE_URL}/functions/v1/tmdb?${q}`, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' })
if (res.status === 429) throw new Error(t('err.searchRate')) if (res.status === 429) throw new Error(t('err.searchRate'))
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>
@@ -36,14 +54,24 @@ export type ProxyState = 'ok' | 'missing-key' | 'not-deployed' | 'offline' | 'er
export async function checkTmdbProxy(): Promise<ProxyState> { export async function checkTmdbProxy(): Promise<ProxyState> {
if (!navigator.onLine) return 'offline' if (!navigator.onLine) return 'offline'
try { try {
const res = await cloudFetch(`/functions/v1/tmdb?${new URLSearchParams({ path: '/configuration' })}`) const path = `/functions/v1/tmdb?${new URLSearchParams({ path: '/configuration' })}`
let res: Response
try {
res = await cloudFetch(path)
} catch (e) {
// Pas de session valable : ce n'est pas le proxy qui manque, on le teste sans compte (comme la recherche)
if (!(e instanceof AuthError)) throw e
res = await timedFetch(SUPABASE_URL + path, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' })
}
if (res.ok) return 'ok' if (res.ok) return 'ok'
if (res.status === 404) return 'not-deployed' if (res.status === 404) return 'not-deployed'
const body = (await res.json().catch(() => ({}))) as { error?: string; status?: number } const body = (await res.json().catch(() => ({}))) as { error?: string; status?: number }
if (res.status === 500 && body.error?.includes('TMDB_API_KEY')) return 'missing-key' if (res.status === 500 && body.error?.includes('TMDB_API_KEY')) return 'missing-key'
if (res.status === 502 && body.status === 401) return 'missing-key' if (res.status === 502 && body.status === 401) return 'missing-key'
return 'error' return 'error'
} catch { } catch (e) {
return navigator.onLine ? 'not-deployed' : 'offline' if (!navigator.onLine) return 'offline'
// Échec réseau (fonction absente) ; un serveur qui ne répond pas à temps n'est pas « non déployé »
return e instanceof TypeError ? 'not-deployed' : 'error'
} }
} }
+98 -28
View File
@@ -1,5 +1,5 @@
import { t, type TKey } from '../../i18n' import { t, type TKey } from '../../i18n'
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config' import { SUPABASE_ANON_KEY, SUPABASE_URL, withTimeout } from './config'
import { isPwnedPassword } from '../pwned' import { isPwnedPassword } from '../pwned'
/** /**
@@ -108,17 +108,21 @@ const msg = (code: string) => (CODE_KEYS[code] ? t(CODE_KEYS[code], { n: PASSWOR
async function gotrue(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<Record<string, unknown>> { async function gotrue(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<Record<string, unknown>> {
let res: Response let res: Response
try { try {
res = await fetch(`${SUPABASE_URL}/auth/v1${path}`, { // Délai maximal : sans réponse, on fait comme hors-ligne plutôt que d'attendre indéfiniment
method: init.method ?? 'POST', res = await withTimeout((signal) =>
headers: { fetch(`${SUPABASE_URL}/auth/v1${path}`, {
apikey: SUPABASE_ANON_KEY, method: init.method ?? 'POST',
'Content-Type': 'application/json', headers: {
...(init.token ? { Authorization: `Bearer ${init.token}` } : {}), apikey: SUPABASE_ANON_KEY,
}, 'Content-Type': 'application/json',
body: init.body ? JSON.stringify(init.body) : undefined, ...(init.token ? { Authorization: `Bearer ${init.token}` } : {}),
credentials: 'omit', },
referrerPolicy: 'no-referrer', body: init.body ? JSON.stringify(init.body) : undefined,
}) credentials: 'omit',
referrerPolicy: 'no-referrer',
signal,
}),
)
} catch { } catch {
throw new Error(t('common.offline')) throw new Error(t('common.offline'))
} }
@@ -131,8 +135,7 @@ async function gotrue(path: string, init: { method?: string; body?: unknown; tok
if (!res.ok) { if (!res.ok) {
const code = String(data.error_code ?? data.code ?? data.error ?? '') const code = String(data.error_code ?? data.code ?? data.error ?? '')
const err = new AuthError(msg(code) ?? (res.status === 429 ? t('auth.err.rate') : t('auth.err.status', { status: res.status }))) const err = new AuthError(msg(code) ?? (res.status === 429 ? t('auth.err.rate') : t('auth.err.status', { status: res.status })))
;(err as AuthError & { status: number; code: string }).status = res.status ;(err as AuthError & { status: number }).status = res.status
;(err as AuthError & { status: number; code: string }).code = code
throw err throw err
} }
return data return data
@@ -160,8 +163,9 @@ export async function signIn(email: string, password: string): Promise<void> {
setSession(s) setSession(s)
} }
/** Crée un compte. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). */ /**
/** Inscription. Le pseudo choisi est repris par la base à la création du profil (s'il est libre). */ * Inscription. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). Le pseudo choisi est repris par la base à la création du profil (s'il est libre).
*/
export async function signUp(email: string, password: string, username?: string): Promise<boolean> { export async function signUp(email: string, password: string, username?: string): Promise<boolean> {
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN })) if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
if (await isPwnedPassword(password)) throw new AuthError(t('auth.err.pwned')) if (await isPwnedPassword(password)) throw new AuthError(t('auth.err.pwned'))
@@ -190,7 +194,17 @@ export async function updatePassword(password: string): Promise<void> {
/** Déconnexion : invalide la session côté serveur (si possible) et l'efface de l'appareil. */ /** Déconnexion : invalide la session côté serveur (si possible) et l'efface de l'appareil. */
export async function signOut(): Promise<void> { export async function signOut(): Promise<void> {
const s = current let s = current
// Jeton d'accès expiré (ou presque) : on tente d'abord de le renouveler, sinon le serveur refuserait
// la déconnexion et la session resterait ouverte côté serveur. Effacée sur l'appareil quoi qu'il arrive.
if (s && navigator.onLine && s.expiresAt - 60_000 <= Date.now()) {
try {
const next = await refresh()
if (next && next.user.id === s.user.id) s = next
} catch {
/* au mieux */
}
}
setSession(null) setSession(null)
if (s && navigator.onLine) { if (s && navigator.onLine) {
try { try {
@@ -226,17 +240,34 @@ export async function signInWithGoogle(): Promise<void> {
location.assign(`${SUPABASE_URL}/auth/v1/authorize?${params}`) location.assign(`${SUPABASE_URL}/auth/v1/authorize?${params}`)
} }
/** Retour de Google : adresse avec ?code=… (ou ?error=…). */ /** Vérificateur gardé pendant l'aller-retour vers Google (null s'il n'y en a pas). */
export const hasOAuthRedirect = () => /[?&](code|error)=/.test(location.search) function readVerifier(): { verifier?: unknown; at?: unknown } | null {
try {
const raw = localStorage.getItem(VERIFIER_KEY)
const parsed: unknown = raw ? JSON.parse(raw) : null
return parsed && typeof parsed === 'object' ? (parsed as { verifier?: unknown; at?: unknown }) : null
} catch {
return null
}
}
/**
* Retour de Google : adresse avec ?code=… (ou ?error=…), seulement si une connexion Google a été lancée
* depuis cet appareil (vérificateur présent) — une autre adresse avec ?code= n'est pas un retour de Google.
*/
export const hasOAuthRedirect = () => /[?&](code|error)=/.test(location.search) && readVerifier() !== null
async function consumeOAuthRedirect(): Promise<{ error?: string }> { async function consumeOAuthRedirect(): Promise<{ error?: string }> {
const params = new URLSearchParams(location.search) const params = new URLSearchParams(location.search)
const code = params.get('code') ?? '' const code = params.get('code') ?? ''
const oauthError = params.get('error_description') ?? params.get('error') const oauthError = params.get('error_description') ?? params.get('error')
history.replaceState(null, '', `${location.pathname}#/`) history.replaceState(null, '', `${location.pathname}#/`)
let saved: { verifier?: string; at?: number } = {} const stored = readVerifier()
const saved = {
verifier: typeof stored?.verifier === 'string' ? stored.verifier : undefined,
at: typeof stored?.at === 'number' ? stored.at : undefined,
}
try { try {
saved = JSON.parse(localStorage.getItem(VERIFIER_KEY) ?? '{}')
localStorage.removeItem(VERIFIER_KEY) localStorage.removeItem(VERIFIER_KEY)
} catch { } catch {
/* ignore */ /* ignore */
@@ -260,26 +291,65 @@ async function consumeOAuthRedirect(): Promise<{ error?: string }> {
let refreshing: Promise<Session | null> | null = null let refreshing: Promise<Session | null> | null = null
/**
* Session plus récente laissée par un autre onglet (même compte, jeton de renouvellement différent,
* ou nouveau jeton d'accès encore valable) : à reprendre plutôt que de renouveler avec un jeton périmé.
*/
function newerStored(s: Session): Session | null {
const stored = load()
if (!stored || stored.user.id !== s.user.id) return null
// Seulement une session plus récente que la nôtre (si notre propre écriture avait échoué, le stockage est en retard)
if (stored.expiresAt <= s.expiresAt) return null
if (stored.refreshToken !== s.refreshToken) return stored
if (stored.accessToken !== s.accessToken && stored.expiresAt - 60_000 > Date.now()) return stored
return null
}
async function refresh(): Promise<Session | null> { async function refresh(): Promise<Session | null> {
const s = current if (!current) return null
if (!s) return null
refreshing ??= (async () => { refreshing ??= (async () => {
const s = current
if (!s) return null
// Un autre onglet a peut-être déjà renouvelé la session (le jeton de renouvellement ne sert qu'une fois)
const adopted = newerStored(s)
if (adopted) {
setSession(adopted)
return adopted
}
const sent = s.refreshToken
try { try {
const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: s.refreshToken } }) const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: sent } })
const next = toSession(data) const next = toSession(data)
// Déconnexion (ou autre compte) pendant le renouvellement : on ne ressuscite pas l'ancienne session // Déconnexion (ou autre compte) pendant le renouvellement : on ne ressuscite pas l'ancienne session
if (!next || next.user.id !== s.user.id || current?.user.id !== s.user.id) return null if (!next || next.user.id !== s.user.id || current?.user.id !== s.user.id) return null
// Session plus récente entre-temps (nouvelle connexion, autre onglet) : on ne l'écrase pas
if (current.refreshToken !== sent) return current
setSession(next) setSession(next)
return next return next
} catch (e) { } catch (e) {
// Un autre onglet a renouvelé pendant ce temps : notre jeton était simplement périmé
if (current?.user.id === s.user.id && current.refreshToken !== sent) return current
const adoptedLate = newerStored(s)
if (adoptedLate && current?.user.id === s.user.id) {
setSession(adoptedLate)
return adoptedLate
}
// Jeton de renouvellement refusé (révoqué, compte supprimé…) : on déconnecte // Jeton de renouvellement refusé (révoqué, compte supprimé…) : on déconnecte
const status = (e as { status?: number }).status const status = (e as { status?: number }).status
if ((status === 400 || status === 401 || status === 403) && current?.user.id === s.user.id) setSession(null) const stored = load()
if (
(status === 400 || status === 401 || status === 403) &&
current?.user.id === s.user.id &&
current.refreshToken === sent &&
(!stored || stored.refreshToken === sent)
) {
setSession(null)
}
return null return null
} finally {
refreshing = null
} }
})() })().finally(() => {
refreshing = null
})
return refreshing return refreshing
} }
+32
View File
@@ -17,3 +17,35 @@ export const cloudEnabled = !!(SUPABASE_URL && SUPABASE_ANON_KEY)
if (!cloudEnabled && (rawUrl || rawKey)) { if (!cloudEnabled && (rawUrl || rawKey)) {
console.warn('[Kino] .env incomplet ou invalide : les comptes sont désactivés (mode local). Vérifie VITE_SUPABASE_URL et VITE_SUPABASE_ANON_KEY.') console.warn('[Kino] .env incomplet ou invalide : les comptes sont désactivés (mode local). Vérifie VITE_SUPABASE_URL et VITE_SUPABASE_ANON_KEY.')
} }
/** Délai maximal d'attente d'une réponse du serveur (la déconnexion ou la synchro ne doivent jamais rester bloquées). */
export const CLOUD_TIMEOUT_MS = 20_000
/**
* Lance `run` avec un signal qui s'interrompt au bout de `ms` (ou si `signal`, celui de l'appelant, s'interrompt).
* Le délai ne court que jusqu'à l'arrivée des en-têtes : la lecture d'une longue réponse n'est pas coupée.
* `timedOut()` indique si c'est le délai (et non l'appelant) qui a interrompu l'appel.
*/
export async function withTimeout<T>(run: (signal: AbortSignal) => Promise<T>, signal?: AbortSignal | null, ms = CLOUD_TIMEOUT_MS): Promise<T> {
const ctrl = new AbortController()
let expired = false
const onAbort = () => ctrl.abort(signal?.reason)
if (signal?.aborted) ctrl.abort(signal.reason)
else signal?.addEventListener('abort', onAbort, { once: true })
const timer = setTimeout(() => {
expired = true
ctrl.abort()
}, ms)
try {
return await run(ctrl.signal)
} catch (e) {
if (expired) throw new TimeoutError()
throw e
} finally {
clearTimeout(timer)
signal?.removeEventListener('abort', onAbort)
}
}
/** Le serveur n'a pas répondu à temps. */
export class TimeoutError extends Error {}
+15 -15
View File
@@ -28,15 +28,8 @@ export const REPORT_DETAILS_MAX = 500
export const BUG_DESCRIPTION_MIN = 10 export const BUG_DESCRIPTION_MIN = 10
export const BUG_DESCRIPTION_MAX = 2000 export const BUG_DESCRIPTION_MAX = 2000
/** Erreur renvoyée par le serveur, avec son code court (« rate limited », « not found »…). */ /** Erreur renvoyée par le serveur (message déjà traduit). */
export class ModerationError extends Error { export class ModerationError extends Error {}
constructor(
message: string,
readonly code: string,
) {
super(message)
}
}
async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise<T> { async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {
const res = await cloudFetch(`/rest/v1/rpc/${name}`, { const res = await cloudFetch(`/rest/v1/rpc/${name}`, {
@@ -49,7 +42,7 @@ async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise
const code = typeof body.message === 'string' ? body.message.slice(0, 40) : `http ${res.status}` const code = typeof body.message === 'string' ? body.message.slice(0, 40) : `http ${res.status}`
const msg = const msg =
code === 'rate limited' ? t('report.errRate') : code === 'not found' ? t('report.errNotFound') : res.status === 404 ? t('report.errUnavailable') : t('social.err.server', { status: res.status }) code === 'rate limited' ? t('report.errRate') : code === 'not found' ? t('report.errNotFound') : res.status === 404 ? t('report.errUnavailable') : t('social.err.server', { status: res.status })
throw new ModerationError(msg, code) throw new ModerationError(msg)
} }
const text = await res.text() const text = await res.text()
return (text ? JSON.parse(text) : null) as T return (text ? JSON.parse(text) : null) as T
@@ -88,13 +81,18 @@ const listeners = new Set<() => void>()
const emit = () => listeners.forEach((fn) => fn()) const emit = () => listeners.forEach((fn) => fn())
/** Charge (une fois par session) la liste des comptes que j'ai bloqués. Silencieux si le serveur n'est pas à jour. */ /** Charge (une fois par session) la liste des comptes que j'ai bloqués. Silencieux si le serveur n'est pas à jour. */
export function loadBlocks(force = false): Promise<void> { export function loadBlocks(): Promise<void> {
const uid = getSession()?.user.id const uid = getSession()?.user.id
if (loaded && !force && loadedFor === uid) return loaded if (loaded && loadedFor === uid) return loaded
if (loadedFor !== uid) blocked = [] if (loadedFor !== uid) blocked = []
loadedFor = uid loadedFor = uid
loaded = rpc<unknown>('my_blocks') const p: Promise<void> = rpc<unknown>('my_blocks')
.then((rows) => { .then((rows) => {
// Réponse arrivée après un changement de compte : elle ne concerne plus le compte ouvert
if (loadedFor !== uid || getSession()?.user.id !== uid) {
if (loaded === p) loaded = null
return
}
blocked = (Array.isArray(rows) ? rows : []).flatMap((r) => { blocked = (Array.isArray(rows) ? rows : []).flatMap((r) => {
if (!isPlainObject(r) || typeof r.id !== 'string' || !UUID.test(r.id)) return [] if (!isPlainObject(r) || typeof r.id !== 'string' || !UUID.test(r.id)) return []
const username = cleanText(r.username, 20) ?? '' const username = cleanText(r.username, 20) ?? ''
@@ -103,9 +101,11 @@ export function loadBlocks(force = false): Promise<void> {
emit() emit()
}) })
.catch(() => { .catch(() => {
/* fonction pas encore déployée / hors-ligne : rien n'est masqué */ /* fonction pas encore déployée / hors-ligne : rien n'est masqué, on réessaiera au prochain affichage */
if (loaded === p) loaded = null
}) })
return loaded loaded = p
return p
} }
export const isBlocked = (userId: string | undefined | null) => !!userId && loadedFor === getSession()?.user.id && blocked.some((b) => b.id === userId) export const isBlocked = (userId: string | undefined | null) => !!userId && loadedFor === getSession()?.user.id && blocked.some((b) => b.id === userId)
+31 -9
View File
@@ -162,16 +162,32 @@ export async function getMyProfile(): Promise<Profile | null> {
return row?.username ? getProfile(row.username) : null return row?.username ? getProfile(row.username) : null
} }
export async function getProfileItems(userId: string, status: string | null, offset: number): Promise<MediaItem[]> { /** Nombre de lignes renvoyées par le serveur (avant le tri des lignes invalides) : sert au décalage de la page suivante. */
if (!UUID.test(userId)) return [] const rawCount = (v: unknown) => (Array.isArray(v) ? v.length : 0)
return toItems(await rpc('get_profile_items', { p_user: userId, p_status: status, p_offset: offset, p_limit: 48 }))
export const PROFILE_ITEMS_PAGE = 48
/** Une page de la bibliothèque d'un profil. `received` : lignes reçues du serveur (pour la page suivante). */
export async function getProfileItems(userId: string, status: string | null, offset: number): Promise<{ items: MediaItem[]; received: number }> {
if (!UUID.test(userId)) return { items: [], received: 0 }
const raw = await rpc('get_profile_items', { p_user: userId, p_status: status, p_offset: offset, p_limit: PROFILE_ITEMS_PAGE })
return { items: toItems(raw), received: rawCount(raw) }
} }
export async function getFeed(before?: string): Promise<FeedEntry[]> { export const FEED_PAGE = 30
const raw = await rpc('get_feed', { p_before: before ?? null, p_limit: 30 })
if (!Array.isArray(raw)) return [] /**
* Une page du fil. `received` : lignes reçues du serveur ; `cursor` : date de la dernière ligne reçue
* (même invalide), d'où repartir pour la page suivante.
*/
export async function getFeed(before?: string): Promise<{ entries: FeedEntry[]; received: number; cursor?: string }> {
const raw = await rpc('get_feed', { p_before: before ?? null, p_limit: FEED_PAGE })
if (!Array.isArray(raw)) return { entries: [], received: 0 }
const out: FeedEntry[] = [] const out: FeedEntry[] = []
let cursor: string | undefined
for (const r of raw.slice(0, 50)) { for (const r of raw.slice(0, 50)) {
// Date brute du serveur (précision à la microseconde) : rien n'est sauté ni répété d'une page à l'autre
if (isPlainObject(r) && safeIso(r.created_at)) cursor = r.created_at as string
if (!isPlainObject(r) || !isPlainObject(r.user)) continue if (!isPlainObject(r) || !isPlainObject(r.user)) continue
const item = othersItem(r.item) const item = othersItem(r.item)
const name = username(r.user.username) const name = username(r.user.username)
@@ -186,14 +202,20 @@ export async function getFeed(before?: string): Promise<FeedEntry[]> {
item, item,
}) })
} }
return out return { entries: out, received: raw.length, cursor }
} }
const toCards = (raw: unknown) => (Array.isArray(raw) ? raw.slice(0, 100).map(toCard).filter((c): c is ProfileCard => c !== null) : []) const toCards = (raw: unknown) => (Array.isArray(raw) ? raw.slice(0, 100).map(toCard).filter((c): c is ProfileCard => c !== null) : [])
export const searchProfiles = async (q: string) => (q.trim().length < 2 ? [] : toCards(await rpc('search_profiles', { q: q.trim().slice(0, 40) }))) export const searchProfiles = async (q: string) => (q.trim().length < 2 ? [] : toCards(await rpc('search_profiles', { q: q.trim().slice(0, 40) })))
export const getFollowList = async (userId: string, kind: 'followers' | 'following', offset = 0) => /** Le serveur renvoie au plus 50 comptes à la fois */
UUID.test(userId) ? toCards(await rpc('get_follow_list', { p_user: userId, p_kind: kind, p_offset: offset })) : [] export const FOLLOW_PAGE = 50
/** Une page d'abonnés / d'abonnements. `received` : lignes reçues du serveur (pour la page suivante). */
export async function getFollowList(userId: string, kind: 'followers' | 'following', offset = 0): Promise<{ cards: ProfileCard[]; received: number }> {
if (!UUID.test(userId)) return { cards: [], received: 0 }
const raw = await rpc('get_follow_list', { p_user: userId, p_kind: kind, p_offset: offset })
return { cards: toCards(raw), received: rawCount(raw) }
}
export const getFollowRequests = async () => toCards(await rpc('get_follow_requests')) export const getFollowRequests = async () => toCards(await rpc('get_follow_requests'))
// ─── Abonnements ─── // ─── Abonnements ───
+176 -46
View File
@@ -1,10 +1,10 @@
import { t } from '../../i18n' import { t } from '../../i18n'
import type { CustomList, MediaItem, Settings } from '../../types' import type { CustomList, MediaItem, Settings } from '../../types'
import { normalizeItem, normalizeLists, normalizeSettings } from '../backup' import { normalizeItem, normalizeLists, normalizeSettings } from '../backup'
import { mediaDB, onMediaChange } from '../db' import { mediaDB, onMediaChange, type RemoteDecision } from '../db'
import { blobToPosterDataURL } from '../image' import { blobToPosterDataURL } from '../image'
import { isPlainObject, isSafeId, safeIso } from '../security' import { isPlainObject, isSafeId, safeIso } from '../security'
import { scopedKey } from '../scope' import { getScope, scopedKey } from '../scope'
import { cloudFetch } from './api' import { cloudFetch } from './api'
/** /**
@@ -42,12 +42,48 @@ interface SyncMeta {
} }
const PAGE = 500 const PAGE = 500
/** Limite d'une fiche côté serveur : 400 000 octets (texte jsonb, un peu plus long que JSON.stringify) → marge. */
const MAX_ROW_BYTES = 380_000 const MAX_ROW_BYTES = 380_000
const MAX_BATCH_BYTES = 1_500_000 const MAX_BATCH_BYTES = 1_500_000
const OVERLAP_MS = 60_000 const OVERLAP_MS = 60_000
const jsonHeaders = { 'Content-Type': 'application/json' } const jsonHeaders = { 'Content-Type': 'application/json' }
/** Taille réelle en octets (UTF-8 : un accent ou un emoji compte pour plusieurs). */
const encoder = new TextEncoder()
const byteSize = (v: unknown) => encoder.encode(JSON.stringify(v)).length
/** Data URL → Blob sans fetch (la CSP n'autorise pas `data:` en connect-src). */
function dataURLToBlob(url: string): Blob {
const comma = url.indexOf(',')
const head = url.slice(0, comma)
const body = url.slice(comma + 1)
const type = head.slice(5).split(';')[0] || 'application/octet-stream'
if (!/;base64$/i.test(head)) return new Blob([decodeURIComponent(body)], { type })
const bin = atob(body)
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
return new Blob([bytes], { type })
}
/** Refus du serveur propre à une ligne (et non session expirée, limite de débit…) : inutile de la renvoyer. */
const isRowRejected = (e: PushError) =>
e.status >= 400 && e.status < 500 && ![401, 403, 404, 408, 429].includes(e.status) &&
// Quota du compte atteint : ce n'est pas la fiche qui pose problème, on la garde en attente (elle partira plus tard)
!/quota/i.test(e.detail)
/** Erreur d'envoi, avec le code HTTP. */
class PushError extends Error {
constructor(
readonly status: number,
readonly detail = '',
) {
super(t('sync.err.push', { status }))
}
}
const maxIso = (a?: string, b?: string) => (a && b ? (a > b ? a : b) : (a ?? b))
export interface SyncEngine { export interface SyncEngine {
start: () => void start: () => void
stop: () => void stop: () => void
@@ -84,14 +120,51 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
} }
let meta = loadMeta() let meta = loadMeta()
const saveMeta = () => { /** Entrées de la boîte d'envoi envoyées par cet onglet (clé → horodatage envoyé). */
const sent = new Map<string, string>()
/** Toujours le même compte, pas déconnecté : sinon on n'écrit plus rien sur l'appareil. */
const alive = () => !stopped && getScope() === userId
/**
* Un autre onglet du même compte partage cette boîte d'envoi : on relit ce qui est enregistré et on
* fusionne (sans écraser ses entrées en attente, sans ressusciter celles que cet onglet a envoyées).
*/
const mergeStored = () => {
const stored = loadMeta()
for (const [k, v] of Object.entries(stored.outbox)) {
if (sent.get(k) === v) continue
if (!meta.outbox[k] || meta.outbox[k] < v) meta.outbox[k] = v
}
meta.itemsCursor = maxIso(meta.itemsCursor, stored.itemsCursor)
meta.listsCursor = maxIso(meta.listsCursor, stored.listsCursor)
meta.settingsAt = maxIso(meta.settingsAt, stored.settingsAt)
meta.lastSyncAt = maxIso(meta.lastSyncAt, stored.lastSyncAt)
}
const saveMeta = (cursors?: Pick<SyncMeta, 'itemsCursor' | 'listsCursor'>) => {
if (!alive()) return
try { try {
mergeStored()
// Curseur volontairement reculé (fiches à relire) : il ne doit pas être ré-avancé par la fusion
if (cursors) Object.assign(meta, cursors)
localStorage.setItem(META_KEY, JSON.stringify(meta)) localStorage.setItem(META_KEY, JSON.stringify(meta))
} catch { } catch {
/* ignore */ /* ignore */
} }
} }
/** Retire de la boîte d'envoi ce qui vient de partir (sauf si re-modifié entre-temps). */
const done = (keys: string[], snapshot: Record<string, string>) => {
for (const k of keys) {
if (meta.outbox[k] !== snapshot[k]) continue
delete meta.outbox[k]
sent.set(k, snapshot[k])
}
saveMeta()
setStatus({})
}
let status: SyncStatus = { state: 'idle', lastSyncAt: meta.lastSyncAt, pending: Object.keys(meta.outbox).length } let status: SyncStatus = { state: 'idle', lastSyncAt: meta.lastSyncAt, pending: Object.keys(meta.outbox).length }
const listeners = new Set<(s: SyncStatus) => void>() const listeners = new Set<(s: SyncStatus) => void>()
const setStatus = (patch: Partial<SyncStatus>) => { const setStatus = (patch: Partial<SyncStatus>) => {
@@ -110,38 +183,68 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
/** Réduit une fiche trop lourde (affiche importée en très haute qualité) avant envoi. */ /** Réduit une fiche trop lourde (affiche importée en très haute qualité) avant envoi. */
async function fitForUpload(item: MediaItem): Promise<MediaItem> { async function fitForUpload(item: MediaItem): Promise<MediaItem> {
if (JSON.stringify(item).length <= MAX_ROW_BYTES) return item if (byteSize(item) <= MAX_ROW_BYTES) return item
if (item.poster?.startsWith('data:image')) { if (item.poster?.startsWith('data:image')) {
try { try {
const blob = await (await fetch(item.poster)).blob() const blob = dataURLToBlob(item.poster)
const smaller = { ...item, poster: await blobToPosterDataURL(blob, 360, 0.75) } const smaller = { ...item, poster: await blobToPosterDataURL(blob, 360, 0.75) }
if (JSON.stringify(smaller).length <= MAX_ROW_BYTES) return smaller if (byteSize(smaller) <= MAX_ROW_BYTES) return smaller
} catch { } catch {
/* image illisible */ /* image illisible */
} }
} }
const { poster: _poster, ...rest } = item const { poster: _poster, ...rest } = item
const stripped = rest as MediaItem const stripped = rest as MediaItem
return JSON.stringify(stripped).length <= MAX_ROW_BYTES ? stripped : { ...stripped, notes: stripped.notes?.slice(0, 5000), overview: undefined } return byteSize(stripped) <= MAX_ROW_BYTES ? stripped : { ...stripped, notes: stripped.notes?.slice(0, 5000), overview: undefined }
} }
async function upsert(table: 'items' | 'lists', rows: { id: string; data: unknown; deleted: boolean; updated_at: string }[]) { type UpRow = { id: string; data: unknown; deleted: boolean; updated_at: string }
async function send(table: 'items' | 'lists', rows: UpRow[]) {
const res = await cloudFetch(`/rest/v1/${table}?on_conflict=user_id,id`, {
method: 'POST',
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
body: JSON.stringify(rows.map((r) => ({ ...r, user_id: userId }))),
})
if (!res.ok) throw new PushError(res.status, (await res.text().catch(() => '')).slice(0, 500))
}
/** Envoi par paquets ; chaque paquet accepté est aussitôt retiré de la boîte d'envoi (`sentRows`). */
async function upsert(table: 'items' | 'lists', rows: UpRow[], sentRows: (rows: UpRow[]) => void) {
// Envoi par paquets de taille raisonnable // Envoi par paquets de taille raisonnable
let batch: typeof rows = [] let batch: UpRow[] = []
let size = 0 let size = 0
const flush = async () => { const flush = async () => {
if (!batch.length) return if (!batch.length) return
const res = await cloudFetch(`/rest/v1/${table}?on_conflict=user_id,id`, { const current = batch
method: 'POST',
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
body: JSON.stringify(batch.map((r) => ({ ...r, user_id: userId }))),
})
if (!res.ok) throw new Error(t('sync.err.push', { status: res.status }))
batch = [] batch = []
size = 0 size = 0
try {
await send(table, current)
} catch (e) {
if (!(e instanceof PushError) || !isRowRejected(e)) throw e
// Paquet refusé : on renvoie ligne par ligne, une fiche invalide ne bloque pas les autres
for (const r of current) {
let status = e.status
try {
if (current.length > 1) {
await send(table, [r])
sentRows([r])
continue
}
} catch (err) {
if (!(err instanceof PushError) || !isRowRejected(err)) throw err
status = err.status
}
console.warn(`[sync] ${table}/${r.id} refusé par le serveur (${status}), ignoré`)
sentRows([r])
}
return
}
sentRows(current)
} }
for (const r of rows) { for (const r of rows) {
const bytes = JSON.stringify(r).length const bytes = byteSize(r)
if (size + bytes > MAX_BATCH_BYTES || batch.length >= 200) await flush() if (size + bytes > MAX_BATCH_BYTES || batch.length >= 200) await flush()
batch.push(r) batch.push(r)
size += bytes size += bytes
@@ -150,13 +253,15 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
} }
async function push() { async function push() {
// Entrées ajoutées par un autre onglet du même compte : envoyées aussi
if (alive()) mergeStored()
const snapshot = { ...meta.outbox } const snapshot = { ...meta.outbox }
const keys = Object.keys(snapshot) const keys = Object.keys(snapshot)
if (!keys.length) return if (!keys.length) return
const itemIds = keys.filter((k) => k.startsWith('i:')).map((k) => k.slice(2)) const itemIds = keys.filter((k) => k.startsWith('i:')).map((k) => k.slice(2))
if (itemIds.length) { if (itemIds.length) {
const rows = [] const rows: UpRow[] = []
for (const id of itemIds) { for (const id of itemIds) {
const item = await mediaDB.get(id) const item = await mediaDB.get(id)
if (item) { if (item) {
@@ -166,7 +271,7 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
rows.push({ id, data: null, deleted: true, updated_at: snapshot[`i:${id}`] }) rows.push({ id, data: null, deleted: true, updated_at: snapshot[`i:${id}`] })
} }
} }
await upsert('items', rows) await upsert('items', rows, (sentRows) => done(sentRows.map((r) => `i:${r.id}`), snapshot))
} }
const listIds = keys.filter((k) => k.startsWith('l:')).map((k) => k.slice(2)) const listIds = keys.filter((k) => k.startsWith('l:')).map((k) => k.slice(2))
@@ -178,6 +283,7 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
const l = current.get(id) const l = current.get(id)
return { id, data: l ?? null, deleted: !l, updated_at: snapshot[`l:${id}`] } return { id, data: l ?? null, deleted: !l, updated_at: snapshot[`l:${id}`] }
}), }),
(sentRows) => done(sentRows.map((r) => `l:${r.id}`), snapshot),
) )
} }
@@ -187,13 +293,11 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' }, headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
body: JSON.stringify({ user_id: userId, data: hooks.getSettings(), updated_at: snapshot.s }), body: JSON.stringify({ user_id: userId, data: hooks.getSettings(), updated_at: snapshot.s }),
}) })
if (!res.ok) throw new Error(t('sync.err.push', { status: res.status })) if (!res.ok) throw new PushError(res.status)
meta.settingsAt = snapshot.s meta.settingsAt = maxIso(meta.settingsAt, snapshot.s)
// On ne retire que ce qui n'a pas été re-modifié pendant l'envoi
done(['s'], snapshot)
} }
// On ne retire que ce qui n'a pas été re-modifié pendant l'envoi
for (const k of keys) if (meta.outbox[k] === snapshot[k]) delete meta.outbox[k]
saveMeta()
} }
// ─── Réception ─── // ─── Réception ───
@@ -222,39 +326,61 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
return { rows, cursor: last } return { rows, cursor: last }
} }
/**
* Curseur après une réception : les lignes ignorées car une modification locale était en attente sont
* relues la prochaine fois (si l'envoi local est refusé par le serveur — version distante plus récente —,
* c'est elle qu'il faudra récupérer).
*/
const heldCursor = (cursor: string | undefined, held: string[]) => {
const first = held.length ? held.reduce((a, b) => (a < b ? a : b)) : undefined
return first && (!cursor || first < cursor) ? first : undefined
}
async function pullItems() { async function pullItems() {
const { rows, cursor } = await fetchChanges('items', meta.itemsCursor) const { rows, cursor } = await fetchChanges('items', meta.itemsCursor)
const toPut: MediaItem[] = [] if (!alive()) return
const toRemove: string[] = [] const remote = new Map<string, Row>()
for (const r of rows) { for (const r of rows) remote.set(r.id, r) // la plus récente (ordre du serveur) l'emporte
if (meta.outbox[`i:${r.id}`]) continue // modification locale en attente : elle passera en priorité const held: string[] = []
const local = await mediaDB.get(r.id) // Décision prise dans la transaction d'écriture (une seule pour toutes les fiches) : la boîte d'envoi
if (r.deleted) { // et la version locale sont relues au dernier moment, une modification faite pendant la réception gagne.
if (local) toRemove.push(r.id) const decide = (id: string, local: MediaItem | undefined): RemoteDecision => {
continue const r = remote.get(id)!
if (!alive()) return null
if (meta.outbox[`i:${id}`]) {
held.push(r.server_updated_at) // modification locale en attente : elle passera en priorité
return null
} }
if (r.deleted) return local ? 'remove' : null
const item = normalizeItem(r.data) const item = normalizeItem(r.data)
if (!item || item.id !== r.id) continue if (!item || item.id !== id) return null
if (local && local.updatedAt > item.updatedAt) continue if (local && local.updatedAt > item.updatedAt) return null
// Même version : on garde l'affiche locale si le serveur ne l'a pas (fiche allégée à l'envoi) // Même version : on garde l'affiche locale si le serveur ne l'a pas (fiche allégée à l'envoi)
if (local && local.updatedAt === item.updatedAt && !item.poster && local.poster) item.poster = local.poster if (local && local.updatedAt === item.updatedAt && !item.poster && local.poster) item.poster = local.poster
if (local && JSON.stringify(local) === JSON.stringify(item)) continue if (local && JSON.stringify(local) === JSON.stringify(item)) return null
toPut.push(item) return { put: item }
} }
await mediaDB.putMany(toPut, { silent: true }) const change = await mediaDB.mergeRemote([...remote.keys()], decide)
await mediaDB.removeMany(toRemove, { silent: true }) if (!alive()) return
meta.itemsCursor = safeIso(cursor) meta.itemsCursor = safeIso(cursor)
saveMeta() const back = heldCursor(meta.itemsCursor, held)
if (toPut.length || toRemove.length) hooks.itemsChanged() if (back) meta.itemsCursor = back
saveMeta(back ? { itemsCursor: back } : undefined)
if (change.put.length || change.removed.length) hooks.itemsChanged()
} }
async function pullLists() { async function pullLists() {
const { rows, cursor } = await fetchChanges('lists', meta.listsCursor) const { rows, cursor } = await fetchChanges('lists', meta.listsCursor)
if (!alive()) return
const held: string[] = []
if (rows.length) { if (rows.length) {
const map = new Map(hooks.getLists().map((l) => [l.id, l])) const map = new Map(hooks.getLists().map((l) => [l.id, l]))
let changed = false let changed = false
for (const r of rows) { for (const r of rows) {
if (meta.outbox[`l:${r.id}`]) continue if (meta.outbox[`l:${r.id}`]) {
held.push(r.server_updated_at)
continue
}
if (r.deleted) { if (r.deleted) {
changed = map.delete(r.id) || changed changed = map.delete(r.id) || changed
continue continue
@@ -268,7 +394,9 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
if (changed) hooks.applyLists([...map.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt))) if (changed) hooks.applyLists([...map.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt)))
} }
meta.listsCursor = safeIso(cursor) meta.listsCursor = safeIso(cursor)
saveMeta() const back = heldCursor(meta.listsCursor, held)
if (back) meta.listsCursor = back
saveMeta(back ? { listsCursor: back } : undefined)
} }
async function pullSettings() { async function pullSettings() {
@@ -279,6 +407,8 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
const at = safeIso(row?.updated_at) const at = safeIso(row?.updated_at)
if (!row || !at || (meta.settingsAt && at <= meta.settingsAt)) return if (!row || !at || (meta.settingsAt && at <= meta.settingsAt)) return
const s = normalizeSettings(row.data) const s = normalizeSettings(row.data)
if (!alive()) return
// Les appareils à jour envoient toujours la liste des mois masqués ([] = aucun) ; absente = ancienne version, on n'y touche pas
if (s) hooks.applySettings(s) if (s) hooks.applySettings(s)
meta.settingsAt = at meta.settingsAt = at
saveMeta() saveMeta()
@@ -306,12 +436,12 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
} catch (e) { } catch (e) {
pushError = e pushError = e
} }
// Déconnexion pendant la synchro : on n'écrit plus rien dans la base de cet utilisateur // Déconnexion (ou changement de compte) pendant la synchro : on n'écrit plus rien sur l'appareil
if (stopped) return if (!alive()) return
await pullItems() await pullItems()
if (stopped) return if (!alive()) return
await pullLists() await pullLists()
if (stopped) return if (!alive()) return
await pullSettings() await pullSettings()
if (pushError) throw pushError if (pushError) throw pushError
meta.lastSyncAt = new Date().toISOString() meta.lastSyncAt = new Date().toISOString()
+197 -31
View File
@@ -1,5 +1,5 @@
import type { MediaItem } from '../types' import type { MediaItem } from '../types'
import { dbNameFor, getScope } from './scope' import { dbNameFor, getScope, scopeEpoch } from './scope'
/** /**
* Mini-wrapper IndexedDB sans dépendance. * Mini-wrapper IndexedDB sans dépendance.
@@ -10,6 +10,34 @@ const STORE = 'media'
let dbPromise: Promise<IDBDatabase> | null = null let dbPromise: Promise<IDBDatabase> | null = null
let dbName = '' let dbName = ''
/** Base ouverte en cache (pour l'oublier si le navigateur la ferme) */
let opened: IDBDatabase | null = null
/** Bases supprimées → « époque » de l'espace et heure de la suppression (voir isWiped). */
const wiped = new Map<string, { epoch: number; at: number }>()
/** Une écriture tardive arrive dans les secondes qui suivent ; au-delà (reconnexion…), la base peut renaître. */
const WIPE_GUARD_MS = 15_000
const markWiped = (name: string) => wiped.set(name, { epoch: scopeEpoch(), at: Date.now() })
/**
* Une écriture tardive (synchro, onglet resté ouvert…) juste après une déconnexion ne doit pas
* recréer la base supprimée : tant que l'espace n'a pas changé depuis la suppression, elle reste fermée.
*/
function isWiped(name: string): boolean {
const w = wiped.get(name)
if (!w) return false
if (w.epoch === scopeEpoch() && Date.now() - w.at < WIPE_GUARD_MS) return true
wiped.delete(name) // l'espace a changé depuis, ou la suppression est ancienne : la base peut renaître normalement
return false
}
/** Oublie la base en cache si c'est celle-ci (fermée par le navigateur ou par un autre onglet). */
function forget(db: IDBDatabase) {
if (opened !== db) return
opened = null
dbPromise = null
dbName = ''
}
function open(name: string): Promise<IDBDatabase> { function open(name: string): Promise<IDBDatabase> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -23,7 +51,16 @@ function open(name: string): Promise<IDBDatabase> {
store.createIndex('updatedAt', 'updatedAt') store.createIndex('updatedAt', 'updatedAt')
} }
} }
req.onsuccess = () => resolve(req.result) req.onsuccess = () => {
const db = req.result
// Suppression / mise à jour demandée ailleurs (autre onglet) : on libère la base pour ne pas la bloquer
db.onversionchange = () => {
db.close()
forget(db)
}
db.onclose = () => forget(db)
resolve(db)
}
req.onerror = () => reject(req.error) req.onerror = () => reject(req.error)
}) })
} }
@@ -33,10 +70,17 @@ function openDB(): Promise<IDBDatabase> {
if (!dbPromise || dbName !== name) { if (!dbPromise || dbName !== name) {
closeDB() closeDB()
dbName = name dbName = name
dbPromise = open(name).catch((e) => { const p: Promise<IDBDatabase> = open(name).then(
dbPromise = null (db) => {
throw e if (dbPromise === p) opened = db
}) return db
},
(e) => {
if (dbPromise === p) dbPromise = null
throw e
},
)
dbPromise = p
} }
return dbPromise return dbPromise
} }
@@ -46,13 +90,24 @@ export function closeDB() {
const p = dbPromise const p = dbPromise
dbPromise = null dbPromise = null
dbName = '' dbName = ''
opened = null
p?.then((db) => db.close()).catch(() => {}) p?.then((db) => db.close()).catch(() => {})
} }
async function run<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T> | void, db?: IDBDatabase): Promise<T> { async function run<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T> | void, db?: IDBDatabase, retried = false): Promise<T> {
const database = db ?? (await openDB()) const database = db ?? (await openDB())
let tx: IDBTransaction
try {
tx = database.transaction(STORE, mode)
} catch (e) {
// Base fermée entre-temps (navigateur, autre onglet) : on la rouvre une fois
if (!db && !retried && (e as DOMException)?.name === 'InvalidStateError') {
forget(database)
return run(mode, fn, undefined, true)
}
throw e
}
return new Promise<T>((resolve, reject) => { return new Promise<T>((resolve, reject) => {
const tx = database.transaction(STORE, mode)
const req = fn(tx.objectStore(STORE)) const req = fn(tx.objectStore(STORE))
tx.oncomplete = () => resolve(req ? req.result : (undefined as T)) tx.oncomplete = () => resolve(req ? req.result : (undefined as T))
tx.onerror = () => reject(tx.error) tx.onerror = () => reject(tx.error)
@@ -70,49 +125,158 @@ export function onMediaChange(fn: (c: MediaChange) => void): () => void {
listeners.add(fn) listeners.add(fn)
return () => listeners.delete(fn) return () => listeners.delete(fn)
} }
const notify = (c: MediaChange, silent?: boolean) => { const notify = (c: MediaChange) => {
if (!silent) for (const fn of listeners) fn(c) for (const fn of listeners) fn(c)
} }
interface Opts { // ─── Autres onglets du même appareil ───
/** Écriture venant de la synchro : ne pas la renvoyer au serveur */ // Chaque écriture prévient les autres onglets ouverts sur la même base, qui relisent alors leurs fiches.
silent?: boolean let channel: BroadcastChannel | null | undefined
function getChannel(): BroadcastChannel | null {
if (channel === undefined) {
try {
channel = typeof BroadcastChannel === 'undefined' ? null : new BroadcastChannel('azuucine-db')
} catch {
channel = null
}
}
return channel
} }
const broadcast = (name: string, wipe = false) => {
try {
getChannel()?.postMessage({ db: name, wipe })
} catch {
/* ignore */
}
}
/** Écriture faite par un autre onglet dans la base de l'espace actif. */
export function onExternalChange(fn: () => void): () => void {
const ch = getChannel()
if (!ch) return () => {}
const handler = (e: MessageEvent) => {
const data = e.data as { db?: unknown; wipe?: unknown } | null
if (!data || data.db !== dbNameFor(getScope())) return
// Base supprimée par un autre onglet (déconnexion) : cet onglet ne doit pas la recréer non plus
if (data.wipe === true) {
markWiped(data.db)
if (data.db === dbName) closeDB()
}
fn()
}
ch.addEventListener('message', handler)
return () => ch.removeEventListener('message', handler)
}
/** Compteur d'écritures dans cet onglet (début et fin) : une lecture qui l'a vu changer peut être périmée. */
let writes = 0
export const writeVersion = () => writes
/** Écriture dans la base active, sauf si elle vient d'être supprimée (no-op). */
async function write(fn: (store: IDBObjectStore) => IDBRequest | void, changed: () => boolean = () => true): Promise<boolean> {
const name = dbNameFor(getScope())
if (isWiped(name)) return false
writes++
try {
await run('readwrite', fn)
} finally {
writes++ // une lecture commencée pendant l'écriture est aussi périmée
}
// Rien n'a changé (réception sans nouveauté) : inutile de faire recharger les autres onglets
if (changed()) broadcast(name)
return true
}
/** Lecture : une base supprimée reste vide (on ne la recrée pas en l'ouvrant). */
const read = <T,>(fn: (store: IDBObjectStore) => IDBRequest<T>, empty: T): Promise<T> =>
isWiped(dbNameFor(getScope())) ? Promise.resolve(empty) : run<T>('readonly', fn)
/** Décision pour une fiche reçue du serveur, prise dans la transaction d'écriture (voir mergeRemote). */
export type RemoteDecision = { put: MediaItem } | 'remove' | null
export const mediaDB = { export const mediaDB = {
getAll: () => run<MediaItem[]>('readonly', (s) => s.getAll() as IDBRequest<MediaItem[]>), getAll: () => read<MediaItem[]>((s) => s.getAll() as IDBRequest<MediaItem[]>, []),
get: (id: string) => run<MediaItem | undefined>('readonly', (s) => s.get(id) as IDBRequest<MediaItem | undefined>), get: (id: string) => read<MediaItem | undefined>((s) => s.get(id) as IDBRequest<MediaItem | undefined>, undefined),
put: async (item: MediaItem, opts: Opts = {}) => { put: async (item: MediaItem) => {
await run('readwrite', (s) => void s.put(item)) if (await write((s) => void s.put(item))) notify({ put: [item], removed: [] })
notify({ put: [item], removed: [] }, opts.silent)
}, },
putMany: async (items: MediaItem[], opts: Opts = {}) => { putMany: async (items: MediaItem[]) => {
if (!items.length) return if (!items.length) return
await run('readwrite', (s) => { const ok = await write((s) => {
for (const item of items) s.put(item) for (const item of items) s.put(item)
}) })
notify({ put: items, removed: [] }, opts.silent) if (ok) notify({ put: items, removed: [] })
}, },
remove: async (id: string, opts: Opts = {}) => { remove: async (id: string) => {
await run('readwrite', (s) => void s.delete(id)) if (await write((s) => void s.delete(id))) notify({ put: [], removed: [id] })
notify({ put: [], removed: [id] }, opts.silent)
}, },
removeMany: async (ids: string[], opts: Opts = {}) => { removeMany: async (ids: string[]) => {
if (!ids.length) return if (!ids.length) return
await run('readwrite', (s) => { const ok = await write((s) => {
for (const id of ids) s.delete(id) for (const id of ids) s.delete(id)
}) })
notify({ put: [], removed: ids }, opts.silent) if (ok) notify({ put: [], removed: ids })
}, },
clear: async (opts: Opts = {}) => { /** Vide la base (clés lues et effacées dans la même transaction). */
const ids = await run<IDBValidKey[]>('readonly', (s) => s.getAllKeys()) clear: async () => {
await run('readwrite', (s) => void s.clear()) let ids: IDBValidKey[] = []
notify({ put: [], removed: ids.map(String) }, opts.silent) const ok = await write((s) => {
const req = s.getAllKeys()
req.onsuccess = () => {
ids = req.result
s.clear()
}
})
if (ok) notify({ put: [], removed: ids.map(String) })
},
/**
* Remplace tout le contenu en une seule transaction : si une écriture échoue, rien n'est effacé.
* La synchro n'est prévenue qu'une fois la transaction terminée.
*/
replaceAll: async (items: MediaItem[]) => {
let ids: IDBValidKey[] = []
const ok = await write((s) => {
const req = s.getAllKeys()
req.onsuccess = () => {
ids = req.result
s.clear()
for (const item of items) s.put(item)
}
})
if (!ok) return
const kept = new Set(items.map((i) => i.id))
notify({ put: items, removed: ids.map(String).filter((id) => !kept.has(id)) })
},
/**
* Fusion de fiches reçues du serveur, en une seule transaction : chaque fiche locale est lue puis
* `decide` choisit (au moment de l'écriture, donc après toute modification locale déjà enregistrée)
* de l'écraser, de la supprimer ou de la garder. Écriture silencieuse (rien à renvoyer au serveur).
*/
mergeRemote: async (ids: string[], decide: (id: string, local: MediaItem | undefined) => RemoteDecision): Promise<MediaChange> => {
const change: MediaChange = { put: [], removed: [] }
if (!ids.length) return change
await write((s) => {
for (const id of ids) {
const req = s.get(id) as IDBRequest<MediaItem | undefined>
req.onsuccess = () => {
const d = decide(id, req.result)
if (d === 'remove') {
s.delete(id)
change.removed.push(id)
} else if (d) {
s.put(d.put)
change.put.push(d.put)
}
}
}
}, () => change.put.length + change.removed.length > 0)
return change
}, },
} }
/** Lit toutes les fiches d'une autre base (ex. les données « sans compte » de cet appareil). */ /** Lit toutes les fiches d'une autre base (ex. les données « sans compte » de cet appareil). */
export async function readOtherDatabase(name: string): Promise<MediaItem[]> { export async function readOtherDatabase(name: string): Promise<MediaItem[]> {
if (isWiped(name)) return []
const exists = (await indexedDB.databases?.())?.some((d) => d.name === name) const exists = (await indexedDB.databases?.())?.some((d) => d.name === name)
if (exists === false) return [] if (exists === false) return []
const db = await open(name) const db = await open(name)
@@ -125,7 +289,9 @@ export async function readOtherDatabase(name: string): Promise<MediaItem[]> {
/** Supprime complètement une base de l'appareil. */ /** Supprime complètement une base de l'appareil. */
export function deleteDatabase(name: string): Promise<void> { export function deleteDatabase(name: string): Promise<void> {
markWiped(name)
if (name === dbName) closeDB() if (name === dbName) closeDB()
broadcast(name, true)
return new Promise((resolve) => { return new Promise((resolve) => {
const req = indexedDB.deleteDatabase(name) const req = indexedDB.deleteDatabase(name)
req.onsuccess = req.onerror = req.onblocked = () => resolve() req.onsuccess = req.onerror = req.onblocked = () => resolve()
+2
View File
@@ -9,6 +9,8 @@ const stack: { current: () => void }[] = []
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
window.addEventListener('keydown', (e) => { window.addEventListener('keydown', (e) => {
if (e.key !== 'Escape' || !stack.length) return if (e.key !== 'Escape' || !stack.length) return
// Échap pendant une saisie composée (IME : japonais, chinois…) annule la composition, pas la fenêtre
if (e.isComposing || e.keyCode === 229) return
e.preventDefault() e.preventDefault()
stack[stack.length - 1].current() stack[stack.length - 1].current()
}) })
+9 -7
View File
@@ -63,15 +63,17 @@ export function seasonPosition(item: Pick<MediaItem, 'episodesWatched' | 'season
const start = episodesBeforeSeason(seasons, chosen) const start = episodesBeforeSeason(seasons, chosen)
if (item.episodesWatched === start) return { season: chosen, episode: 0, size: seasons[chosen - 1], before: start } if (item.episodesWatched === start) return { season: chosen, episode: 0, size: seasons[chosen - 1], before: start }
} }
let before = 0 const at = (k: number, before: number): SeasonPosition => {
for (let k = 0; k < seasons.length; k++) {
const size = seasons[k] const size = seasons[k]
if (item.episodesWatched <= before + size || k === seasons.length - 1) { return { season: k + 1, episode: Math.min(size, Math.max(0, item.episodesWatched - before)), size, before }
return { season: k + 1, episode: Math.min(size, Math.max(0, item.episodesWatched - before)), size, before }
}
before += size
} }
return undefined let before = 0
for (let k = 0; k < seasons.length - 1; k++) {
if (item.episodesWatched <= before + seasons[k]) return at(k, before)
before += seasons[k]
}
// Au-delà : dernière saison
return at(seasons.length - 1, before)
} }
/** Nombre d'épisodes vus au début de la saison n (1 = première). */ /** Nombre d'épisodes vus au début de la saison n (1 = première). */
+10 -2
View File
@@ -93,6 +93,8 @@ export async function loadMonth(
const cache = load() const cache = load()
const entry = (cache[key] ??= {}) const entry = (cache[key] ??= {})
const failed: ReleaseCategory[] = [] const failed: ReleaseCategory[] = []
// Catégories récupérées pendant cet appel (fusionnées au cache le plus récent à l'enregistrement)
const fetched: Partial<Record<ReleaseCategory, { at: string; list: GlobalRelease[] }>> = {}
if (isBrowsableMonth(key) && navigator.onLine) { if (isBrowsableMonth(key) && navigator.onLine) {
const ttl = monthOffset(key) < 0 ? PAST_FRESH_MS : FRESH_MS const ttl = monthOffset(key) < 0 ? PAST_FRESH_MS : FRESH_MS
const from = `${key}-01` const from = `${key}-01`
@@ -114,7 +116,7 @@ export async function loadMonth(
job = created job = created
} }
try { try {
entry[c] = { at: new Date().toISOString(), list: await job } entry[c] = fetched[c] = { at: new Date().toISOString(), list: await job }
} catch { } catch {
failed.push(c) failed.push(c)
} }
@@ -126,7 +128,13 @@ export async function loadMonth(
for (const c of stale.filter((x) => x !== 'anime')) await fetchCat(c) for (const c of stale.filter((x) => x !== 'anime')) await fetchCat(c)
})(), })(),
]) ])
if (stale.length) save(cache) // Deux chargements en parallèle (deux mois, double rendu…) : chacun relit le cache juste avant
// d'enregistrer, sinon le dernier à finir effaçait ce que l'autre venait d'ajouter
if (Object.keys(fetched).length) {
const latest = load()
latest[key] = { ...latest[key], ...fetched }
save(latest)
}
} }
return { releases: cats.flatMap((c) => entry[c]?.list ?? []), failed } return { releases: cats.flatMap((c) => entry[c]?.list ?? []), failed }
} }
+8 -2
View File
@@ -50,9 +50,15 @@ export async function remotePosterToLocal(url: string): Promise<string | undefin
const safe = safePosterUrl(url) const safe = safePosterUrl(url)
if (!safe || safe.startsWith('data:')) return safe if (!safe || safe.startsWith('data:')) return safe
try { try {
const res = await fetch(safe, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer' }) const res = await fetch(safe, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(15_000) })
// Réponse en erreur ou annoncée trop grosse : on ne lit pas le corps
const announced = Number(res.headers.get('Content-Length'))
if (!res.ok || (Number.isFinite(announced) && announced > LIMITS.imageFileBytes)) {
await res.body?.cancel().catch(() => {})
return safe
}
const blob = await res.blob() const blob = await res.blob()
if (!res.ok || !blob.type.startsWith('image/') || blob.size > LIMITS.imageFileBytes) return safe if (!blob.type.startsWith('image/') || blob.size > LIMITS.imageFileBytes) return safe
return await blobToPosterDataURL(blob) return await blobToPosterDataURL(blob)
} catch { } catch {
return safe return safe
+100 -23
View File
@@ -1,5 +1,5 @@
import { t } from '../../i18n' import { t } from '../../i18n'
import { ANILIST, ANILIST_FIELDS, aniToResult, CLOUD_TMDB, getTmdbDetails, tmdbFindExternal, tmdbImportSearch, type AniMedia, type SearchResult } from '../catalogApi' import { ANILIST, ANILIST_FIELDS, aniToResult, CLOUD_TMDB, getTmdbDetails, sanitizeMeta, tmdbFindExternal, tmdbImportSearch, type AniMedia, type SearchResult } from '../catalogApi'
import type { MediaInput } from '../../types' import type { MediaInput } from '../../types'
import { anilistEntries, titleKey, type AniListEntry, type ImportEntry } from './sources' import { anilistEntries, titleKey, type AniListEntry, type ImportEntry } from './sources'
@@ -35,17 +35,59 @@ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
// ─── Cache des correspondances (données publiques uniquement) ─── // ─── Cache des correspondances (données publiques uniquement) ───
const CACHE_KEY = 'azuucine:import-match' const CACHE_KEY = 'azuucine:import-match'
const CACHE_MAX = 4000 const CACHE_MAX = 1500
let cache: Record<string, SearchResult> | null = null /** Taille max du cache une fois sérialisé (caractères) : il ne doit pas remplir le stockage de l'appli. */
const CACHE_BUDGET = 1_000_000
/** Une correspondance plus vieille que 30 jours est oubliée (titres, affiches et saisons évoluent). */
const CACHE_TTL = 30 * 24 * 3600_000
function loadCache(): Record<string, SearchResult> { /** Forme compacte en cache : juste de quoi reconstruire la correspondance (pas de vignette, pas de doublons). */
interface CachedMatch {
id: string
t: string
o?: string
y?: number
p?: string
g: SearchResult['typeGuess']
m?: Partial<MediaInput>
/** Titres alternatifs (rapprochement des franchises à la fusion) */
a?: string[]
at: number
}
let cache: Record<string, CachedMatch> | null = null
function compact(r: SearchResult, at = Date.now()): CachedMatch {
// Ces champs sont déjà dans le résultat : inutile de les garder deux fois
const { title: _t, originalTitle: _o, year: _y, externalId: _e, poster: _p, ...rest } = r.prefill ?? {}
void [_t, _o, _y, _e, _p]
return { id: r.externalId, t: r.title, o: r.originalTitle, y: r.year, p: r.posterUrl, g: r.typeGuess, m: r.prefill ? rest : undefined, a: r.altTitles?.length ? r.altTitles : undefined, at }
}
function expand(c: CachedMatch): SearchResult {
const prefill = c.m ? sanitizeMeta({ ...c.m, title: c.t, originalTitle: c.o, year: c.y, externalId: c.id, poster: c.p }) : undefined
return { source: 'tmdb', externalId: c.id, title: c.t, originalTitle: c.o, year: c.y, posterUrl: c.p, kindLabel: '', typeGuess: c.g, altTitles: Array.isArray(c.a) ? c.a.filter((x): x is string => typeof x === 'string').slice(0, 3) : undefined, prefill }
}
const isCached = (v: unknown): v is CachedMatch => {
const c = v as CachedMatch
return !!c && typeof c === 'object' && typeof c.id === 'string' && c.id.startsWith('tmdb:') && typeof c.t === 'string' && typeof c.at === 'number' && typeof c.g === 'string'
}
function loadCache(): Record<string, CachedMatch> {
if (cache) return cache if (cache) return cache
cache = Object.create(null) as Record<string, SearchResult> cache = Object.create(null) as Record<string, CachedMatch>
try { try {
const raw = JSON.parse(localStorage.getItem(CACHE_KEY) ?? '{}') as unknown const raw = JSON.parse(localStorage.getItem(CACHE_KEY) ?? '{}') as unknown
if (raw && typeof raw === 'object' && !Array.isArray(raw)) { if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
const now = Date.now()
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) { for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
if (v && typeof v === 'object' && typeof (v as SearchResult).externalId === 'string') cache[k] = v as SearchResult if (isCached(v)) {
if (now - v.at < CACHE_TTL) cache[k] = v
} else if (v && typeof v === 'object' && typeof (v as SearchResult).externalId === 'string' && (v as SearchResult).externalId.startsWith('tmdb:') && typeof (v as SearchResult).title === 'string') {
// Ancien format (résultat complet) : converti, et compté comme récent
cache[k] = compact(v as SearchResult, now)
}
} }
} }
} catch { } catch {
@@ -57,9 +99,20 @@ function loadCache(): Record<string, SearchResult> {
function saveCache() { function saveCache() {
if (!cache) return if (!cache) return
try { try {
const keys = Object.keys(cache) const now = Date.now()
if (keys.length > CACHE_MAX) for (const k of keys.slice(0, keys.length - CACHE_MAX)) delete cache[k] for (const [k, v] of Object.entries(cache)) if (now - v.at >= CACHE_TTL) delete cache[k]
localStorage.setItem(CACHE_KEY, JSON.stringify(cache)) // Les plus anciennes d'abord : ce sont elles qu'on retire quand c'est trop gros
const keys = Object.keys(cache).sort((a, b) => cache![a].at - cache![b].at)
let drop = Math.max(0, keys.length - CACHE_MAX)
for (;;) {
for (const k of keys.splice(0, drop)) delete cache[k]
const json = JSON.stringify(cache)
if (json.length <= CACHE_BUDGET || !keys.length) {
localStorage.setItem(CACHE_KEY, json)
return
}
drop = Math.max(1, Math.ceil(keys.length / 5))
}
} catch { } catch {
/* stockage plein ou bloqué : tant pis pour le cache */ /* stockage plein ou bloqué : tant pis pour le cache */
} }
@@ -94,10 +147,17 @@ const isRateError = (e: unknown) => {
/** Exécute les tâches avec au plus `size` en parallèle. */ /** Exécute les tâches avec au plus `size` en parallèle. */
async function pool<T>(list: T[], size: number, token: CancelToken, fn: (x: T) => Promise<void>) { async function pool<T>(list: T[], size: number, token: CancelToken, fn: (x: T) => Promise<void>) {
let i = 0 let i = 0
// Un travailleur en échec (ex. hors ligne) arrête les autres : inutile de continuer à vider la liste
let failed = false
const worker = async () => { const worker = async () => {
while (i < list.length) { while (i < list.length) {
if (token.cancelled) throw new CancelledError() if (token.cancelled || failed) throw new CancelledError()
await fn(list[i++]) try {
await fn(list[i++])
} catch (e) {
failed = true
throw e
}
} }
} }
await Promise.all(Array.from({ length: Math.min(size, list.length) }, worker)) await Promise.all(Array.from({ length: Math.min(size, list.length) }, worker))
@@ -117,7 +177,8 @@ export function bestTmdbMatch(results: SearchResult[], entry: Pick<ImportEntry,
const close = cands.filter((r) => r.year != null && Math.abs(r.year - y) <= 1) const close = cands.filter((r) => r.year != null && Math.abs(r.year - y) <= 1)
return exact.find(same) ?? close.find(same) ?? exact[0] ?? close[0] return exact.find(same) ?? close.find(same) ?? exact[0] ?? close[0]
} }
return cands.find(same) ?? cands[0] // Sans année, le premier résultat venu peut être n'importe quoi : on exige le même titre
return cands.find(same)
} }
/** Requête TMDB avec reprise automatique quand la limite de débit est atteinte. */ /** Requête TMDB avec reprise automatique quand la limite de débit est atteinte. */
@@ -150,6 +211,7 @@ async function anilistPost<T>(query: string, variables: Record<string, unknown>)
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
credentials: 'omit', credentials: 'omit',
body: JSON.stringify({ query, variables }), body: JSON.stringify({ query, variables }),
signal: AbortSignal.timeout(15_000),
}) })
if (res.status === 429) throw new Error('rate') if (res.status === 429) throw new Error('rate')
const json = (await res.json().catch(() => ({}))) as { data?: T; errors?: { message?: string; status?: number }[] } const json = (await res.json().catch(() => ({}))) as { data?: T; errors?: { message?: string; status?: number }[] }
@@ -267,26 +329,38 @@ export async function resolveEntries(entries: ImportEntry[], opts: ResolveOption
const c = loadCache() const c = loadCache()
let sinceSave = 0 let sinceSave = 0
const lang = document.documentElement.lang || 'x' const lang = document.documentElement.lang || 'x'
// Jeton interne : annulé par l'utilisateur, ou dès qu'un travailleur échoue (hors ligne) pour que les autres
// arrêtent d'attendre / de réessayer. Le jeton de l'appelant n'est pas modifié : l'erreur reste affichée.
let stopped = false
const tk: CancelToken = {
get cancelled() {
return token.cancelled || stopped
},
set cancelled(v: boolean) {
token.cancelled = v
},
}
await pool(viaTmdb, 4, token, async (e) => { await pool(viaTmdb, 4, tk, async (e) => {
try { try {
const cacheKey = e.tvdbId ? `tvdb:${e.tvdbId}:${lang}` : e.imdbId ? `imdb:${e.imdbId}:${lang}` : `${e.kind}:${titleKey(e.title)}|${e.year ?? ''}:${lang}` const cacheKey = e.tvdbId ? `tvdb:${e.tvdbId}:${lang}` : e.imdbId ? `imdb:${e.imdbId}:${lang}` : `${e.kind}:${titleKey(e.title)}|${e.year ?? ''}:${lang}`
let result: SearchResult | undefined = c[cacheKey] const hit = c[cacheKey]
let result: SearchResult | undefined = hit ? expand(hit) : undefined
if (!result && (e.tvdbId || e.imdbId)) { if (!result && (e.tvdbId || e.imdbId)) {
await rate(token) await rate(tk)
result = await withRetry(() => tmdbFindExternal(e.tvdbId ?? e.imdbId!, e.tvdbId ? 'tvdb_id' : 'imdb_id', key), token, onWait).catch((err) => { result = await withRetry(() => tmdbFindExternal(e.tvdbId ?? e.imdbId!, e.tvdbId ? 'tvdb_id' : 'imdb_id', key), tk, onWait).catch((err) => {
if (err instanceof CancelledError) throw err if (err instanceof CancelledError) throw err
return undefined // ancien serveur sans /find, ou identifiant inconnu : recherche par titre return undefined // ancien serveur sans /find, ou identifiant inconnu : recherche par titre
}) })
} }
if (!result && !e.title.startsWith('#')) { if (!result && !e.title.startsWith('#')) {
await rate(token) await rate(tk)
const list = await withRetry(() => tmdbImportSearch(e.title, key), token, onWait) const list = await withRetry(() => tmdbImportSearch(e.title, key), tk, onWait)
result = bestTmdbMatch(list, e) result = bestTmdbMatch(list, e)
} }
if (!result) return if (!result) return
if (!c[cacheKey]) { if (!hit) {
c[cacheKey] = result c[cacheKey] = compact(result)
if (++sinceSave >= 25) { if (++sinceSave >= 25) {
sinceSave = 0 sinceSave = 0
saveCache() saveCache()
@@ -295,8 +369,8 @@ export async function resolveEntries(entries: ImportEntry[], opts: ResolveOption
let meta: Partial<MediaInput> = { ...result.prefill, poster: result.posterUrl } let meta: Partial<MediaInput> = { ...result.prefill, poster: result.posterUrl }
// Séries : saisons et nombre d'épisodes, pour reprendre la progression // Séries : saisons et nombre d'épisodes, pour reprendre la progression
if (result.externalId.startsWith('tmdb:tv:')) { if (result.externalId.startsWith('tmdb:tv:')) {
await rate(token) await rate(tk)
const details = await withRetry(() => getTmdbDetails(result!, key), token, onWait).catch((err) => { const details = await withRetry(() => getTmdbDetails(result!, key), tk, onWait).catch((err) => {
if (err instanceof CancelledError) throw err if (err instanceof CancelledError) throw err
return undefined return undefined
}) })
@@ -305,7 +379,10 @@ export async function resolveEntries(entries: ImportEntry[], opts: ResolveOption
found.set(e.key, { result, meta }) found.set(e.key, { result, meta })
} catch (err) { } catch (err) {
if (err instanceof CancelledError) throw err if (err instanceof CancelledError) throw err
if (!navigator.onLine) throw new Error(t('search.offline')) if (!navigator.onLine) {
stopped = true
throw new Error(t('search.offline'))
}
// Erreur ponctuelle sur un titre : il sera compté comme « non trouvé » // Erreur ponctuelle sur un titre : il sera compté comme « non trouvé »
} finally { } finally {
step() step()
+13 -6
View File
@@ -2,6 +2,8 @@ import type { MediaItem, MediaType, TopCategory, TopEntry, WatchStatus } from '.
import { ALL_TOP_CATEGORIES } from './constants' import { ALL_TOP_CATEGORIES } from './constants'
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, safeCountries, safeDay, safeIso, safeStringList } from './security' import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, safeCountries, safeDay, safeIso, safeStringList } from './security'
import { splitGenres } from './catalogApi' import { splitGenres } from './catalogApi'
// Import circulaire sans risque : normalizeItem n'est appelée qu'à l'exécution, jamais au chargement du module
import { normalizeItem } from './backup'
import { normalizeText } from './utils' import { normalizeText } from './utils'
/** /**
@@ -99,7 +101,8 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
// Épisodes vus par fiche // Épisodes vus par fiche
const eps = new Map<number, LegacyEpisode[]>() const eps = new Map<number, LegacyEpisode[]>()
for (const e of data.episodes ?? []) { // Fichier non fiable : chaque liste peut manquer ou ne pas être un tableau
for (const e of Array.isArray(data.episodes) ? data.episodes : []) {
if (!e || !(e.watched === 1 || e.watched === true)) continue if (!e || !(e.watched === 1 || e.watched === true)) continue
const list = eps.get(e.item_id) ?? [] const list = eps.get(e.item_id) ?? []
list.push(e) list.push(e)
@@ -113,7 +116,8 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
.map((t) => [t.id, cleanText(t.name, LIMITS.shortText)] as const), .map((t) => [t.id, cleanText(t.name, LIMITS.shortText)] as const),
) )
const itemTags = new Map<number, string[]>() const itemTags = new Map<number, string[]>()
for (const it of data.item_tags ?? []) { for (const it of Array.isArray(data.item_tags) ? data.item_tags : []) {
if (!it || typeof it !== 'object') continue
const name = tagNames.get(it.tag_id) const name = tagNames.get(it.tag_id)
if (!name) continue if (!name) continue
itemTags.set(it.item_id, [...(itemTags.get(it.item_id) ?? []), name]) itemTags.set(it.item_id, [...(itemTags.get(it.item_id) ?? []), name])
@@ -121,8 +125,8 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
// Tops 5 par catégorie // Tops 5 par catégorie
const tops = new Map<number, TopEntry>() const tops = new Map<number, TopEntry>()
for (const t of data.top5 ?? []) { for (const t of Array.isArray(data.top5) ? data.top5 : []) {
if (ALL_TOP_CATEGORIES.includes(t.category as TopCategory) && t.position >= 1 && t.position <= 5) { if (t && typeof t === 'object' && ALL_TOP_CATEGORIES.includes(t.category as TopCategory) && t.position >= 1 && t.position <= 5) {
tops.set(t.item_id, { category: t.category as TopCategory, rank: t.position }) tops.set(t.item_id, { category: t.category as TopCategory, rank: t.position })
} }
} }
@@ -173,7 +177,8 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
const note = typeof r.note === 'number' && Number.isFinite(r.note) && r.note > 0 ? Math.min(10, Math.round(r.note * 2 * 2) / 2) : undefined const note = typeof r.note === 'number' && Number.isFinite(r.note) && r.note > 0 ? Math.min(10, Math.round(r.note * 2 * 2) / 2) : undefined
const created = toISO(r.date_added) ?? now const created = toISO(r.date_added) ?? now
items.push({ // Même validation que les sauvegardes Kino (bornes, formats, champs inconnus retirés)
const item = normalizeItem({
id: `legacy-${r.id}`, id: `legacy-${r.id}`,
title, title,
originalTitle: r.original_title && r.original_title !== title ? r.original_title : undefined, originalTitle: r.original_title && r.original_title !== title ? r.original_title : undefined,
@@ -208,7 +213,9 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
})(), })(),
createdAt: created, createdAt: created,
updatedAt: toISO(r.watch_date) ?? created, updatedAt: toISO(r.watch_date) ?? created,
}) } satisfies MediaItem)
if (item) items.push(item)
else skipped++
} }
return { items, skipped } return { items, skipped }
} }
+8 -5
View File
@@ -1,4 +1,4 @@
import { t } from '../i18n' import { t, tmdbLanguage } from '../i18n'
import { ANILIST, ANILIST_FIELDS, aniToResult, tmdbFetch, tmdbToResult, TMDB_IMG, type AniMedia, type SearchResult, type TmdbItem } from './catalogApi' import { ANILIST, ANILIST_FIELDS, aniToResult, tmdbFetch, tmdbToResult, TMDB_IMG, type AniMedia, type SearchResult, type TmdbItem } from './catalogApi'
import { cleanText, isSafeTmdbPath, safePosterUrl } from './security' import { cleanText, isSafeTmdbPath, safePosterUrl } from './security'
@@ -78,7 +78,7 @@ interface TmdbPersonHit {
} }
async function searchTmdbPeople(query: string, key: string): Promise<PersonHit[]> { async function searchTmdbPeople(query: string, key: string): Promise<PersonHit[]> {
const data = await tmdbFetch<{ results?: TmdbPersonHit[] }>('/search/person', key, { query: query.slice(0, 100), include_adult: 'false' }) const data = await tmdbFetch<{ results?: TmdbPersonHit[] }>('/search/person', key, { query, include_adult: 'false' })
return (Array.isArray(data.results) ? data.results : []) return (Array.isArray(data.results) ? data.results : [])
.slice(0, 12) .slice(0, 12)
.map((p): PersonHit | null => { .map((p): PersonHit | null => {
@@ -105,6 +105,7 @@ async function aniQuery<T>(query: string, variables: Record<string, unknown>): P
body: JSON.stringify({ query, variables }), body: JSON.stringify({ query, variables }),
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
credentials: 'omit', credentials: 'omit',
signal: AbortSignal.timeout(12_000),
}) })
if (res.status === 429) throw new Error(t('err.anilistRate')) if (res.status === 429) throw new Error(t('err.anilistRate'))
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status })) if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
@@ -333,11 +334,13 @@ const personCache = new Map<string, Promise<PersonDetails>>()
export function getPerson(id: string, tmdbKey?: string): Promise<PersonDetails> { export function getPerson(id: string, tmdbKey?: string): Promise<PersonDetails> {
if (!isPersonId(id)) return Promise.reject(new Error(t('person.notFound'))) if (!isPersonId(id)) return Promise.reject(new Error(t('person.notFound')))
if (id.startsWith('tmdbp:') && !tmdbKey?.trim()) return Promise.reject(new Error(t('search.animeOnly'))) if (id.startsWith('tmdbp:') && !tmdbKey?.trim()) return Promise.reject(new Error(t('search.animeOnly')))
const cached = personCache.get(id) // Clé avec la langue : biographie et titres changent avec elle
const cacheKey = `${id}:${tmdbLanguage()}`
const cached = personCache.get(cacheKey)
if (cached) return cached if (cached) return cached
const p = id.startsWith('tmdbp:') ? tmdbPerson(id, tmdbKey!) : aniPerson(id) const p = id.startsWith('tmdbp:') ? tmdbPerson(id, tmdbKey!) : aniPerson(id)
personCache.set(id, p) personCache.set(cacheKey, p)
p.catch(() => personCache.delete(id)) p.catch(() => personCache.delete(cacheKey))
return p return p
} }
+5 -2
View File
@@ -21,7 +21,8 @@ export function episodesPatch(
const today = todayISO() const today = todayISO()
if (watched > 0) { if (watched > 0) {
if (!item.startDate || item.episodesWatched === 0) patch.startDate = item.episodesWatched === 0 ? today : item.startDate ?? today // Premier épisode coché (ou date de début manquante) : début aujourd'hui
if (!item.startDate || item.episodesWatched === 0) patch.startDate = today
if (item.status === 'a_voir' || item.status === 'pause') patch.status = 'en_cours' if (item.status === 'a_voir' || item.status === 'pause') patch.status = 'en_cours'
} else { } else {
patch.startDate = undefined patch.startDate = undefined
@@ -33,7 +34,9 @@ export function episodesPatch(
patch.status = 'termine' patch.status = 'termine'
// Date de fin = le jour où l'on coche le dernier épisode // Date de fin = le jour où l'on coche le dernier épisode
patch.endDate = item.status === 'termine' && item.endDate ? item.endDate : today patch.endDate = item.status === 'termine' && item.endDate ? item.endDate : today
} else if (watched > 0 && item.status === 'termine' && watched < item.episodesWatched) { } else if (watched > 0 && item.status === 'termine' && (watched < item.episodesWatched || (cap && watched > item.episodesWatched))) {
// Terminé, puis un épisode décoché… ou coché alors que de nouveaux épisodes sont sortis
// (série en cours dont le total a augmenté) : la fiche repasse « En cours »
patch.status = 'en_cours' patch.status = 'en_cours'
patch.endDate = undefined patch.endDate = undefined
} }
+11 -4
View File
@@ -15,7 +15,6 @@ export interface CalendarEvent {
date: string // AAAA-MM-JJ date: string // AAAA-MM-JJ
item: MediaItem item: MediaItem
label: string label: string
kind: 'episode' | 'release'
} }
type ReleaseCache = Record<string, ReleaseInfo & { checkedAt: string }> type ReleaseCache = Record<string, ReleaseInfo & { checkedAt: string }>
@@ -86,26 +85,34 @@ export async function refreshReleases(items: MediaItem[], tmdbKey?: string, forc
) )
} }
} }
// Fiches retirées de la bibliothèque : leurs sorties ne servent plus (le cache ne grossit plus sans fin)
// (bibliothèque vide = pas encore chargée : on ne touche à rien)
if (items.length) {
const ids = new Set(items.map((i) => i.id))
for (const id of Object.keys(cache)) if (!ids.has(id)) delete cache[id]
}
saveReleases(cache) saveReleases(cache)
return cache return cache
} }
/** Tous les évènements connus, triés par date (à partir d'il y a 7 jours). */ /** Tous les évènements connus, triés par date (à partir d'il y a 7 jours). */
export function calendarEvents(items: MediaItem[], releases: ReleaseCache = loadReleases()): CalendarEvent[] { export function calendarEvents(items: MediaItem[], releases: ReleaseCache = loadReleases()): CalendarEvent[] {
const from = localDay(new Date(Date.now() - 7 * 86400000)) // Il y a 7 jours (calcul en jours du calendrier : juste aux changements d'heure)
const now = new Date()
const from = localDay(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7))
const airing = loadAiring() const airing = loadAiring()
const events: CalendarEvent[] = [] const events: CalendarEvent[] = []
for (const item of trackable(items)) { for (const item of trackable(items)) {
const nx = airing[item.id]?.next const nx = airing[item.id]?.next
if (nx && nx.date >= from) { if (nx && nx.date >= from) {
const label = nx.episode === 1 && nx.season ? t('release.season', { season: nx.season }) : t('release.episode', { ep: nx.episode }) const label = nx.episode === 1 && nx.season ? t('release.season', { season: nx.season }) : t('release.episode', { ep: nx.episode })
events.push({ date: nx.date, item, label, kind: 'episode' }) events.push({ date: nx.date, item, label })
} }
} }
const byId = new Map(items.map((i) => [i.id, i])) const byId = new Map(items.map((i) => [i.id, i]))
for (const [id, r] of Object.entries(releases)) { for (const [id, r] of Object.entries(releases)) {
const item = byId.get(id) const item = byId.get(id)
if (item && item.status === 'a_voir' && r.date >= from) events.push({ date: r.date, item, label: r.label, kind: 'release' }) if (item && item.status === 'a_voir' && r.date >= from) events.push({ date: r.date, item, label: r.label })
} }
return events.sort((a, b) => a.date.localeCompare(b.date) || a.item.title.localeCompare(b.item.title, locale())) return events.sort((a, b) => a.date.localeCompare(b.date) || a.item.title.localeCompare(b.item.title, locale()))
} }
+12 -2
View File
@@ -58,12 +58,22 @@ export function rewatchEpisodesPatch(item: MediaItem, n: number): { patch: Parti
return { patch: { rewatch: { ...item.rewatch, episodes } }, finished: false } return { patch: { rewatch: { ...item.rewatch, episodes } }, finished: false }
} }
/**
* Revisionnage terminé par ce changement (dernier épisode, ou « Revu en entier ») : il disparaît en même temps
* qu'une date rejoint l'historique. Un simple abandon (`stopRewatch`) ne touche pas aux dates.
* On regarde le patch et non le nombre de dates : une date déjà présente ce jour-là (ou le plafond de
* MAX_REWATCHES) ne l'allonge pas, alors que le revisionnage est bien terminé.
*/
export const isRewatchFinish = (current: Pick<MediaItem, 'rewatch'>, patch: Partial<MediaInput>) =>
!!current.rewatch && 'rewatch' in patch && !patch.rewatch && 'rewatchDates' in patch
/** Épisodes vus en plus pendant un revisionnage (pour le journal des défis). */ /** Épisodes vus en plus pendant un revisionnage (pour le journal des défis). */
export function rewatchEpisodeDelta(current: MediaItem, next: MediaItem): number { export function rewatchEpisodeDelta(current: MediaItem, next: MediaItem, finished?: boolean): number {
const before = current.rewatch?.episodes ?? 0 const before = current.rewatch?.episodes ?? 0
if (next.rewatch) return next.rewatch.episodes - before if (next.rewatch) return next.rewatch.episodes - before
// Revisionnage terminé : les derniers épisodes jusqu'à la fin comptent // Revisionnage terminé : les derniers épisodes jusqu'à la fin comptent
if (current.rewatch && (next.rewatchDates?.length ?? 0) > (current.rewatchDates?.length ?? 0)) { const done = finished ?? (!!current.rewatch && (next.rewatchDates?.length ?? 0) > (current.rewatchDates?.length ?? 0))
if (current.rewatch && done) {
const cap = episodeCap(current) const cap = episodeCap(current)
return cap ? Math.max(0, cap - before) : 0 return cap ? Math.max(0, cap - before) : 0
} }
+6 -1
View File
@@ -3,11 +3,16 @@
* et sa propre base IndexedDB. Sans compte (mode local), on garde les anciens noms. * et sa propre base IndexedDB. Sans compte (mode local), on garde les anciens noms.
*/ */
let scope: string | null = null let scope: string | null = null
/** Compteur de changements d'espace (connexion, déconnexion, changement de compte). */
let epoch = 0
export const getScope = () => scope export const getScope = () => scope
export const scopeEpoch = () => epoch
export const setScope = (userId: string | null) => { export const setScope = (userId: string | null) => {
// Un compte (identifiant), ou « guest » : l'espace vide du mode découverte, séparé de tout le reste // Un compte (identifiant), ou « guest » : l'espace vide du mode découverte, séparé de tout le reste
scope = userId && (/^[0-9a-f-]{36}$/i.test(userId) || userId === 'guest') ? userId : null const next = userId && (/^[0-9a-f-]{36}$/i.test(userId) || userId === 'guest') ? userId : null
if (next !== scope) epoch++
scope = next
} }
/** Nom de clé localStorage pour l'espace actif : « azuucine:lists » ou « azuucine:<id>:lists ». */ /** Nom de clé localStorage pour l'espace actif : « azuucine:lists » ou « azuucine:<id>:lists ». */
+7 -5
View File
@@ -37,22 +37,24 @@ function colors() {
async function loadImage(raw?: string): Promise<HTMLImageElement | null> { async function loadImage(raw?: string): Promise<HTMLImageElement | null> {
const src = safePosterUrl(raw) const src = safePosterUrl(raw)
if (!src) return null if (!src) return null
let objectUrl: string | undefined
try { try {
let url = src let url = src
let revoke = false
if (!src.startsWith('data:')) { if (!src.startsWith('data:')) {
const res = await fetch(src, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer' }) // Délai max : une affiche qui ne vient pas ne doit pas bloquer la création de l'image
const res = await fetch(src, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(12_000) })
if (!res.ok) return null if (!res.ok) return null
url = URL.createObjectURL(await res.blob()) url = objectUrl = URL.createObjectURL(await res.blob())
revoke = true
} }
const img = new Image() const img = new Image()
img.src = url img.src = url
await img.decode() await img.decode()
if (revoke) setTimeout(() => URL.revokeObjectURL(url), 5000)
return img return img
} catch { } catch {
return null return null
} finally {
// Une image déjà décodée reste dessinable : l'adresse temporaire peut être libérée, même en cas d'échec
if (objectUrl) URL.revokeObjectURL(objectUrl)
} }
} }
+5 -1
View File
@@ -24,7 +24,11 @@ function firstViewMinutes(item: MediaItem): number {
export function oneViewMinutes(item: MediaItem): number { export function oneViewMinutes(item: MediaItem): number {
if (!TYPE_BY_VALUE[item.type].episodic) return item.duration || DEFAULT_FILM_MINUTES if (!TYPE_BY_VALUE[item.type].episodic) return item.duration || DEFAULT_FILM_MINUTES
const cap = episodeCap(item) const cap = episodeCap(item)
return cap ? cap * (item.episodeDuration || TYPE_BY_VALUE[item.type].episodeMinutes) : 0 const epMin = item.episodeDuration || TYPE_BY_VALUE[item.type].episodeMinutes
// Nombre d'épisodes inconnu : on compte ceux vus au premier visionnage, sinon la durée saisie
// (avant, un revisionnage d'une telle série valait 0 min)
if (cap) return cap * epMin
return item.episodesWatched > 0 ? item.episodesWatched * epMin : item.duration || 0
} }
/** Temps passé à revoir le titre : revisionnages terminés + épisodes du revisionnage en cours. */ /** Temps passé à revoir le titre : revisionnages terminés + épisodes du revisionnage en cours. */
+1 -1
View File
@@ -29,7 +29,7 @@ const CANVAS: Record<Exclude<ThemeMode, 'auto'>, string> = {
light: '#ffffff', light: '#ffffff',
dark: '#0a0a0a', dark: '#0a0a0a',
night: '#000000', night: '#000000',
starfield: '#0a1230', starfield: '#070b1c',
} }
export const isHexColor = (v: unknown): v is string => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v) export const isHexColor = (v: unknown): v is string => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v)
+5 -3
View File
@@ -55,8 +55,9 @@ function OverviewTab() {
if (error) return <EmptyState title={t('admin.loadError')} /> if (error) return <EmptyState title={t('admin.loadError')} />
if (!data) return <Spinner /> if (!data) return <Spinner />
const max = data.signups_by_day.reduce((m, d) => Math.max(m, d.n), 1) // Réponse inattendue du serveur (ancienne version) : pas de graphique plutôt qu'un plantage
const days = data.signups_by_day const days = Array.isArray(data.signups_by_day) ? data.signups_by_day : []
const max = days.reduce((m, d) => Math.max(m, Number(d?.n) || 0), 1)
return ( return (
<div className="mt-6"> <div className="mt-6">
@@ -150,7 +151,8 @@ function UsersTab() {
} catch { } catch {
/* on garde la liste en l'état */ /* on garde la liste en l'état */
} finally { } finally {
if (reqId.current === id) setLoadingMore(false) // Toujours remis à zéro (sinon, recherche changée entre-temps : bouton bloqué pour de bon)
setLoadingMore(false)
} }
} }
+23 -8
View File
@@ -1,7 +1,7 @@
import { genreLabel, subtypeLabel } from '../lib/genres' import { genreLabel, subtypeLabel } from '../lib/genres'
import { locale, t } from '../i18n' import { locale, t } from '../i18n'
import { CheckSquare, Hash, Heart, Search, SlidersHorizontal, X } from 'lucide-react' import { CheckSquare, Hash, Heart, Search, SlidersHorizontal, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react' import { useDeferredValue, useEffect, useMemo, useState } from 'react'
import { StatusDot } from '../components/Badges' import { StatusDot } from '../components/Badges'
import JournalView from '../components/JournalView' import JournalView from '../components/JournalView'
import ListsView from '../components/ListsView' import ListsView from '../components/ListsView'
@@ -77,8 +77,18 @@ export default function CatalogPage({ onOpen, onAdd }: Props) {
return next return next
}) })
// Texte de recherche de chaque fiche, normalisé une fois par bibliothèque (et non à chaque touche)
const haystacks = useMemo(() => {
const map = new Map<string, string>()
for (const i of items)
map.set(i.id, normalizeText([i.title, i.originalTitle, i.subtype, i.subtype && subtypeLabel(i.subtype), i.platform, ...i.genres, ...i.genres.map(genreLabel), ...(i.tags ?? [])].filter(Boolean).join(' ')))
return map
}, [items])
// La saisie reste fluide : le filtrage suit la frappe sans la bloquer
const deferredQuery = useDeferredValue(query)
const results = useMemo(() => { const results = useMemo(() => {
const q = normalizeText(query) const q = normalizeText(deferredQuery)
const filtered = items.filter((i) => { const filtered = items.filter((i) => {
if (types.size && !types.has(i.type)) return false if (types.size && !types.has(i.type)) return false
if (status && i.status !== status) return false if (status && i.status !== status) return false
@@ -86,10 +96,7 @@ export default function CatalogPage({ onOpen, onAdd }: Props) {
if (minRating && (i.rating ?? 0) < minRating) return false if (minRating && (i.rating ?? 0) < minRating) return false
if (favOnly && !i.favorite) return false if (favOnly && !i.favorite) return false
if (tag && !hasTag(i, tag)) return false if (tag && !hasTag(i, tag)) return false
if (q) { if (q && !haystacks.get(i.id)?.includes(q)) return false
const haystack = normalizeText([i.title, i.originalTitle, i.subtype, i.subtype && subtypeLabel(i.subtype), i.platform, ...i.genres, ...i.genres.map(genreLabel), ...(i.tags ?? [])].filter(Boolean).join(' '))
if (!haystack.includes(q)) return false
}
return true return true
}) })
const sorted = [...filtered] const sorted = [...filtered]
@@ -98,7 +105,7 @@ export default function CatalogPage({ onOpen, onAdd }: Props) {
else if (sort === 'watched') else if (sort === 'watched')
sorted.sort((a, b) => (b.endDate ?? b.startDate ?? '').localeCompare(a.endDate ?? a.startDate ?? '')) sorted.sort((a, b) => (b.endDate ?? b.startDate ?? '').localeCompare(a.endDate ?? a.startDate ?? ''))
return sorted return sorted
}, [items, query, types, status, genre, minRating, favOnly, tag, sort]) }, [items, haystacks, deferredQuery, types, status, genre, minRating, favOnly, tag, sort])
const activeAdvanced = (genre ? 1 : 0) + (minRating ? 1 : 0) + (favOnly ? 1 : 0) + (tag ? 1 : 0) const activeAdvanced = (genre ? 1 : 0) + (minRating ? 1 : 0) + (favOnly ? 1 : 0) + (tag ? 1 : 0)
const anyFilter = query || types.size || status || activeAdvanced const anyFilter = query || types.size || status || activeAdvanced
@@ -164,7 +171,15 @@ export default function CatalogPage({ onOpen, onAdd }: Props) {
{t('select.count', { count: selected.length })} {t('select.count', { count: selected.length })}
</p> </p>
<button <button
onClick={() => setSelection(allShownSelected ? new Set() : new Set([...selection, ...results.map((i) => i.id)]))} onClick={() => {
// « Tout désélectionner » ne retire que les fiches affichées (les autres, masquées par un filtre, restent choisies)
const shown = results.map((i) => i.id)
if (allShownSelected) {
const next = new Set(selection)
for (const id of shown) next.delete(id)
setSelection(next)
} else setSelection(new Set([...selection, ...shown]))
}}
className="chip py-1 text-xs" className="chip py-1 text-xs"
disabled={!results.length} disabled={!results.length}
> >
+22 -11
View File
@@ -73,7 +73,9 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
const info = next[i.id] const info = next[i.id]
if (!info) return [] if (!info) return []
const patch: Partial<MediaItem> = {} const patch: Partial<MediaItem> = {}
if (i.status !== 'termine' && info.aired > (i.episodesTotal ?? 0)) patch.episodesTotal = info.aired // Total relevé aux épisodes sortis. Aussi pour une fiche « Terminé » dont la série continue :
// sinon, une fois à jour, les nouveaux épisodes ne pouvaient plus jamais être cochés (le statut ne change pas ici)
if ((i.status !== 'termine' || !info.ended) && info.aired > (i.episodesTotal ?? 0)) patch.episodesTotal = info.aired
// Découpage par saison (nouvelle saison annoncée, ou fiche ajoutée avant le suivi par saison) // Découpage par saison (nouvelle saison annoncée, ou fiche ajoutée avant le suivi par saison)
if (info.seasonSizes && info.seasonSizes.join() !== (i.seasons ?? []).join()) patch.seasons = info.seasonSizes if (info.seasonSizes && info.seasonSizes.join() !== (i.seasons ?? []).join()) patch.seasons = info.seasonSizes
if (info.backdrop && !i.backdrop) patch.backdrop = info.backdrop if (info.backdrop && !i.backdrop) patch.backdrop = info.backdrop
@@ -112,7 +114,8 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
}, []) }, [])
const soon = useMemo(() => { const soon = useMemo(() => {
const today = todayISO() const today = todayISO()
const d = new Date(Date.now() + 7 * 86400000) const now = new Date()
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 7)
const end = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` const end = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
return calendarEvents(items).filter((e) => e.date >= today && e.date <= end).length return calendarEvents(items).filter((e) => e.date >= today && e.date <= end).length
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -122,18 +125,26 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
const airing = useMemo(() => loadAiring(), [cacheVersion]) // eslint-disable-line react-hooks/exhaustive-deps const airing = useMemo(() => loadAiring(), [cacheVersion]) // eslint-disable-line react-hooks/exhaustive-deps
// Pendant la vérification, une série suivie dont on ne connaît pas encore les sorties reste masquée : // Pendant la vérification, une série suivie dont on ne connaît pas encore les sorties reste masquée :
// sinon elle s'affichait puis disparaissait quelques secondes après (une fois vue « à jour »). // sinon elle s'affichait puis disparaissait quelques secondes après (une fois vue « à jour »).
const unknownWhileChecking = (i: MediaItem) => (checkingAiring || loading) && !airing[i.id] && trackable([i]).length > 0 // Listes de l'accueil recalculées seulement quand la bibliothèque ou les sorties changent
const hideUnknown = checkingAiring || loading
// Un revisionnage en cours apparaît comme une série en cours (avec sa propre progression) // Un revisionnage en cours apparaît comme une série en cours (avec sa propre progression)
const inProgress = items.map(progressView).filter((i) => i.status === 'en_cours' && !isCaughtUp(i, airing) && !unknownWhileChecking(i)) const inProgress = useMemo(
() => items.map(progressView).filter((i) => i.status === 'en_cours' && !isCaughtUp(i, airing) && !(hideUnknown && !airing[i.id] && trackable([i]).length > 0)),
[items, airing, hideUnknown],
)
// Bannière : ce que je regarde en ce moment (le plus récemment touché), sinon le prochain « à voir » // Bannière : ce que je regarde en ce moment (le plus récemment touché), sinon le prochain « à voir »
const byRecent = [...inProgress].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) const byRecent = useMemo(() => [...inProgress].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)), [inProgress])
const firstToWatch = items.find((i) => i.status === 'a_voir') const firstToWatch = items.find((i) => i.status === 'a_voir')
const featured = (byRecent.length ? byRecent.slice(0, 8) : firstToWatch ? [firstToWatch] : []) const featured = (byRecent.length ? byRecent.slice(0, 8) : firstToWatch ? [firstToWatch] : [])
const toWatch = items.filter((i) => i.status === 'a_voir').slice(0, 12) const toWatch = useMemo(() => items.filter((i) => i.status === 'a_voir').slice(0, 12), [items])
const recent = items const recent = useMemo(
.filter((i) => i.status === 'termine') () =>
.sort((a, b) => (b.endDate ?? b.updatedAt).localeCompare(a.endDate ?? a.updatedAt)) items
.slice(0, 12) .filter((i) => i.status === 'termine')
.sort((a, b) => (b.endDate ?? b.updatedAt).localeCompare(a.endDate ?? a.updatedAt))
.slice(0, 12),
[items],
)
const seeAll = <LinkArrow onClick={() => onNavigate('catalog')}>{t('home.seeAll')}</LinkArrow> const seeAll = <LinkArrow onClick={() => onNavigate('catalog')}>{t('home.seeAll')}</LinkArrow>
@@ -199,7 +210,7 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
{stats.toWatch ? t('home.rouletteHint', { count: stats.toWatch }) : t('home.rouletteHintAll')} {stats.toWatch ? t('home.rouletteHint', { count: stats.toWatch }) : t('home.rouletteHintAll')}
</span> </span>
</span> </span>
<span className="text-accent">→</span> <span className="inline-block text-accent rtl:-scale-x-100">→</span>
</button> </button>
+43 -18
View File
@@ -1,7 +1,7 @@
import { t } from '../i18n' import { t } from '../i18n'
import { LanguageSelect } from '../i18n/react' import { LanguageSelect } from '../i18n/react'
import { Check, Download, ExternalLink, Eye, EyeOff, HardDrive, Import, ShieldCheck, Smartphone, Trash2, Upload, UserX } from 'lucide-react' import { Check, Download, ExternalLink, Eye, EyeOff, HardDrive, Import, ShieldCheck, Smartphone, Trash2, Upload, UserX } from 'lucide-react'
import { useEffect, useRef, useState, type ReactNode } from 'react' import { useEffect, useId, useRef, useState, type ReactNode } from 'react'
import AccountSection from '../components/AccountSection' import AccountSection from '../components/AccountSection'
import ConfirmDialog from '../components/ConfirmDialog' import ConfirmDialog from '../components/ConfirmDialog'
import ImportWizard from '../components/ImportWizard' import ImportWizard from '../components/ImportWizard'
@@ -16,6 +16,7 @@ import { isAdmin } from '../lib/cloud/admin'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { useEscape } from '../lib/escape' import { useEscape } from '../lib/escape'
import { useBackToClose } from '../lib/backNav' import { useBackToClose } from '../lib/backNav'
import { useScrollLock } from '../lib/scrollLock'
import { useMedia } from '../store' import { useMedia } from '../store'
import { mergeImportedSettings } from '../lib/challenges' import { mergeImportedSettings } from '../lib/challenges'
import { BugReportRow } from '../components/moderation/BugReport' import { BugReportRow } from '../components/moderation/BugReport'
@@ -31,11 +32,17 @@ function Row({ icon, title, hint, onClick, danger }: { icon: ReactNode; title: s
<span className="block font-medium">{title}</span> <span className="block font-medium">{title}</span>
{hint && <span className="mt-0.5 block text-xs text-ink-3">{hint}</span>} {hint && <span className="mt-0.5 block text-xs text-ink-3">{hint}</span>}
</span> </span>
<span className={danger ? 'text-accent' : 'text-ink-3'}>→</span> <span className={cx('inline-block rtl:-scale-x-100', danger ? 'text-accent' : 'text-ink-3')}>→</span>
</button> </button>
) )
} }
/** Bloque le défilement de la page tant qu'il est affiché (fenêtre d'installation). */
function ScrollLock() {
useScrollLock()
return null
}
export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void }) { export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void }) {
const { items, settings, updateSettings, importItems, clearAll, lists, mergeLists, account, guest, requestAccount } = useMedia() const { items, settings, updateSettings, importItems, clearAll, lists, mergeLists, account, guest, requestAccount } = useMedia()
const { canInstall, installed, install } = useInstallPrompt() const { canInstall, installed, install } = useInstallPrompt()
@@ -43,8 +50,16 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
// Une seule vérification par connexion (et pas à chaque changement d'état de la synchro) // Une seule vérification par connexion (et pas à chaque changement d'état de la synchro)
const signedIn = !!account const signedIn = !!account
useEffect(() => { useEffect(() => {
if (signedIn) void isAdmin().then(setAdmin) // Réponse arrivée après une déconnexion (ou la fermeture de la page) : ignorée
let alive = true
if (signedIn)
void isAdmin()
.then((ok) => alive && setAdmin(ok))
.catch(() => alive && setAdmin(false))
else setAdmin(false) else setAdmin(false)
return () => {
alive = false
}
}, [signedIn]) }, [signedIn])
const adminHint = alertsSummary(useAdminAlerts(admin)) const adminHint = alertsSummary(useAdminAlerts(admin))
const fileRef = useRef<HTMLInputElement>(null) const fileRef = useRef<HTMLInputElement>(null)
@@ -120,14 +135,18 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
const confirmImport = async (mode: 'merge' | 'replace') => { const confirmImport = async (mode: 'merge' | 'replace') => {
if (!pending) return if (!pending) return
setConfirm(null) setConfirm(null)
await importItems(pending.items, mode) try {
if (pending.settings) updateSettings(mode === 'merge' ? mergeImportedSettings(pending.settings, settings) : pending.settings) await importItems(pending.items, mode)
if (pending.lists) mergeLists(pending.lists, mode) if (pending.settings) updateSettings(mode === 'merge' ? mergeImportedSettings(pending.settings, settings) : pending.settings)
setMessage({ if (pending.lists) mergeLists(pending.lists, mode)
kind: 'ok', setMessage({
text: pending.skipped ? t('settings.importedSkipped', { n: pending.items.length, skipped: pending.skipped }) : t('settings.imported', { count: pending.items.length }), kind: 'ok',
}) text: pending.skipped ? t('settings.importedSkipped', { n: pending.items.length, skipped: pending.skipped }) : t('settings.imported', { count: pending.items.length }),
setPending(undefined) })
setPending(undefined)
} catch (e) {
setMessage({ kind: 'error', text: (e as Error).message })
}
} }
const onDeleteAccount = async () => { const onDeleteAccount = async () => {
@@ -144,14 +163,19 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
const onReset = async () => { const onReset = async () => {
setConfirm(null) setConfirm(null)
await clearAll() try {
setMessage({ kind: 'ok', text: t('settings.cleared') }) await clearAll()
setMessage({ kind: 'ok', text: t('settings.cleared') })
} catch (e) {
setMessage({ kind: 'error', text: (e as Error).message })
}
} }
const [showImport, setShowImport] = useState(false) const [showImport, setShowImport] = useState(false)
const [showInstall, setShowInstall] = useState(false) const [showInstall, setShowInstall] = useState(false)
useEscape(() => setShowInstall(false), showInstall) useEscape(() => setShowInstall(false), showInstall)
useBackToClose(() => setShowInstall(false), showInstall) useBackToClose(() => setShowInstall(false), showInstall)
const installTitleId = useId()
const platform = detectPlatform() const platform = detectPlatform()
const doNativeInstall = async () => { const doNativeInstall = async () => {
@@ -281,16 +305,17 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
<button onClick={() => setShowInstall(true)} className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2"> <button onClick={() => setShowInstall(true)} className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2">
<span className="text-ink-2"><Smartphone size={19} /></span> <span className="text-ink-2"><Smartphone size={19} /></span>
<span className="flex-1 font-medium">{t('settings.installApp')}</span> <span className="flex-1 font-medium">{t('settings.installApp')}</span>
<span className="text-ink-3">→</span> <span className="inline-block text-ink-3 rtl:-scale-x-100">→</span>
</button> </button>
)} )}
</div> </div>
<p className="mt-2.5 text-xs text-ink-3">{t('settings.installHint')}</p> <p className="mt-2.5 text-xs text-ink-3">{t('settings.installHint')}</p>
{showInstall && ( {showInstall && (
<div className="fixed inset-0 z-[70] flex items-end justify-center bg-black/70 p-4 sm:items-center" onClick={() => setShowInstall(false)}> <div className="fixed inset-0 z-[70] flex items-end justify-center bg-scrim p-4 sm:items-center" onClick={() => setShowInstall(false)}>
<div role="dialog" aria-modal="true" className="sheet-in safe-bottom w-full max-w-sm rounded-3xl border border-line-strong bg-surface p-5" onClick={(e) => e.stopPropagation()}> <ScrollLock />
<h2 className="flex items-center gap-2 text-lg"><Smartphone size={20} className="text-accent" /> {t('install.title')}</h2> <div role="dialog" aria-modal="true" aria-labelledby={installTitleId} className="sheet-in safe-bottom w-full max-w-sm rounded-3xl border border-line-strong bg-surface p-5" onClick={(e) => e.stopPropagation()}>
<h2 id={installTitleId} className="flex items-center gap-2 text-lg"><Smartphone size={20} className="text-accent" /> {t('install.title')}</h2>
<ol className="mt-4 space-y-3"> <ol className="mt-4 space-y-3">
{t(`install.${platform}`).split('\n').map((step, i) => ( {t(`install.${platform}`).split('\n').map((step, i) => (
<li key={i} className="flex gap-3 text-sm leading-relaxed text-ink-2"> <li key={i} className="flex gap-3 text-sm leading-relaxed text-ink-2">
@@ -353,7 +378,7 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
</p> </p>
{proxy !== 'ok' && proxy !== 'checking' && ( {proxy !== 'ok' && proxy !== 'checking' && (
<button onClick={() => void runProxyCheck()} className="mt-2 text-xs font-medium text-ink-3"> <button onClick={() => void runProxyCheck()} className="mt-2 text-xs font-medium text-ink-3">
{t('settings.recheck')} <span className="text-accent">→</span> {t('settings.recheck')} <span className="inline-block text-accent rtl:-scale-x-100">→</span>
</button> </button>
)} )}
</div> </div>
+2 -1
View File
@@ -416,7 +416,8 @@ export function BugsTab({ onChange }: { onChange: () => void }) {
setBusyId(b.id) setBusyId(b.id)
try { try {
await adminSetBugStatus(b.id, s) await adminSetBugStatus(b.id, s)
setRows((p) => p.map((x) => (x.id === b.id ? { ...x, status: s } : x))) // Filtre actif : le signalement qui n'y correspond plus quitte la liste (comme au rechargement)
setRows((p) => (filter !== 'all' && filter !== s ? p.filter((x) => x.id !== b.id) : p.map((x) => (x.id === b.id ? { ...x, status: s } : x))))
onChange() onChange()
} catch { } catch {
/* inchangé */ /* inchangé */
+91 -34
View File
@@ -7,7 +7,7 @@ import { applyTheme, DEFAULT_ACCENT } from './lib/theme'
import { normalizeItem, normalizeLists, normalizeSettings } from './lib/backup' import { normalizeItem, normalizeLists, normalizeSettings } from './lib/backup'
import { CLOUD_TMDB, isPlausibleTmdbKey } from './lib/catalogApi' import { CLOUD_TMDB, isPlausibleTmdbKey } from './lib/catalogApi'
import { createSync, type SyncEngine, type SyncStatus } from './lib/cloud/sync' import { createSync, type SyncEngine, type SyncStatus } from './lib/cloud/sync'
import { deleteDatabase, readOtherDatabase } from './lib/db' import { deleteDatabase, onExternalChange, readOtherDatabase, writeVersion } from './lib/db'
import { cloudFetch } from './lib/cloud/api' import { cloudFetch } from './lib/cloud/api'
import { signOut } from './lib/cloud/auth' import { signOut } from './lib/cloud/auth'
import { dbNameFor, scopedKey } from './lib/scope' import { dbNameFor, scopedKey } from './lib/scope'
@@ -16,9 +16,9 @@ import { mediaDB, requestPersistentStorage } from './lib/db'
import { episodesPatch } from './lib/progress' import { episodesPatch } from './lib/progress'
import { uid } from './lib/utils' import { uid } from './lib/utils'
import { episodeCap } from './lib/franchise' import { episodeCap } from './lib/franchise'
import { airedCount } from './lib/airing' import { airedCount, CACHE_EVENT } from './lib/airing'
import { logEpisodes } from './lib/challenges' import { logEpisodes, mergeImportedSettings } from './lib/challenges'
import { rewatchEpisodeDelta, rewatchEpisodesPatch } from './lib/rewatch' import { isRewatchFinish, rewatchEpisodeDelta, rewatchEpisodesPatch } from './lib/rewatch'
// Clés propres à l'espace actif (compte connecté, ou appareil sans compte) // Clés propres à l'espace actif (compte connecté, ou appareil sans compte)
const settingsKey = () => scopedKey('settings') const settingsKey = () => scopedKey('settings')
@@ -118,12 +118,28 @@ async function wipeAccountFromDevice(userId: string) {
} catch { } catch {
/* ignore */ /* ignore */
} }
} } // Les caches gardés en mémoire (sorties d'épisodes) sont oubliés eux aussi
window.dispatchEvent(new Event(CACHE_EVENT))
} }
const MediaContext = createContext<MediaStore | null>(null) const MediaContext = createContext<MediaStore | null>(null)
const byUpdatedDesc = (a: MediaItem, b: MediaItem) => b.updatedAt.localeCompare(a.updatedAt) // Dates ISO : la comparaison directe suffit (localeCompare est bien plus lent sur une grosse bibliothèque)
const byUpdatedDesc = (a: MediaItem, b: MediaItem) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0)
/** Place une fiche (nouvelle ou modifiée) dans la liste déjà triée, sans tout retrier. */
function insertSorted(list: MediaItem[], item: MediaItem): MediaItem[] {
const rest = list.filter((i) => i.id !== item.id)
const at = rest.findIndex((i) => i.updatedAt <= item.updatedAt)
if (at < 0) return [...rest, item]
return [...rest.slice(0, at), item, ...rest.slice(at)]
}
/** Fiches lues dans la base → état React (validées, plus récentes d'abord). */
const fromDB = (all: MediaItem[]) => all.map(normalizeItem).filter((i): i is MediaItem => i !== null).sort(byUpdatedDesc)
/** Même statut de synchro (évite de re-rendre toute l'appli pour un statut identique). */
const sameStatus = (a: SyncStatus, b: SyncStatus) => a.state === b.state && a.pending === b.pending && a.lastSyncAt === b.lastSyncAt && a.error === b.error
/** /**
* Service de données : l'état React est la copie de travail, * Service de données : l'état React est la copie de travail,
@@ -183,18 +199,38 @@ export function MediaProvider({
}, []) }, [])
const reloadItems = useCallback(async () => { const reloadItems = useCallback(async () => {
const all = await mediaDB.getAll() // Une écriture de cet onglet pendant la lecture rend le résultat périmé (il effacerait une
setItems(all.map(normalizeItem).filter((i): i is MediaItem => i !== null).sort(byUpdatedDesc)) // modification toute fraîche de l'écran) : on relit, et sinon on l'ignore (l'écriture met l'état à jour elle-même)
}, []) for (let attempt = 0; attempt < 3; attempt++) {
const version = writeVersion()
const all = await mediaDB.getAll()
if (version !== writeVersion()) continue
setItems(fromDB(all))
return
}
}, [setItems])
useEffect(() => { useEffect(() => {
mediaDB mediaDB
.getAll() .getAll()
.then((all) => setItems(all.map(normalizeItem).filter((i): i is MediaItem => i !== null).sort(byUpdatedDesc))) .then((all) => setItems(fromDB(all)))
.catch((e) => setError(t('store.dbError', { error: String(e?.message ?? e) }))) .catch((e) => setError(t('store.dbError', { error: String(e?.message ?? e) })))
.finally(() => setLoading(false)) .finally(() => setLoading(false))
void requestPersistentStorage() void requestPersistentStorage()
}, []) }, [setItems])
// Autres onglets ouverts sur le même espace : leurs modifications apparaissent ici aussi
useEffect(() => {
const offDB = onExternalChange(() => void reloadItems().catch(() => {}))
const onStorage = (e: StorageEvent) => {
if (e.key === listsKey()) setListsState(loadLists())
}
window.addEventListener('storage', onStorage)
return () => {
offDB()
window.removeEventListener('storage', onStorage)
}
}, [reloadItems])
// ─── Compte : synchronisation avec le serveur ─── // ─── Compte : synchronisation avec le serveur ───
const [syncStatus, setSyncStatus] = useState<SyncStatus>({ state: 'idle', pending: 0 }) const [syncStatus, setSyncStatus] = useState<SyncStatus>({ state: 'idle', pending: 0 })
@@ -207,13 +243,14 @@ export function MediaProvider({
applyLists: (next) => setLists(() => next, true), applyLists: (next) => setLists(() => next, true),
getSettings: () => { getSettings: () => {
const { ratingScale, topCategories, accentColor, themeMode, challenges, statsHiddenMonths } = settingsRef.current const { ratingScale, topCategories, accentColor, themeMode, challenges, statsHiddenMonths } = settingsRef.current
return { ratingScale, topCategories, accentColor, themeMode, challenges, statsHiddenMonths } // Mois masqués : liste vide plutôt qu'absente, sinon « tout réafficher » ne partirait jamais au serveur
return { ratingScale, topCategories, accentColor, themeMode, challenges, statsHiddenMonths: statsHiddenMonths ?? [] }
}, },
applySettings: (patch) => updateSettingsRef.current(patch, true), applySettings: (patch) => updateSettingsRef.current(patch, true),
itemsChanged: () => void reloadItems(), itemsChanged: () => void reloadItems().catch(() => {}),
}) })
syncRef.current = engine syncRef.current = engine
const off = engine.subscribe(setSyncStatus) const off = engine.subscribe((s) => setSyncStatus((prev) => (sameStatus(prev, s) ? prev : s)))
setSyncStatus(engine.status()) setSyncStatus(engine.status())
engine.start() engine.start()
@@ -268,8 +305,8 @@ export function MediaProvider({
const item = normalizeItem(raw) const item = normalizeItem(raw)
if (!item) throw new Error(t('store.invalidItem')) if (!item) throw new Error(t('store.invalidItem'))
await mediaDB.put(item) await mediaDB.put(item)
setItems((prev) => [item, ...prev.filter((i) => i.id !== item.id)].sort(byUpdatedDesc)) setItems((prev) => insertSorted(prev, item))
}, []) }, [setItems])
const add = useCallback( const add = useCallback(
async (input: MediaInput) => { async (input: MediaInput) => {
@@ -285,17 +322,23 @@ export function MediaProvider({
async (id: string, patch: Partial<MediaInput>) => { async (id: string, patch: Partial<MediaInput>) => {
const current = itemsRef.current.find((i) => i.id === id) const current = itemsRef.current.find((i) => i.id === id)
if (!current) return if (!current) return
const next = { ...current, ...patch, updatedAt: new Date().toISOString() } const raw = { ...current, ...patch, updatedAt: new Date().toISOString() }
// Notes de saison : série entièrement vue → la note finale est la moyenne des saisons notées // Notes de saison : série entièrement vue → la note finale est la moyenne des saisons notées
if (('seasonRatings' in patch || patch.status === 'termine') && next.status === 'termine' && next.seasonRatings) { if (('seasonRatings' in patch || patch.status === 'termine') && raw.status === 'termine' && raw.seasonRatings) {
const avg = seasonsAverage(next.seasonRatings, settingsRef.current.ratingScale) const avg = seasonsAverage(raw.seasonRatings, settingsRef.current.ratingScale)
if (avg != null) next.rating = avg if (avg != null) raw.rating = avg
} }
// Un revisionnage n'existe que sur un titre terminé // Un revisionnage n'existe que sur un titre terminé
if (next.rewatch && next.status !== 'termine') delete next.rewatch if (raw.rewatch && raw.status !== 'termine') delete raw.rewatch
// Défis : on retient le jour où des épisodes sont cochés (ou décochés) // Validation d'abord : le nombre d'épisodes peut y être plafonné, le journal doit suivre la valeur réelle
const delta = (patch.episodesWatched ?? current.episodesWatched) - current.episodesWatched + rewatchEpisodeDelta(current, next) const next = normalizeItem(raw)
if (!next) throw new Error(t('store.invalidItem'))
// Défis : on retient le jour où des épisodes sont cochés (ou décochés). Les épisodes revus ont leur
// propre journal : ils ne doivent pas réduire l'estimation des épisodes vus la première fois.
const delta = next.episodesWatched - current.episodesWatched
if (delta) next.episodeLog = logEpisodes(current.episodeLog, delta) if (delta) next.episodeLog = logEpisodes(current.episodeLog, delta)
const rewatchDelta = rewatchEpisodeDelta(current, next, isRewatchFinish(current, patch))
if (rewatchDelta) next.rewatchLog = logEpisodes(current.rewatchLog, rewatchDelta)
await save(next) await save(next)
}, },
[save], [save],
@@ -308,7 +351,7 @@ export function MediaProvider({
await mediaDB.remove(id) await mediaDB.remove(id)
removedAtRef.current.set(id, Date.now()) removedAtRef.current.set(id, Date.now())
setItems((prev) => prev.filter((i) => i.id !== id)) setItems((prev) => prev.filter((i) => i.id !== id))
}, []) }, [setItems])
const removeMany = useCallback(async (ids: string[]) => { const removeMany = useCallback(async (ids: string[]) => {
if (!ids.length) return if (!ids.length) return
@@ -317,7 +360,7 @@ export function MediaProvider({
for (const id of ids) removedAtRef.current.set(id, now) for (const id of ids) removedAtRef.current.set(id, now)
const gone = new Set(ids) const gone = new Set(ids)
setItems((prev) => prev.filter((i) => !gone.has(i.id))) setItems((prev) => prev.filter((i) => !gone.has(i.id)))
}, []) }, [setItems])
const updateMany = useCallback( const updateMany = useCallback(
async (patches: { id: string; patch: Partial<MediaInput> }[]) => { async (patches: { id: string; patch: Partial<MediaInput> }[]) => {
@@ -383,19 +426,19 @@ export function MediaProvider({
const importItems = useCallback(async (incoming: MediaItem[], mode: 'merge' | 'replace') => { const importItems = useCallback(async (incoming: MediaItem[], mode: 'merge' | 'replace') => {
if (mode === 'replace') { if (mode === 'replace') {
await mediaDB.clear()
// Remplacement voulu : les fiches importées deviennent la version la plus récente // Remplacement voulu : les fiches importées deviennent la version la plus récente
// (sinon le serveur garderait ses versions plus récentes et les appareils divergeraient) // (sinon le serveur garderait ses versions plus récentes et les appareils divergeraient).
// Effacement et écriture dans la même transaction : en cas d'échec, la bibliothèque reste intacte.
const now = new Date().toISOString() const now = new Date().toISOString()
await mediaDB.putMany(incoming.map((i) => ({ ...i, updatedAt: now }))) await mediaDB.replaceAll(incoming.map((i) => ({ ...i, updatedAt: now })))
} else { } else {
// Fusion : une sauvegarde plus ancienne n'écrase pas une fiche modifiée depuis // Fusion : une sauvegarde plus ancienne n'écrase pas une fiche modifiée depuis
const current = new Map((await mediaDB.getAll()).map((i) => [i.id, i])) const current = new Map((await mediaDB.getAll()).map((i) => [i.id, i]))
await mediaDB.putMany(incoming.filter((i) => !current.has(i.id) || current.get(i.id)!.updatedAt < i.updatedAt)) await mediaDB.putMany(incoming.filter((i) => !current.has(i.id) || current.get(i.id)!.updatedAt < i.updatedAt))
} }
const all = await mediaDB.getAll() const all = await mediaDB.getAll()
setItems(all.sort(byUpdatedDesc)) setItems(fromDB(all))
}, []) }, [setItems])
const setTopList = useCallback( const setTopList = useCallback(
async (category: TopCategory, orderedIds: string[]) => { async (category: TopCategory, orderedIds: string[]) => {
@@ -414,7 +457,7 @@ export function MediaProvider({
if (!changed.length) return if (!changed.length) return
await mediaDB.putMany(changed) await mediaDB.putMany(changed)
const byId = new Map(changed.map((c) => [c.id, c])) const byId = new Map(changed.map((c) => [c.id, c]))
setItems((prev) => prev.map((i) => byId.get(i.id) ?? i)) setItems((prev) => prev.map((i) => byId.get(i.id) ?? i).sort(byUpdatedDesc))
}, },
[setItems], [setItems],
) )
@@ -422,7 +465,7 @@ export function MediaProvider({
const clearAll = useCallback(async () => { const clearAll = useCallback(async () => {
await mediaDB.clear() await mediaDB.clear()
setItems([]) setItems([])
}, []) }, [setItems])
const patchMany = useCallback( const patchMany = useCallback(
async (patches: { id: string; patch: Partial<MediaInput> }[]) => { async (patches: { id: string; patch: Partial<MediaInput> }[]) => {
@@ -462,7 +505,7 @@ export function MediaProvider({
if (changed.length) { if (changed.length) {
await mediaDB.putMany(changed) await mediaDB.putMany(changed)
const map = new Map(changed.map((c) => [c.id, c])) const map = new Map(changed.map((c) => [c.id, c]))
setItems((prev) => prev.map((i) => map.get(i.id) ?? i)) setItems((prev) => prev.map((i) => map.get(i.id) ?? i).sort(byUpdatedDesc))
} }
}, },
[setItems, setLists], [setItems, setLists],
@@ -525,7 +568,19 @@ export function MediaProvider({
const oldLists = normalizeLists(readStorage(scopedKey('lists', null), [])) ?? [] const oldLists = normalizeLists(readStorage(scopedKey('lists', null), [])) ?? []
if (oldLists.length) setLists((prev) => [...prev, ...oldLists.filter((l) => !prev.some((p) => p.id === l.id))]) if (oldLists.length) setLists((prev) => [...prev, ...oldLists.filter((l) => !prev.some((p) => p.id === l.id))])
const oldSettings = normalizeSettings(readStorage(scopedKey('settings', null), {})) const oldSettings = normalizeSettings(readStorage(scopedKey('settings', null), {}))
if (oldSettings && Object.keys(oldSettings).length) updateSettings(oldSettings) if (oldSettings && Object.keys(oldSettings).length) {
// Les réglages du compte gardent la main : les anciens ne complètent que ce qu'il n'a pas encore choisi
const mine = normalizeSettings(readStorage(settingsKey(), {})) ?? {}
const current = settingsRef.current
const merged = mergeImportedSettings(oldSettings, current)
const patch: Partial<Settings> = {}
for (const k of ['ratingScale', 'topCategories', 'accentColor', 'themeMode'] as const) {
if (mine[k] === undefined && merged[k] !== undefined) Object.assign(patch, { [k]: merged[k] })
}
if (oldSettings.challenges?.length) patch.challenges = merged.challenges
if (oldSettings.statsHiddenMonths?.length) patch.statsHiddenMonths = [...new Set([...(current.statsHiddenMonths ?? []), ...oldSettings.statsHiddenMonths])].sort()
if (Object.keys(patch).length) updateSettings(patch)
}
await reloadItems() await reloadItems()
// Les données sont maintenant dans le compte : on retire la copie « sans compte » de l'appareil // Les données sont maintenant dans le compte : on retire la copie « sans compte » de l'appareil
await deleteDatabase(dbNameFor(null)) await deleteDatabase(dbNameFor(null))
@@ -566,6 +621,8 @@ export function MediaProvider({
ask() ask()
return undefined return undefined
}, importItems: noop, setTopList: noop, clearAll: noop, }, importItems: noop, setTopList: noop, clearAll: noop,
// Mises à jour automatiques (affiches, notes du public…) : rien à enregistrer, sans demander de compte
patchMany: async () => {},
updateMany: noop, removeMany: noop, restore: noop, deleteList: noop, toggleInList: noop, updateMany: noop, removeMany: noop, restore: noop, deleteList: noop, toggleInList: noop,
createList: (name: string) => { createList: (name: string) => {
ask() ask()
+2
View File
@@ -65,6 +65,8 @@ export interface MediaItem {
seasonRatings?: Record<string, SeasonRating> seasonRatings?: Record<string, SeasonRating>
/** Épisodes cochés par jour (AAAA-MM-JJ → nombre), pour les défis. Privé (retiré des profils publics). */ /** Épisodes cochés par jour (AAAA-MM-JJ → nombre), pour les défis. Privé (retiré des profils publics). */
episodeLog?: Record<string, number> episodeLog?: Record<string, number>
/** Épisodes revus par jour pendant un revisionnage (AAAA-MM-JJ → nombre), pour les défis. Privé. */
rewatchLog?: Record<string, number>
createdAt: string // ISO createdAt: string // ISO
updatedAt: string // ISO updatedAt: string // ISO
File diff suppressed because it is too large. Load diff
+43 -8
View File
@@ -28,8 +28,22 @@ export function json(req: Request, status: number, body: unknown, extra: Record<
}) })
} }
// Petit cache jeton → utilisateur (évite de revérifier le même jeton à chaque requête) // Petit cache jeton → utilisateur (évite de revérifier le même jeton à chaque requête).
const verified = new Map<string, { id: string; until: number }>() // Les jetons refusés sont aussi gardés 30 s (id null) : un jeton invalide répété ne sollicite pas Supabase Auth à chaque fois.
const verified = new Map<string, { id: string | null; until: number }>()
function remember(token: string, id: string | null, ttlMs: number) {
// Trop d'entrées : on retire les plus anciennes (ordre d'insertion de la Map) au lieu de tout vider
if (verified.size >= 5000) {
let n = verified.size - 4000
for (const k of verified.keys()) {
if (n-- <= 0) break
verified.delete(k)
}
}
verified.delete(token)
verified.set(token, { id, until: Date.now() + ttlMs })
}
/** Vérifie le jeton de connexion auprès de Supabase Auth. Renvoie l'id de l'utilisateur, ou null. */ /** Vérifie le jeton de connexion auprès de Supabase Auth. Renvoie l'id de l'utilisateur, ou null. */
export async function getUserId(req: Request): Promise<string | null> { export async function getUserId(req: Request): Promise<string | null> {
@@ -38,12 +52,24 @@ export async function getUserId(req: Request): Promise<string | null> {
if (!token || token.length > 4096 || token === ANON_KEY) return null if (!token || token.length > 4096 || token === ANON_KEY) return null
const cached = verified.get(token) const cached = verified.get(token)
if (cached && cached.until > Date.now()) return cached.id if (cached && cached.until > Date.now()) return cached.id
const res = await fetch(`${SUPABASE_URL}/auth/v1/user`, { headers: { apikey: ANON_KEY, Authorization: `Bearer ${token}` } }) let res: Response
if (!res.ok) return null try {
const user = (await res.json()) as { id?: string } res = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
headers: { apikey: ANON_KEY, Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(8000),
})
} catch {
return null // Auth injoignable : on ne met rien en cache
}
if (!res.ok) {
await res.body?.cancel()
// Jeton refusé (401/403) : mémorisé brièvement ; erreur passagère (5xx…) : pas de cache
if (res.status === 401 || res.status === 403) remember(token, null, 30_000)
return null
}
const user = (await res.json().catch(() => ({}))) as { id?: string }
if (typeof user.id !== 'string') return null if (typeof user.id !== 'string') return null
if (verified.size > 5000) verified.clear() remember(token, user.id, 60_000)
verified.set(token, { id: user.id, until: Date.now() + 60_000 })
return user.id return user.id
} }
@@ -53,7 +79,16 @@ export function rateLimited(userId: string, max: number, windowMs: number): bool
const now = Date.now() const now = Date.now()
const list = (hits.get(userId) ?? []).filter((t) => now - t < windowMs) const list = (hits.get(userId) ?? []).filter((t) => now - t < windowMs)
list.push(now) list.push(now)
// Réinsertion : la clé passe en fin de Map (ordre = dernière activité)
hits.delete(userId)
hits.set(userId, list) hits.set(userId, list)
if (hits.size > 10000) hits.clear() // Trop de clés : on retire les moins récemment actives au lieu de tout vider (sinon tout le monde repart à zéro)
if (hits.size > 10000) {
let n = hits.size - 8000
for (const k of hits.keys()) {
if (n-- <= 0) break
hits.delete(k)
}
}
return list.length > max return list.length > max
} }
+40 -14
View File
@@ -11,7 +11,8 @@ const PATHS = /^\/(search\/(multi|person)|configuration|discover\/(movie|tv)|(mo
// Paramètres autorisés et forme de leur valeur // Paramètres autorisés et forme de leur valeur
const PARAMS: Record<string, RegExp> = { const PARAMS: Record<string, RegExp> = {
language: /^(fr-FR|en-US|es-ES|it-IT|de-DE|pt-BR|zh-CN|ja-JP|ko-KR)$/, // Forme « xx » ou « xx-YY » : couvre toutes les langues de l'app (src/i18n/index.ts) sans liste à tenir à jour
language: /^[a-z]{2}(-[A-Z]{2})?$/,
query: /^[^\u0000-\u001f]{1,100}$/, query: /^[^\u0000-\u001f]{1,100}$/,
include_adult: /^false$/, include_adult: /^false$/,
page: /^[1-9]\d?$/, page: /^[1-9]\d?$/,
@@ -35,15 +36,7 @@ Deno.serve(async (req) => {
if (req.method !== 'GET') return json(req, 405, { error: 'method' }) if (req.method !== 'GET') return json(req, 405, { error: 'method' })
if (!TMDB_KEY) return json(req, 500, { error: 'TMDB_API_KEY manquante' }) if (!TMDB_KEY) return json(req, 500, { error: 'TMDB_API_KEY manquante' })
// Compte connecté : 600 requêtes / 10 min. Visiteur sans compte (mode découverte) : 200 / 10 min par adresse IP. // On vérifie l'adresse et les paramètres AVANT d'appeler Supabase Auth (une requête invalide ne coûte rien)
const userId = await getUserId(req)
if (userId) {
if (rateLimited(userId, 600, 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(`ip:${ip.slice(0, 64)}`, 200, 10 * 60_000)) return json(req, 429, { error: 'rate' })
}
const url = new URL(req.url) const url = new URL(req.url)
const path = url.searchParams.get('path') ?? '' const path = url.searchParams.get('path') ?? ''
if (!PATHS.test(path)) return json(req, 400, { error: 'path' }) if (!PATHS.test(path)) return json(req, 400, { error: 'path' })
@@ -51,17 +44,50 @@ Deno.serve(async (req) => {
const target = new URL('https://api.themoviedb.org/3' + path) const target = new URL('https://api.themoviedb.org/3' + path)
for (const [k, v] of url.searchParams) { for (const [k, v] of url.searchParams) {
if (k === 'path') continue if (k === 'path') continue
const rule = PARAMS[k] // Object.hasOwn : « ?constructor=x » ne doit pas remonter jusqu'au prototype
const rule = Object.hasOwn(PARAMS, k) ? PARAMS[k] : undefined
if (!rule || !rule.test(v)) return json(req, 400, { error: 'param', name: k.slice(0, 40) }) if (!rule || !rule.test(v)) return json(req, 400, { error: 'param', name: k.slice(0, 40) })
target.searchParams.set(k, v) target.searchParams.set(k, v)
} }
// Compte connecté : 600 requêtes / 10 min. Visiteur sans compte (mode découverte) : 200 / 10 min par adresse IP.
const userId = await getUserId(req)
if (userId) {
if (rateLimited(userId, 600, 10 * 60_000)) return json(req, 429, { error: 'rate' })
} else {
// NB : la 1re entrée de x-forwarded-for peut être fournie par le client. Faute de garantie documentée
// sur un en-tête posé par la plateforme Supabase (non falsifiable), on garde ce comportement.
const ip = (req.headers.get('x-forwarded-for') ?? '').split(',')[0].trim() || req.headers.get('cf-connecting-ip') || 'inconnu'
if (rateLimited(`ip:${ip.slice(0, 64)}`, 200, 10 * 60_000)) return json(req, 429, { error: 'rate' })
}
// Clé v3 (32 caractères) en paramètre, jeton v4 en en-tête // Clé v3 (32 caractères) en paramètre, jeton v4 en en-tête
const isBearer = TMDB_KEY.length > 40 const isBearer = TMDB_KEY.length > 40
if (!isBearer) target.searchParams.set('api_key', TMDB_KEY) if (!isBearer) target.searchParams.set('api_key', TMDB_KEY)
const res = await fetch(target, { headers: isBearer ? { Authorization: `Bearer ${TMDB_KEY}` } : {} }) let res: Response
if (!res.ok) return json(req, res.status === 404 ? 404 : 502, { error: 'tmdb', status: res.status }) let body: string
const body = await res.text() try {
res = await fetch(target, {
headers: isBearer ? { Authorization: `Bearer ${TMDB_KEY}` } : {},
signal: AbortSignal.timeout(8000),
})
if (res.status === 429) {
// TMDB nous limite : on transmet le 429 (et le délai conseillé) plutôt qu'une erreur générique
const retry = res.headers.get('Retry-After')
await res.body?.cancel()
return json(req, 429, { error: 'tmdb', status: 429 }, retry && /^\d{1,5}$/.test(retry) ? { 'Retry-After': retry } : {})
}
if (!res.ok) {
await res.body?.cancel()
return json(req, res.status === 404 ? 404 : 502, { error: 'tmdb', status: res.status })
}
body = await res.text()
} catch (e) {
// TMDB injoignable ou trop lent (délai dépassé)
const timeout = e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError')
return json(req, timeout ? 504 : 502, { error: timeout ? 'timeout' : 'upstream' })
}
if (body.length > 2_000_000) return json(req, 502, { error: 'size' }) if (body.length > 2_000_000) return json(req, 502, { error: 'size' })
return new Response(body, { return new Response(body, {
status: 200, status: 200,
+4 -1
View File
@@ -23,7 +23,10 @@ revoke all on function public.is_admin() from public, anon;
grant execute on function public.is_admin() to authenticated; grant execute on function public.is_admin() to authenticated;
-- Romain est administrateur. -- Romain est administrateur.
insert into public.admins (user_id) values ('4529202d-618c-4b40-ab13-228eef3f71ad') on conflict do nothing; -- (seulement si ce compte existe : une base neuve ou une copie de test n'a pas cet utilisateur)
insert into public.admins (user_id)
select id from auth.users where id = '4529202d-618c-4b40-ab13-228eef3f71ad'
on conflict do nothing;
-- ── Intégration de la suspension dans les fonctions sociales ── -- ── Intégration de la suspension dans les fonctions sociales ──
-- (can_view, search_profiles, get_feed, get_follow_list, get_follow_requests, get_profile -- (can_view, search_profiles, get_feed, get_follow_list, get_follow_requests, get_profile
@@ -22,14 +22,24 @@ begin
end $$; end $$;
-- Plus aucun appareil ne peut s'inscrire aux notifications push -- Plus aucun appareil ne peut s'inscrire aux notifications push
revoke execute on function public.register_push_subscription(text, text, text, text, text) from public, anon, authenticated; do $$ begin
if to_regprocedure('public.register_push_subscription(text,text,text,text,text)') is not null then
execute 'revoke execute on function public.register_push_subscription(text,text,text,text,text) from public, anon, authenticated';
end if;
end $$;
-- Données devenues inutiles : appareils inscrits et notifications déjà reçues -- Données devenues inutiles : appareils inscrits et notifications déjà reçues
delete from public.push_subscriptions; do $$ begin
if to_regclass('public.push_subscriptions') is not null then delete from public.push_subscriptions; end if;
end $$;
delete from public.notifications; delete from public.notifications;
-- Ménage : fonctions et secrets qui ne servaient qu'à l'envoi push -- Ménage : fonctions et secrets qui ne servaient qu'à l'envoi push
drop function if exists public.azuu_push_dispatch(); drop function if exists public.azuu_push_dispatch();
drop function if exists public.push_claim(uuid); drop function if exists public.push_claim(uuid);
drop function if exists public.push_done(uuid, text[], text[]); drop function if exists public.push_done(uuid, text[], text[]);
delete from vault.secrets where name in ('azuu_push_secret', 'azuu_push_url'); do $$ begin
if to_regclass('vault.secrets') is not null then
delete from vault.secrets where name in ('azuu_push_secret', 'azuu_push_url');
end if;
end $$;
@@ -0,0 +1,495 @@
-- ============================================================================
-- Kino — audit du 22 novembre 2026 : corrections serveur. Idempotent (rejouable).
-- 1. Fonctions présentes en ligne mais absentes du dépôt (admin, versions « comptes suspendus ») :
-- elles sont maintenant versionnées ici, telles qu'en ligne (+ corrections ci-dessous).
-- 2. Blocage : un compte qui m'a bloqué ne m'est plus visible (profil, bibliothèque, avis, recherche).
-- 3. Avis par titre : une note mal formée ne casse plus la page ; tri avant pagination.
-- 4. Fiches supprimées : leur contenu est effacé (empêchait de dépasser le quota de stockage).
-- 5. Comptes suspendus : ne peuvent plus s'abonner ni réagir.
-- 6. Ménage : objets inutilisés depuis la suppression des notifications, fonctions de test.
-- ============================================================================
-- ── 1. Lecture : visibilité d'un compte (suspendu ou m'ayant bloqué = invisible) ──
create or replace function public.can_view(owner uuid)
returns boolean language sql stable security definer set search_path = '' as $$
select auth.uid() is not null and (
owner = auth.uid()
or (
not exists (select 1 from public.profiles p where p.id = owner and p.suspended)
and not exists (select 1 from public.blocks b where b.blocker_id = owner and b.blocked_id = auth.uid())
and (
exists (select 1 from public.profiles p where p.id = owner and not p.is_private)
or exists (select 1 from public.follows f where f.follower_id = auth.uid() and f.following_id = owner and f.status = 'accepted')
)
)
)
$$;
revoke all on function public.can_view(uuid) from public, anon, authenticated;
create or replace function public.get_profile(p_username text)
returns jsonb language plpgsql stable security definer set search_path = '' as $$
declare
p public.profiles;
me uuid := auth.uid();
res jsonb;
begin
if me is null then
return null;
end if;
select * into p from public.profiles where username = lower(trim(p_username));
if not found then
return null;
end if;
-- Compte suspendu : invisible pour les autres (l'admin et le compte lui-même y accèdent)
if p.suspended and p.id <> me and not public.is_admin() then
return null;
end if;
-- Compte qui m'a bloqué : invisible
if p.id <> me and exists (select 1 from public.blocks b where b.blocker_id = p.id and b.blocked_id = me) then
return null;
end if;
res := public.profile_card(p) || jsonb_build_object(
'bio', p.bio,
'banner_url', p.banner_url,
'is_me', p.id = me,
'follows_me', exists (select 1 from public.follows where follower_id = p.id and following_id = me and status = 'accepted'),
'followers', (select count(*) from public.follows where following_id = p.id and status = 'accepted'),
'following', (select count(*) from public.follows where follower_id = p.id and status = 'accepted'),
'visible', public.can_view(p.id)
);
if public.can_view(p.id) then
res := res || jsonb_build_object(
'stats', (
select jsonb_build_object(
'total', count(*),
'finished', count(*) filter (where data->>'status' = 'termine'),
'finished_year', count(*) filter (where data->>'status' = 'termine' and left(data->>'endDate', 4) = to_char(now(), 'YYYY')),
'films', count(*) filter (where data->>'status' = 'termine' and data->>'type' = 'film'),
'series', count(*) filter (where data->>'status' = 'termine' and data->>'type' <> 'film'),
'episodes', coalesce(sum(case when data->>'episodesWatched' ~ '^\d{1,6}$' then (data->>'episodesWatched')::int else 0 end), 0),
'rated', count(*) filter (where data ? 'rating')
)
from public.items where user_id = p.id and not deleted
),
'top', (
select coalesce(jsonb_agg(public.public_item(data) order by data->'top'->>'category', (data->'top'->>'rank')), '[]'::jsonb)
from public.items i
where i.user_id = p.id and not i.deleted and jsonb_typeof(i.data->'top') = 'object'
and coalesce(
(select s.data->'topCategories' ? (i.data->'top'->>'category')
from public.settings s where s.user_id = p.id and jsonb_typeof(s.data->'topCategories') = 'array'),
true)
),
'recent', (
select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc nulls last), '[]'::jsonb)
from (
select data, coalesce(data->>'endDate', data->>'startDate') as k
from public.items
where user_id = p.id and not deleted and data->>'status' = 'termine'
order by k desc nulls last limit 12
) s
),
'watching', (
select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc nulls last), '[]'::jsonb)
from (
select data, coalesce(data->>'startDate', left(data->>'updatedAt', 10)) as k
from public.items
where user_id = p.id and not deleted and data->>'status' = 'en_cours'
order by k desc nulls last limit 8
) s
),
'watchlist', (
select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc nulls last), '[]'::jsonb)
from (
select data, data->>'createdAt' as k
from public.items
where user_id = p.id and not deleted and data->>'status' = 'a_voir'
order by k desc nulls last limit 8
) s
)
);
end if;
return res;
end;
$$;
revoke all on function public.get_profile(text) from public, anon;
grant execute on function public.get_profile(text) to authenticated;
create or replace function public.search_profiles(q text)
returns jsonb language plpgsql stable security definer set search_path = '' as $$
declare
term text := lower(trim(coalesce(q, '')));
pattern text;
begin
if auth.uid() is null or char_length(term) < 2 or char_length(term) > 40 then
return '[]'::jsonb;
end if;
pattern := replace(replace(replace(ltrim(term, '@'), '\', '\\'), '%', '\%'), '_', '\_');
return (
select coalesce(jsonb_agg(public.profile_card(p) order by (p.username = ltrim(term, '@')) desc, p.username), '[]'::jsonb)
from (
select * from public.profiles pr
where pr.id <> auth.uid() and not pr.suspended
and not exists (select 1 from public.blocks b where b.blocker_id = pr.id and b.blocked_id = auth.uid())
and (pr.username like pattern || '%' or lower(pr.display_name) like '%' || pattern || '%')
order by pr.username
limit 20
) p
);
end;
$$;
revoke all on function public.search_profiles(text) from public, anon;
grant execute on function public.search_profiles(text) to authenticated;
-- Versions en ligne (comptes suspendus filtrés), désormais dans le dépôt
create or replace function public.get_follow_requests()
returns jsonb language sql stable security definer set search_path = '' as $$
select coalesce(jsonb_agg(public.profile_card(p) order by f.created_at desc), '[]'::jsonb)
from public.follows f
join public.profiles p on p.id = f.follower_id and not p.suspended
where f.following_id = auth.uid() and f.status = 'pending'
$$;
revoke all on function public.get_follow_requests() from public, anon;
grant execute on function public.get_follow_requests() to authenticated;
create or replace function public.get_follow_list(p_user uuid, p_kind text, p_offset integer default 0)
returns jsonb language plpgsql stable security definer set search_path = '' as $$
begin
if not public.can_view(p_user) or p_kind not in ('followers', 'following') then
return '[]'::jsonb;
end if;
return (
select coalesce(jsonb_agg(public.profile_card(p) order by s.created_at desc), '[]'::jsonb)
from (
select case when p_kind = 'followers' then f.follower_id else f.following_id end as uid, f.created_at
from public.follows f
where f.status = 'accepted' and (case when p_kind = 'followers' then f.following_id else f.follower_id end) = p_user
order by f.created_at desc
offset greatest(p_offset, 0)
limit 50
) s
join public.profiles p on p.id = s.uid and not p.suspended
);
end;
$$;
revoke all on function public.get_follow_list(uuid, text, integer) from public, anon;
grant execute on function public.get_follow_list(uuid, text, integer) to authenticated;
create or replace function public.get_feed(p_before timestamptz default null, p_limit integer default 30)
returns jsonb language sql stable security definer set search_path = '' as $$
select coalesce(jsonb_agg(entry order by created_at desc), '[]'::jsonb)
from (
select a.created_at,
jsonb_build_object(
'id', a.id, 'kind', a.kind, 'created_at', a.created_at,
'user', jsonb_build_object('username', p.username, 'display_name', p.display_name, 'avatar_url', p.avatar_url),
'item', public.public_item(i.data)
) as entry
from public.activity a
join public.follows f on f.following_id = a.user_id and f.follower_id = auth.uid() and f.status = 'accepted'
join public.profiles p on p.id = a.user_id and not p.suspended
join public.items i on i.user_id = a.user_id and i.id = a.item_id and not i.deleted
where p_before is null or a.created_at < p_before
order by a.created_at desc
limit least(greatest(p_limit, 1), 50)
) s
$$;
revoke all on function public.get_feed(timestamptz, integer) from public, anon;
grant execute on function public.get_feed(timestamptz, integer) to authenticated;
-- ── 1 bis. Administration (fonctions en ligne, versionnées ici) ──
create or replace function public.admin_overview()
returns jsonb language plpgsql stable security definer set search_path = '' as $$
declare res jsonb;
begin
if not public.is_admin() then raise exception 'forbidden'; end if;
select jsonb_build_object(
'users', (select count(*) from auth.users),
'profiles', (select count(*) from public.profiles),
'public_profiles', (select count(*) from public.profiles where not is_private and not suspended),
'private_profiles', (select count(*) from public.profiles where is_private and not suspended),
'suspended', (select count(*) from public.profiles where suspended),
'items', (select count(*) from public.items where not deleted),
'reviews', (select count(*) from public.items where not deleted and coalesce(data->>'notes','') <> ''),
'films', (select count(*) from public.items where not deleted and data->>'type' = 'film'),
'series', (select count(*) from public.items where not deleted and data->>'type' <> 'film'),
'follows', (select count(*) from public.follows where status = 'accepted'),
'pending_follows', (select count(*) from public.follows where status = 'pending'),
'media_files', (select count(*) from storage.objects where bucket_id = 'profile-media'),
'signups_7d', (select count(*) from auth.users where created_at > now() - interval '7 days'),
'signups_30d', (select count(*) from auth.users where created_at > now() - interval '30 days'),
'active_7d', (select count(distinct user_id) from public.activity where created_at > now() - interval '7 days'),
'new_items_7d', (select count(*) from public.items where not deleted and updated_at > now() - interval '7 days'),
'signups_by_day', (
select coalesce(jsonb_agg(jsonb_build_object('day', to_char(d.day, 'YYYY-MM-DD'), 'n', coalesce(c.n, 0)) order by d.day), '[]'::jsonb)
from generate_series((current_date - 13), current_date, interval '1 day') as d(day)
left join (
select date_trunc('day', created_at)::date as day, count(*) as n
from auth.users where created_at > now() - interval '14 days' group by 1
) c on c.day = d.day::date
)
) into res;
return res;
end;
$$;
create or replace function public.admin_users(q text default null, p_offset integer default 0)
returns jsonb language plpgsql stable security definer set search_path = '' as $$
declare term text := lower(trim(coalesce(q, '')));
begin
if not public.is_admin() then raise exception 'forbidden'; end if;
return (
select coalesce(jsonb_agg(row_to_json(x) order by x.created_at desc), '[]'::jsonb)
from (
select u.id, u.email, u.created_at, u.last_sign_in_at,
p.username, p.display_name, p.is_private, coalesce(p.suspended, false) as suspended,
(select count(*) from public.items i where i.user_id = u.id and not i.deleted) as items,
(select count(*) from public.items i where i.user_id = u.id and not i.deleted and coalesce(i.data->>'notes','') <> '') as reviews,
(select count(*) from public.follows f where f.following_id = u.id and f.status = 'accepted') as followers
from auth.users u
left join public.profiles p on p.id = u.id
where term = '' or lower(u.email) like '%' || term || '%'
or lower(coalesce(p.username, '')) like '%' || term || '%'
or lower(coalesce(p.display_name, '')) like '%' || term || '%'
order by u.created_at desc
offset greatest(p_offset, 0) limit 50
) x
);
end;
$$;
create or replace function public.admin_recent_reviews(p_offset integer default 0)
returns jsonb language plpgsql stable security definer set search_path = '' as $$
begin
if not public.is_admin() then raise exception 'forbidden'; end if;
return (
select coalesce(jsonb_agg(row_to_json(x) order by x.updated_at desc), '[]'::jsonb)
from (
select i.id as item_id, i.user_id, i.updated_at,
p.username, p.display_name, coalesce(p.suspended, false) as suspended,
i.data->>'title' as title, i.data->>'type' as type,
i.data->>'notes' as notes,
-- Note mal formée dans une fiche : ignorée au lieu de faire échouer la liste
case when i.data->>'rating' ~ '^[0-9]{1,2}(\.[0-9]{1,3})?$' then (i.data->>'rating')::numeric end as rating
from public.items i
left join public.profiles p on p.id = i.user_id
where not i.deleted and coalesce(i.data->>'notes','') <> ''
order by i.updated_at desc
offset greatest(p_offset, 0) limit 30
) x
);
end;
$$;
create or replace function public.admin_set_suspended(p_user uuid, p_value boolean)
returns jsonb language plpgsql security definer set search_path = '' as $$
begin
if not public.is_admin() then raise exception 'forbidden'; end if;
if p_user = auth.uid() then raise exception 'cannot suspend yourself'; end if;
update public.profiles set suspended = coalesce(p_value, false), updated_at = now() where id = p_user;
return jsonb_build_object('ok', found, 'suspended', p_value);
end;
$$;
create or replace function public.admin_clear_review(p_user uuid, p_item text)
returns jsonb language plpgsql security definer set search_path = '' as $$
declare now_iso text := to_char(now() at time zone 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"');
begin
if not public.is_admin() then raise exception 'forbidden'; end if;
update public.items
set data = jsonb_set((data - 'notes'), '{updatedAt}', to_jsonb(now_iso)),
updated_at = now()
where user_id = p_user and id = p_item and not deleted and coalesce(data->>'notes','') <> '';
return jsonb_build_object('ok', found);
end;
$$;
revoke all on function public.admin_overview() from public, anon;
revoke all on function public.admin_users(text, integer) from public, anon;
revoke all on function public.admin_recent_reviews(integer) from public, anon;
revoke all on function public.admin_set_suspended(uuid, boolean) from public, anon;
revoke all on function public.admin_clear_review(uuid, text) from public, anon;
grant execute on function public.admin_overview() to authenticated;
grant execute on function public.admin_users(text, integer) to authenticated;
grant execute on function public.admin_recent_reviews(integer) to authenticated;
grant execute on function public.admin_set_suspended(uuid, boolean) to authenticated;
grant execute on function public.admin_clear_review(uuid, text) to authenticated;
-- ── 3. Avis d'un titre : note mal formée tolérée, comptes qui m'ont bloqué exclus, tri avant pagination ──
create or replace function public.title_reviews(p_external_id text, p_offset integer default 0)
returns jsonb language plpgsql stable security definer set search_path = '' as $$
declare me uuid := auth.uid(); res jsonb;
begin
if me is null or p_external_id !~ '^(tmdb:(movie|tv):[0-9]{1,10}|anilist:[0-9]{1,10})$' then
return jsonb_build_object('friends', '[]'::jsonb, 'others', '[]'::jsonb);
end if;
with revs as (
select i.user_id, i.id as item_id, i.updated_at,
case when i.data->>'rating' ~ '^[0-9]{1,2}(\.[0-9]{1,3})?$' then (i.data->>'rating')::numeric end as rating,
i.data->>'notes' as notes,
coalesce(i.data->>'notesSpoiler', '') = 'true' as spoiler,
pr,
exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted') as friend
from public.items i
join public.profiles pr on pr.id = i.user_id
where i.data->>'externalId' = p_external_id
and not i.deleted and coalesce(i.data->>'notes','') <> ''
and i.user_id <> me and not pr.suspended
and not exists (select 1 from public.blocks b where b.blocker_id = i.user_id and b.blocked_id = me)
and (not pr.is_private
or exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted'))
),
enriched as (
select r.*,
(select coalesce(jsonb_object_agg(e.emoji, e.c), '{}'::jsonb)
from (select emoji, count(*) c from public.review_reactions rr
where rr.author_id = r.user_id and rr.item_id = r.item_id group by emoji) e) as reactions,
(select count(*) from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id) as total,
(select emoji from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id and rr.user_id = me) as mine,
(select count(*) from public.review_comments rc join public.profiles cp on cp.id = rc.user_id
where rc.author_id = r.user_id and rc.item_id = r.item_id and (not cp.suspended or rc.user_id = me)) as comments
from revs r
)
select jsonb_build_object(
'friends', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
'updated_at', updated_at, 'rating', rating, 'notes', notes, 'spoiler', spoiler,
'reactions', reactions, 'total', total, 'mine', mine, 'comments', comments) entry, total, updated_at
from enriched where friend order by total desc, updated_at desc offset greatest(p_offset, 0) limit 40) f), '[]'::jsonb),
'others', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
'updated_at', updated_at, 'rating', rating, 'notes', notes, 'spoiler', spoiler,
'reactions', reactions, 'total', total, 'mine', mine, 'comments', comments) entry, total, updated_at
from enriched where not friend order by total desc, updated_at desc offset greatest(p_offset, 0) limit 40) o), '[]'::jsonb)
) into res;
return res;
end;
$$;
revoke all on function public.title_reviews(text, integer) from public, anon;
grant execute on function public.title_reviews(text, integer) to authenticated;
-- Les avis d'un titre sont cherchés par externalId : index (au lieu de parcourir toutes les fiches)
create index if not exists items_review_external_idx on public.items ((data->>'externalId'))
where not deleted and coalesce(data->>'notes', '') <> '';
-- ── Profils : chacun ne lit directement que le sien (les autres passent par les fonctions ci-dessus) ──
drop policy if exists "profiles readable" on public.profiles;
drop policy if exists "own profile read" on public.profiles;
create policy "own profile read" on public.profiles for select to authenticated using ((select auth.uid()) = id);
-- ── 4. Fiche ou liste supprimée : on n'en garde que la trace (contenu effacé) ──
create or replace function public.azuu_tombstone()
returns trigger language plpgsql set search_path = '' as $$
begin
if new.deleted then new.data := null; end if;
return new;
end $$;
revoke all on function public.azuu_tombstone() from public, anon, authenticated;
drop trigger if exists items_atombstone on public.items;
create trigger items_atombstone before insert or update on public.items for each row execute function public.azuu_tombstone();
drop trigger if exists lists_atombstone on public.lists;
create trigger lists_atombstone before insert or update on public.lists for each row execute function public.azuu_tombstone();
update public.items set data = null where deleted and data is not null;
update public.lists set data = null where deleted and data is not null;
-- Fiche effacée pour de bon : ses commentaires et réactions partent aussi
create or replace function public.azuu_review_cleanup()
returns trigger language plpgsql security definer set search_path = '' as $$
declare r record;
begin
if tg_op = 'DELETE' then r := old; else r := new; end if;
delete from public.review_comments where author_id = r.user_id and item_id = r.id;
if tg_op = 'DELETE' then
delete from public.review_reactions where author_id = r.user_id and item_id = r.id;
end if;
return null;
end $$;
revoke all on function public.azuu_review_cleanup() from public, anon, authenticated;
drop trigger if exists items_review_cleanup_del on public.items;
create trigger items_review_cleanup_del after delete on public.items for each row execute function public.azuu_review_cleanup();
-- ── 5. Compte suspendu : ne peut plus s'abonner ni réagir ──
create or replace function public.azuu_actor_active_guard()
returns trigger language plpgsql security definer set search_path = '' as $$
begin
if auth.uid() is not null and not public.azuu_me_active() then
raise exception 'forbidden';
end if;
return new;
end $$;
revoke all on function public.azuu_actor_active_guard() from public, anon, authenticated;
drop trigger if exists follows_zsuspended_guard on public.follows;
create trigger follows_zsuspended_guard before insert on public.follows for each row execute function public.azuu_actor_active_guard();
drop trigger if exists review_reactions_zsuspended_guard on public.review_reactions;
create trigger review_reactions_zsuspended_guard before insert or update on public.review_reactions for each row execute function public.azuu_actor_active_guard();
-- Blocage : on quitte aussi les listes partagées l'un de l'autre
create or replace function public.block_user(p_user uuid)
returns jsonb language plpgsql security definer set search_path = '' as $$
declare me uuid := auth.uid();
begin
if me is null then raise exception 'auth'; end if;
if p_user is null or p_user = me then raise exception 'bad target'; end if;
if not exists (select 1 from public.profiles p where p.id = p_user) then raise exception 'not found'; end if;
if (select count(*) from public.blocks b where b.blocker_id = me) >= 1000 then raise exception 'too many blocks'; end if;
insert into public.blocks (blocker_id, blocked_id) values (me, p_user) on conflict do nothing;
delete from public.follows f
where (f.follower_id = me and f.following_id = p_user) or (f.follower_id = p_user and f.following_id = me);
delete from public.shared_list_members m using public.shared_lists l
where m.list_id = l.id and m.user_id <> l.owner_id
and ((l.owner_id = me and m.user_id = p_user) or (l.owner_id = p_user and m.user_id = me));
return jsonb_build_object('ok', true);
end;
$$;
revoke all on function public.block_user(uuid) from public, anon;
grant execute on function public.block_user(uuid) to authenticated;
-- Fil d'activité : basculer un statut en boucle ne fait plus remonter la fiche en tête du fil des abonnés
create or replace function public.azuu_log(p_user uuid, p_item text, p_kind text)
returns void language plpgsql security definer set search_path = '' as $$
begin
-- Pas de doublon pour la même fiche dans la journée : la première activité est gardée telle quelle
if exists (select 1 from public.activity
where user_id = p_user and item_id = p_item and kind = p_kind and created_at > now() - interval '1 day') then
return;
end if;
insert into public.activity (user_id, item_id, kind) values (p_user, p_item, p_kind);
-- On garde les 500 dernières activités par compte
delete from public.activity
where user_id = p_user and id in (
select id from public.activity where user_id = p_user order by created_at desc offset 500
);
end;
$$;
revoke all on function public.azuu_log(uuid, text, text) from public, anon, authenticated;
-- Profils publics : on ne sort pas non plus le journal des revisionnages (privé, comme episodeLog)
create or replace function public.public_item(d jsonb)
returns jsonb language sql immutable set search_path = '' as $$
select case when length(coalesce(x->>'poster', '')) > 150000 then x - 'poster' else x end
from (select d - 'listIds' - 'notesPublic' - 'tags' - 'episodeLog' - 'rewatchLog' as x) s
$$;
revoke all on function public.public_item(jsonb) from public, anon, authenticated;
-- ── Index (clés étrangères utilisées à la suppression d'un compte, filtres admin) ──
create index if not exists reports_target_user_idx on public.reports (target_user_id);
create index if not exists review_reactions_user_idx on public.review_reactions (user_id);
create index if not exists moderation_log_admin_idx on public.moderation_log (admin_id);
drop index if exists public.review_reactions_target_idx;
-- ── 6. Ménage : ce qui ne servait qu'aux notifications (la table notifications reste : des fonctions de listes partagées y font encore référence) ──
drop function if exists public.get_notifications(integer);
drop function if exists public.notifications_unread();
drop function if exists public.mark_notifications_read();
drop function if exists public.add_episode_notifications(jsonb);
drop function if exists public.register_push_subscription(text, text, text, text, text);
drop function if exists public.unregister_push_subscription(text);
drop function if exists public.azuu_follow_notify();
drop function if exists public.azuu_reaction_notify();
drop function if exists public.azuu_wants(uuid, text);
drop table if exists public.episode_seen;
drop table if exists public.push_subscriptions;
-- Fonctions de test oubliées
drop function if exists public._tmp_ping2();
drop function if exists public._tmp_sd2();