correction bug
deploy / deploy (push) Successful in 31s

This commit is contained in:
Romain committed 2026-10-04 13:38:33 +02:00
1 parent eaad6f1e77
commit a5da756803
51 files changed
+537 -672

No files matched your search

+4 -2
View File
@@ -4,6 +4,8 @@ import { CLOUD_TMDB, isPlausibleTmdbKey } from './catalogApi'
import { tmdbViaCloud } from './cloud/api'
import { TYPE_BY_VALUE } from './constants'
import { isPlainObject, isSafeExternalId, isSafeId, isSafeTmdbPath, readStorage, remoteImage, safeDay, safeIso, safeSeasons } from './security'
import { episodeCap } from './franchise'
import { localDay } from './utils'
/**
* Suivi des nouveaux épisodes.
@@ -165,7 +167,7 @@ async function checkAniList(ids: number[]): Promise<Map<number, Omit<AiringInfo,
out.set(m.id, {
aired: nx ? Math.max(0, n0(nx.episode) - 1) : n0(m.episodes),
ended: m.status === 'FINISHED' || m.status === 'CANCELLED',
next: nx && ts ? { episode: n0(nx.episode), date: new Date(ts * 1000).toISOString().slice(0, 10) } : undefined,
next: nx && ts ? { episode: n0(nx.episode), date: localDay(new Date(ts * 1000)) } : undefined,
})
}
}
@@ -227,7 +229,7 @@ export function novelties(items: MediaItem[], cache: AiringCache): Novelty[] {
const unwatched = Math.max(0, info.aired - item.episodesWatched)
if (item.status === 'termine') {
// Terminé de mon côté, mais de nouveaux épisodes sont sortis depuis → nouvelle saison
if (unwatched > 0 && item.episodesTotal && info.aired > item.episodesTotal) out.push({ item, info, unwatched, kind: 'new_season' })
if (unwatched > 0 && episodeCap(item) && info.aired > episodeCap(item)!) out.push({ item, info, unwatched, kind: 'new_season' })
} else if (unwatched > 0) {
out.push({ item, info, unwatched, kind: 'new_episodes' })
} else if (info.next && new Date(info.next.date).getTime() < soon) {
+7 -6
View File
@@ -1,6 +1,7 @@
import { t } from '../i18n'
import type { BackupFile, Criteria, CustomList, MediaItem, MediaType, Settings, TopCategory, TopEntry, WatchStatus } from '../types'
import { ALL_TOP_CATEGORIES, MEDIA_TYPES, STATUSES } from './constants'
import { episodeCap } from './franchise'
import { convertLegacyBackup, isLegacyBackup } from './legacyImport'
import {
cleanText,
@@ -61,9 +62,7 @@ function safeDates(v: unknown): string[] | undefined {
return out.length ? out : undefined
}
/** Valide et nettoie une fiche venant d'un fichier importé. Renvoie null si inutilisable. */
/** Valide et nettoie une fiche (import, synchro, écriture locale). Renvoie null si inutilisable. */
export function normalizeItem(raw: unknown): MediaItem | null {
if (!isPlainObject(raw)) return null
const r = raw
@@ -78,8 +77,11 @@ export function normalizeItem(raw: unknown): MediaItem | null {
}
const type = (TYPES.has(r.type as string) ? r.type : 'autre') as MediaType
const episodesTotal = int(r.episodesTotal, 0, 100000) || undefined
const seasons = safeSeasons(r.seasons)
let episodesWatched = int(r.episodesWatched, 0, 100000) ?? 0
if (episodesTotal && episodesWatched > episodesTotal) episodesWatched = episodesTotal
// Plafond : toutes les saisons connues (la fiche peut en avoir plus que le total enregistré)
const cap = episodeCap({ episodesTotal, seasons })
if (cap && episodesWatched > cap) episodesWatched = cap
const listIds = safeStringList(r.listIds, LIMITS.lists, 64).filter(isSafeId)
return {
id: isSafeId(r.id) ? r.id : uid(),
@@ -95,7 +97,7 @@ export function normalizeItem(raw: unknown): MediaItem | null {
episodesWatched,
episodesTotal,
season: int(r.season, 0, 1000) || undefined,
seasons: safeSeasons(r.seasons),
seasons,
episodeDuration: int(r.episodeDuration, 0, 1440) || undefined,
duration: int(r.duration, 0, 6000) || undefined,
startDate: safeDay(r.startDate),
@@ -103,7 +105,6 @@ export function normalizeItem(raw: unknown): MediaItem | null {
genres: safeStringList(r.genres, LIMITS.genres),
platform: cleanText(r.platform, LIMITS.shortText),
notes: cleanText(r.notes, LIMITS.notes),
notesPublic: r.notesPublic === true || undefined,
poster: safePosterUrl(r.poster),
backdrop: remoteImage(r.backdrop),
overview: cleanText(r.overview, LIMITS.overview),
+3 -4
View File
@@ -5,6 +5,7 @@ import { TYPE_BY_VALUE } from './constants'
import { subtypeLabel, tmdbGenres } from './genres'
import { franchiseKey } from './franchise'
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, remoteImage, safeCountries, safeDay, safePosterUrl, safeSeasons, safeStringList } from './security'
import { localDay } from './utils'
/**
* Recherche dans les bases publiques :
@@ -666,7 +667,7 @@ export async function getTmdbRelease(externalId: string, key: string): Promise<R
const pick = (type: number) => day(local.filter((r) => r.type === type).map((r) => r.release_date ?? '').sort()[0])
const cinema = pick(3) ?? pick(2)
const online = pick(4)
const today = new Date().toISOString().slice(0, 10)
const today = localDay()
if (cinema && cinema >= today) return { date: cinema, label: t('release.cinema') }
if (online && online >= today) return { date: online, label: t('release.online') }
const primary = day(d.release_date)
@@ -708,7 +709,7 @@ export async function getAniListReleases(ids: number[]): Promise<Map<number, Rel
if (!Number.isInteger(m?.id)) continue
const nx = m.nextAiringEpisode
if (nx && typeof nx.airingAt === 'number' && nx.airingAt > 0 && nx.airingAt < 4102444800) {
out.set(m.id, { date: new Date(nx.airingAt * 1000).toISOString().slice(0, 10), label: nx.episode === 1 ? t('release.firstEpisode') : nx.episode ? t('release.episode', { ep: nx.episode }) : t('release.newEpisode') })
out.set(m.id, { date: localDay(new Date(nx.airingAt * 1000)), label: nx.episode === 1 ? t('release.firstEpisode') : nx.episode ? t('release.episode', { ep: nx.episode }) : t('release.newEpisode') })
} else if (m.startDate?.year && m.startDate.month && m.startDate.day) {
const d = `${m.startDate.year}-${String(m.startDate.month).padStart(2, '0')}-${String(m.startDate.day).padStart(2, '0')}`
if (day(d)) out.set(m.id, { date: d, label: t('release.firstEpisode') })
@@ -737,8 +738,6 @@ export interface GlobalRelease {
pop: number
}
const localDay = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
function safeRelease(r: GlobalRelease): GlobalRelease | null {
const title = cleanText(r.title, LIMITS.title)
const date = day(r.date)
+7 -2
View File
@@ -261,12 +261,14 @@ async function refresh(): Promise<Session | null> {
try {
const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: s.refreshToken } })
const next = toSession(data)
if (next && next.user.id === s.user.id) setSession(next)
// 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
setSession(next)
return next
} catch (e) {
// Jeton de renouvellement refusé (révoqué, compte supprimé…) : on déconnecte
const status = (e as { status?: number }).status
if (status === 400 || status === 401 || status === 403) setSession(null)
if ((status === 400 || status === 401 || status === 403) && current?.user.id === s.user.id) setSession(null)
return null
} finally {
refreshing = null
@@ -300,6 +302,7 @@ export async function consumeAuthRedirect(): Promise<{ type?: string; error?: st
return { error: code === 'otp_expired' ? t('auth.err.linkExpired') : t('auth.err.linkUsed') }
}
const accessToken = params.get('access_token') ?? ''
if (!TOKEN.test(accessToken)) return { error: t('auth.err.linkInvalid') }
try {
const user = await gotrue('/user', { method: 'GET', token: accessToken })
const s = toSession({
@@ -310,6 +313,8 @@ export async function consumeAuthRedirect(): Promise<{ type?: string; error?: st
user,
})
if (!s) return { error: t('auth.err.linkInvalid') }
// Un lien ne doit jamais remplacer en douce le compte déjà ouvert sur cet appareil
if (current && current.user.id !== s.user.id) return { error: t('auth.err.linkInvalid') }
setSession(s)
return { type: params.get('type') ?? undefined }
} catch (e) {
+13 -2
View File
@@ -299,15 +299,26 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
}
setStatus({ state: 'syncing', error: undefined })
try {
await push()
// Un envoi refusé (fiche trop lourde, quota…) ne doit pas empêcher de recevoir les autres appareils
let pushError: unknown
try {
await push()
} catch (e) {
pushError = e
}
// Déconnexion pendant la synchro : on n'écrit plus rien dans la base de cet utilisateur
if (stopped) return
await pullItems()
if (stopped) return
await pullLists()
if (stopped) return
await pullSettings()
if (pushError) throw pushError
meta.lastSyncAt = new Date().toISOString()
saveMeta()
setStatus({ state: 'idle', lastSyncAt: meta.lastSyncAt })
} catch (e) {
setStatus({ state: navigator.onLine ? 'error' : 'offline', error: (e as Error).message })
if (!stopped) setStatus({ state: navigator.onLine ? 'error' : 'offline', error: (e as Error).message })
}
}
-6
View File
@@ -47,12 +47,6 @@ export const CRITERIA: { key: CriteriaKey; readonly label: string }[] = [
{ key: 'ost', get label() { return t('criteria.ost') } },
]
export const PLATFORM_SUGGESTIONS = [
'Netflix', 'Prime Video', 'Disney+', 'Crunchyroll', 'ADN', 'Viki', 'Apple TV+', 'Max',
'Canal+', 'Paramount+', 'YouTube', 'iQIYI', 'WeTV', 'Youku',
]
export const platformSuggestions = () => [...PLATFORM_SUGGESTIONS, t('platform.cinema'), t('platform.dvd'), t('platform.tv')]
export const TOP_CATEGORIES: { value: TopCategory; readonly label: string; readonly plural: string }[] = [
{ value: 'film', get label() { return t('type.film') }, get plural() { return t('typePlural.film') } },
{ value: 'serie', get label() { return t('type.serie') }, get plural() { return t('typePlural.serie') } },
+29
View File
@@ -0,0 +1,29 @@
import { useEffect, useRef } from 'react'
/**
* Touche Échap : seule la fenêtre ouverte en dernier se ferme
* (sinon une confirmation par-dessus une fiche fermait les deux d'un coup).
*/
const stack: { current: () => void }[] = []
if (typeof window !== 'undefined') {
window.addEventListener('keydown', (e) => {
if (e.key !== 'Escape' || !stack.length) return
e.preventDefault()
stack[stack.length - 1].current()
})
}
export function useEscape(onEscape: () => void, active = true) {
const ref = useRef(onEscape)
ref.current = onEscape
useEffect(() => {
if (!active) return
const entry = { current: () => ref.current() }
stack.push(entry)
return () => {
const k = stack.indexOf(entry)
if (k >= 0) stack.splice(k, 1)
}
}, [active])
}
+2 -2
View File
@@ -3,7 +3,7 @@ import type { MediaItem } from '../types'
import { loadAiring, trackable, CACHE_EVENT } from './airing'
import { getAniListReleases, getTmdbRelease, type ReleaseInfo } from './catalogApi'
import { isPlainObject, isSafeExternalId, isSafeId, readStorage, safeDay, safeIso } from './security'
import { todayISO } from './utils'
import { localDay, todayISO } from './utils'
/**
* Calendrier des sorties :
@@ -92,7 +92,7 @@ export async function refreshReleases(items: MediaItem[], tmdbKey?: string, forc
/** 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[] {
const from = new Date(Date.now() - 7 * 86400000).toISOString().slice(0, 10)
const from = localDay(new Date(Date.now() - 7 * 86400000))
const airing = loadAiring()
const events: CalendarEvent[] = []
for (const item of trackable(items)) {
+5 -3
View File
@@ -40,7 +40,7 @@ export function cleanText(value: unknown, max: number): string | undefined {
/** Identifiant interne : lettres, chiffres, tirets, max 64 caractères. */
export function isSafeId(value: unknown): value is string {
return typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value)
return typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value) && value !== '__proto__'
}
/**
@@ -77,8 +77,10 @@ export function safePosterUrl(value: unknown): string | undefined {
/** Date au format AAAA-MM-JJ valide. */
export function safeDay(value: unknown): string | undefined {
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return undefined
const d = new Date(value + 'T12:00:00')
return Number.isNaN(d.getTime()) ? undefined : value
const [y, m, day] = value.split('-').map(Number)
const d = new Date(Date.UTC(y, m - 1, day))
// « 2026-02-31 » n'existe pas (le moteur JS l'aurait transformé en 3 mars)
return d.getUTCFullYear() === y && d.getUTCMonth() === m - 1 && d.getUTCDate() === day ? value : undefined
}
/** Date-heure ISO valide (ou undefined). */
+4 -2
View File
@@ -2,6 +2,7 @@ import { genreLabel } from './genres'
import { t } from '../i18n'
import type { MediaItem, RatingScale } from '../types'
import { TYPE_BY_VALUE } from './constants'
import { episodeCap } from './franchise'
import { safePosterUrl } from './security'
import { formatRating } from './utils'
@@ -255,8 +256,9 @@ export async function renderItemCard(item: MediaItem, scale: RatingScale, credit
const episodic = TYPE_BY_VALUE[item.type].episodic
const minutes = credits?.runtime ?? item.duration
const rows: [string, string][] = []
if (episodic && item.episodesTotal) {
rows.push([t('form.episodes'), `${t('stats.episodesN', { count: item.episodesTotal })}${item.episodeDuration ? ` · ${t('common.minutes', { n: item.episodeDuration })}` : ''}`])
const totalEps = episodeCap(item)
if (episodic && totalEps) {
rows.push([t('form.episodes'), `${t('stats.episodesN', { count: totalEps })}${item.episodeDuration ? ` · ${t('common.minutes', { n: item.episodeDuration })}` : ''}`])
} else if (!episodic && minutes) {
rows.push([t('form.duration'), t('share.minutesLong', { n: minutes })])
}
+5 -1
View File
@@ -1,5 +1,6 @@
import { locale } from '../i18n'
import type { MediaItem, MediaType, WatchStatus } from '../types'
import { episodeCap } from './franchise'
import { DEFAULT_FILM_MINUTES, MEDIA_TYPES, STATUSES, TYPE_BY_VALUE } from './constants'
/** Temps estimé (minutes) passé sur une fiche. */
@@ -7,7 +8,10 @@ export function watchMinutes(item: MediaItem): number {
const epMin = item.episodeDuration || TYPE_BY_VALUE[item.type].episodeMinutes
if (item.type === 'film') return item.status === 'termine' ? (item.duration || DEFAULT_FILM_MINUTES) * (1 + (item.rewatchDates?.length ?? 0)) : 0
if (item.episodesWatched > 0) return item.episodesWatched * epMin
if (item.status === 'termine') return item.episodesTotal ? item.episodesTotal * epMin : item.duration || 0
if (item.status === 'termine') {
const cap = episodeCap(item)
return cap ? cap * epMin : item.duration || 0
}
return 0
}
+4 -2
View File
@@ -12,12 +12,14 @@ export function uid(): string {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 10)
}
export function todayISO(): string {
const d = new Date()
/** Jour local AAAA-MM-JJ (et pas le jour UTC : un épisode diffusé à 1 h du matin reste au bon jour). */
export function localDay(d: Date = new Date()): string {
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
}
export const todayISO = () => localDay()
export function cx(...classes: (string | false | null | undefined)[]): string {
return classes.filter(Boolean).join(' ')
}