Modif
deploy / deploy (push) Successful in 34s

This commit is contained in:
Romain committed 2026-10-04 12:09:35 +02:00
1 parent b555ef3b94
commit 080279e456
22 files changed
+400 -67

No files matched your search

+1
View File
@@ -63,6 +63,7 @@ export default function App() {
key={editor === 'new' ? 'new' : editor.id}
item={editor === 'new' ? undefined : editor}
onClose={() => setEditor(null)}
onOpenItem={(i) => setEditor(i)}
onGoToSettings={() => {
setEditor(null)
go('settings')
+14 -3
View File
@@ -2,7 +2,8 @@ import { locale, t } from '../i18n'
import { Check, ChevronLeft, ChevronRight, Loader2, Plus, RefreshCw, X } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { loadAiring, refreshAiring, saveAiring } from '../lib/airing'
import { 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 { cachedMonth, isBrowsableMonth, loadMonth, RELEASE_CATEGORIES } from '../lib/globalReleases'
import { remotePosterToLocal } from '../lib/image'
import { calendarEvents, loadReleases, refreshReleases } from '../lib/releases'
@@ -198,7 +199,12 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
}
for (const r of global) {
const key = `${r.externalId}|${r.date}`
const item = byExt.get(r.externalId) ?? byTitle.get(normalizeText(r.title)) ?? (r.originalTitle ? byTitle.get(normalizeText(r.originalTitle)) : undefined)
const item =
byExt.get(r.externalId) ??
byTitle.get(normalizeText(r.title)) ??
(r.originalTitle ? byTitle.get(normalizeText(r.originalTitle)) : undefined) ??
// « Black Clover Season 2 » sur AniList = ma fiche « Black Clover »
(r.cat !== 'film' ? findFranchiseItem(items, [r.title, r.originalTitle], { type: r.cat }) : undefined)
map.set(key, {
key,
date: r.date,
@@ -262,7 +268,12 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
try {
let data: Partial<MediaInput> = {}
let poster: string | undefined
if (r.externalId.startsWith('anilist:')) {
// Anime : on préfère la fiche TMDB, qui regroupe toutes les saisons (sinon chaque saison AniList ferait une fiche)
const series = r.externalId.startsWith('anilist:') && hasKey ? await findTmdbSeries([r.title, r.originalTitle], settings.tmdbKey!).catch(() => undefined) : undefined
if (series) {
data = await getTmdbDetails(series, settings.tmdbKey!)
poster = series.posterUrl ? await remotePosterToLocal(series.posterUrl) : undefined
} else if (r.externalId.startsWith('anilist:')) {
const res = await getAniListById(r.externalId)
data = { ...res?.prefill }
poster = res?.posterUrl ?? r.poster
+41 -48
View File
@@ -1,11 +1,12 @@
import { t } from '../i18n'
import { Check, Loader2, Search } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { getTmdbDetails, searchAniList, searchTmdb, type SearchResult, type Source } from '../lib/catalogApi'
import { getTmdbDetails, searchAll, type SearchResult } from '../lib/catalogApi'
import { findFranchiseItem } from '../lib/franchise'
import { remotePosterToLocal } from '../lib/image'
import { cx } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaInput } from '../types'
import type { MediaInput, MediaItem } from '../types'
interface Props {
/** Reçoit les métadonnées trouvées (titre, type, genres, épisodes, affiche…). */
@@ -14,18 +15,14 @@ interface Props {
/** Identifiant externe de la fiche en cours d'édition (pour ne pas la signaler comme doublon). */
currentExternalId?: string
onGoToSettings?: () => void
/** Nouvelle fiche : si le titre (ou une autre saison) est déjà dans la bibliothèque, on ouvre la fiche existante. */
onOpenExisting?: (item: MediaItem) => void
}
const SOURCES: { value: Source; readonly label: string; hint: string }[] = [
{ value: 'tmdb', get label() { return t('search.moviesSeries') }, hint: 'TMDB' },
{ value: 'anilist', get label() { return t('typePlural.anime') }, hint: 'AniList' },
]
/** Recherche un titre dans TMDB ou AniList et remplit la fiche automatiquement. */
export default function DatabaseSearch({ onPick, initialQuery = '', currentExternalId, onGoToSettings }: Props) {
/** Recherche un titre (films, séries et animes en une seule fois) et remplit la fiche automatiquement. */
export default function DatabaseSearch({ onPick, initialQuery = '', currentExternalId, onGoToSettings, onOpenExisting }: Props) {
const { items, settings } = useMedia()
const hasKey = !!settings.tmdbKey?.trim()
const [source, setSource] = useState<Source>(hasKey ? 'tmdb' : 'anilist')
const [query, setQuery] = useState(initialQuery)
const [results, setResults] = useState<SearchResult[]>([])
const [loading, setLoading] = useState(false)
@@ -33,13 +30,17 @@ export default function DatabaseSearch({ onPick, initialQuery = '', currentExter
const [error, setError] = useState<string>()
const requestId = useRef(0)
const existing = new Set(items.map((i) => i.externalId).filter((id) => id && id !== currentExternalId))
const others = items.filter((i) => !currentExternalId || i.externalId !== currentExternalId)
/** Déjà dans ma bibliothèque : même référence, ou une autre saison de la même série. */
const inLibrary = (r: SearchResult) =>
others.find((i) => i.externalId === r.externalId) ??
findFranchiseItem(others, [r.title, r.originalTitle, ...(r.altTitles ?? [])], { type: r.typeGuess })
// Recherche avec un petit délai pendant la frappe
useEffect(() => {
const q = query.trim()
setError(undefined)
if (q.length < 2 || (source === 'tmdb' && !hasKey)) {
if (q.length < 2) {
setResults([])
setLoading(false)
return
@@ -48,7 +49,7 @@ export default function DatabaseSearch({ onPick, initialQuery = '', currentExter
setLoading(true)
const timer = setTimeout(async () => {
try {
const res = source === 'tmdb' ? await searchTmdb(q, settings.tmdbKey!) : await searchAniList(q)
const res = await searchAll(q, hasKey ? settings.tmdbKey : undefined)
if (id === requestId.current) setResults(res)
} catch (e) {
if (id === requestId.current) {
@@ -60,9 +61,11 @@ export default function DatabaseSearch({ onPick, initialQuery = '', currentExter
}
}, 450)
return () => clearTimeout(timer)
}, [query, source, hasKey, settings.tmdbKey])
}, [query, hasKey, settings.tmdbKey])
const pick = async (r: SearchResult) => {
const mine = onOpenExisting && inLibrary(r)
if (mine) return onOpenExisting(mine)
setPicking(r.externalId)
setError(undefined)
try {
@@ -83,43 +86,32 @@ export default function DatabaseSearch({ onPick, initialQuery = '', currentExter
<div className="card p-4">
<div className="mb-3 flex items-center justify-between gap-2">
<span className="eyebrow">{t('search.fillFrom')}</span>
<div className="flex rounded-full border border-line p-0.5">
{SOURCES.map((s) => (
<button
key={s.value}
type="button"
onClick={() => setSource(s.value)}
className={cx('rounded-full px-3 py-1 text-xs font-medium transition-colors', source === s.value ? 'bg-ink text-bg' : 'text-ink-3')}
>
{s.label}
</button>
))}
</div>
<span className="text-[11px] text-ink-3">{t('search.allKinds')}</span>
</div>
{source === 'tmdb' && !hasKey ? (
<div className="rounded-xl border border-dashed border-line-strong p-3.5 text-sm text-ink-2">
{t('search.needKey')}
<div className="relative">
<Search size={17} className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Parasite, Frieren, Crash Landing on You…"
className="field pl-10"
enterKeyHint="search"
autoComplete="off"
/>
{loading && <Loader2 size={17} className="absolute right-3.5 top-1/2 -translate-y-1/2 animate-spin text-ink-3" />}
</div>
{!hasKey && (
<div className="mt-2 text-xs text-ink-3">
{t('search.animeOnly')}
{onGoToSettings && (
<button type="button" onClick={onGoToSettings} className="mt-2 block font-medium text-ink">
<button type="button" onClick={onGoToSettings} className="ml-1 font-medium text-ink">
{t('search.openSettings')} <span className="text-accent">→</span>
</button>
)}
</div>
) : (
<div className="relative">
<Search size={17} className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={source === 'tmdb' ? 'Parasite, Crash Landing on You…' : 'Frieren, One Piece…'}
className="field pl-10"
enterKeyHint="search"
autoComplete="off"
/>
{loading && <Loader2 size={17} className="absolute right-3.5 top-1/2 -translate-y-1/2 animate-spin text-ink-3" />}
</div>
)}
{error && <p className="mt-2 text-sm text-accent">{error}</p>}
@@ -127,7 +119,8 @@ export default function DatabaseSearch({ onPick, initialQuery = '', currentExter
{results.length > 0 && (
<ul className="-mx-1 mt-3 max-h-[22rem] divide-y divide-line overflow-y-auto overscroll-contain">
{results.map((r) => {
const already = existing.has(r.externalId)
const mine = inLibrary(r)
const already = !!mine
return (
<li key={r.externalId}>
<button
@@ -148,7 +141,7 @@ export default function DatabaseSearch({ onPick, initialQuery = '', currentExter
{r.originalTitle && <span className="block truncate text-xs text-ink-3">{r.originalTitle}</span>}
<span className="mt-1 block text-[10.5px] uppercase text-ink-3">
{[r.kindLabel, r.year].filter(Boolean).join(' · ')}
{already && <span className="text-accent"> · {t('search.already')}</span>}
{already && <span className="text-accent"> · {mine.externalId === r.externalId ? t('search.already') : t('search.alreadySeries')}</span>}
</span>
</span>
{picking === r.externalId ? (
@@ -163,13 +156,13 @@ export default function DatabaseSearch({ onPick, initialQuery = '', currentExter
</ul>
)}
{!loading && !error && query.trim().length >= 2 && results.length === 0 && !(source === 'tmdb' && !hasKey) && (
{!loading && !error && query.trim().length >= 2 && results.length === 0 && (
<p className="mt-3 text-sm text-ink-3">{t('search.noResults')}</p>
)}
<p className="mt-3 flex items-start gap-1.5 text-[11px] leading-relaxed text-ink-3">
<Check size={12} className="mt-0.5 shrink-0" />
{t('search.privacy', { source: source === 'tmdb' ? 'TMDB' : 'AniList' })}
{t('search.privacy', { source: hasKey ? 'TMDB / AniList' : 'AniList' })}
</p>
</div>
)
+10 -4
View File
@@ -1,6 +1,7 @@
import { t } from '../i18n'
import { Heart, Plus } from 'lucide-react'
import { TYPE_BY_VALUE } from '../lib/constants'
import { seasonPosition } from '../lib/franchise'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import { StatusPill, TypeBadge } from './Badges'
@@ -9,16 +10,21 @@ import { RatingBadge } from './Rating'
function Progress({ item }: { item: MediaItem }) {
if (!TYPE_BY_VALUE[item.type].episodic || (!item.episodesWatched && !item.episodesTotal)) return null
const pct = item.episodesTotal ? Math.min(100, (item.episodesWatched / item.episodesTotal) * 100) : 0
// Série en plusieurs saisons : progression dans la saison en cours
const pos = seasonPosition(item)
const done = pos ? pos.episode : item.episodesWatched
const size = pos ? pos.size : item.episodesTotal
const pct = size ? Math.min(100, (done / size) * 100) : 0
const season = pos?.season ?? item.season
return (
<div className="mt-1.5">
<div className="flex justify-between text-[10.5px] text-ink-3">
<span>
{item.season ? `S${item.season} · ` : ''}{t('card.ep', { n: item.episodesWatched })}
{item.episodesTotal ? `/${item.episodesTotal}` : ''}
{season ? `S${season} · ` : ''}{t('card.ep', { n: done })}
{size ? `/${size}` : ''}
</span>
</div>
{item.episodesTotal ? (
{size ? (
<div className="mt-1.5 h-[3px] overflow-hidden rounded-full bg-line">
<div className="h-full rounded-full bg-accent" style={{ width: `${pct}%` }} />
</div>
+78 -5
View File
@@ -4,7 +4,8 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { CRITERIA, DEFAULT_FILM_MINUTES, MEDIA_TYPES, platformSuggestions as defaultPlatforms, STATUSES, TYPE_BY_VALUE } from '../lib/constants'
import { canonicalGenre, canonicalSubtype, genreLabel, genreSuggestions as defaultGenres, subtypeLabel, subtypeSuggestions } from '../lib/genres'
import { fileToPosterDataURL } from '../lib/image'
import { getTmdbCredits } from '../lib/catalogApi'
import { getTmdbCredits, getTmdbSeasons } from '../lib/catalogApi'
import { episodesBeforeSeason, seasonPosition } from '../lib/franchise'
import { renderItemCard, slug } from '../lib/shareCard'
import { useScrollLock } from '../lib/scrollLock'
import { cx, formatRating, todayISO } from '../lib/utils'
@@ -38,6 +39,7 @@ const METADATA_KEYS = [
'overview',
'duration',
'episodesTotal',
'seasons',
'episodeDuration',
'poster',
'externalId',
@@ -70,6 +72,39 @@ interface Props {
item?: MediaItem
onClose: () => void
onGoToSettings?: () => void
/** Ouvre une autre fiche (titre déjà dans la bibliothèque) */
onOpenItem?: (item: MediaItem) => void
}
/** Choix de la saison : « S2 » = la saison 1 est vue, on commence la 2. */
function SeasonPicker({ seasons, watched, season, onChange }: { seasons: number[]; watched: number; season?: number; onChange: (episodesWatched: number, season: number) => void }) {
const current = seasonPosition({ episodesWatched: watched, seasons, season })!
return (
<div>
<span className="label">{t('form.season')}</span>
<div className="no-scrollbar -mx-1 flex gap-1.5 overflow-x-auto px-1 pb-1">
{seasons.map((size, k) => {
const n = k + 1
const start = episodesBeforeSeason(seasons, n)
const done = watched >= start + size
const on = n === current.season
return (
<button
key={n}
type="button"
onClick={() => !on && (n < current.season ? onChange(start + size, n) : onChange(start, n))}
className={cx('chip shrink-0', on && 'chip-on')}
aria-pressed={on}
title={t('form.seasonEpisodes', { count: size })}
>
{done && !on && <Check size={13} />}
S{n}
</button>
)
})}
</div>
</div>
)
}
/** « Moi vs le public » : ma note comparée à la moyenne TMDB / AniList. */
@@ -127,7 +162,7 @@ function Rewatches({ dates, onChange }: { dates: string[]; onChange: (d: string[
)
}
export default function MediaForm({ item, onClose, onGoToSettings }: Props) {
export default function MediaForm({ item, onClose, onGoToSettings, onOpenItem }: Props) {
const { add, update, remove, items, settings, lists } = useMedia()
const [form, setForm] = useState<MediaInput>(() => {
if (!item) return EMPTY
@@ -142,10 +177,29 @@ export default function MediaForm({ item, onClose, onGoToSettings }: Props) {
const fileRef = useRef<HTMLInputElement>(null)
const [showInfo, setShowInfo] = useState(false)
const typeInfo = TYPE_BY_VALUE[form.type]
const pos = typeInfo.episodic ? seasonPosition(form) : undefined
// Bloque le défilement de la page derrière la feuille
useScrollLock()
// Série TMDB ajoutée avant le suivi par saison : on récupère le découpage en arrière-plan
const extId = form.externalId
useEffect(() => {
const key = settings.tmdbKey?.trim()
if (!extId?.startsWith('tmdb:tv:') || form.seasons || !key || !navigator.onLine) return
let alive = true
getTmdbSeasons(extId, key)
.then(({ seasons, total }) => {
if (!alive || !seasons) return
setForm((f) => (f.externalId === extId && !f.seasons ? { ...f, seasons, episodesTotal: Math.max(f.episodesTotal ?? 0, total ?? 0) || f.episodesTotal } : f))
})
.catch(() => {})
return () => {
alive = false
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [extId])
const set = <K extends keyof MediaInput>(key: K, value: MediaInput[K]) => setForm((f) => ({ ...f, [key]: value }))
// Suggestions = listes par défaut + ce que j'ai déjà utilisé
@@ -162,6 +216,8 @@ export default function MediaForm({ item, onClose, onGoToSettings }: Props) {
for (const key of METADATA_KEYS) {
if (data[key] !== undefined) (next as unknown as Record<string, unknown>)[key] = data[key]
}
// Découpage par saison : celui de la nouvelle source (ou aucun)
next.seasons = data.seasons
if (data.type && data.type !== 'autre') next.subtype = undefined
if (data.genres?.length) next.genres = [...new Set([...f.genres, ...data.genres])]
if (data.platform && !f.platform) next.platform = data.platform
@@ -218,6 +274,8 @@ export default function MediaForm({ item, onClose, onGoToSettings }: Props) {
poster: form.poster?.trim() || undefined,
overview: form.overview?.trim() || undefined,
}
const pos = seasonPosition(clean)
if (pos) clean.season = pos.season
try {
if (item) await update(item.id, clean)
else await add(clean)
@@ -285,6 +343,7 @@ export default function MediaForm({ item, onClose, onGoToSettings }: Props) {
initialQuery={item ? form.title : ''}
currentExternalId={item?.externalId}
onGoToSettings={onGoToSettings}
onOpenExisting={!item && onOpenItem ? onOpenItem : undefined}
/>
) : (
<button
@@ -410,21 +469,34 @@ export default function MediaForm({ item, onClose, onGoToSettings }: Props) {
{typeInfo.episodic ? (
<Section title={t('form.episodes')}>
<div className="card space-y-5 p-4">
{pos && form.seasons ? (
<SeasonPicker seasons={form.seasons} watched={form.episodesWatched} season={form.season} onChange={(n, season) => setForm((f) => ({ ...f, episodesWatched: n, season }))} />
) : null}
<div className="flex items-center justify-between">
<span className="text-sm text-ink-2">{t('home.episodesSeen')}</span>
<span className="text-sm text-ink-2">{pos ? t('form.episodesOfSeason', { season: pos.season }) : t('home.episodesSeen')}</span>
<div className="flex items-center gap-3">
<button type="button" onClick={() => changeEpisodes(-1)} className="grid size-10 place-items-center rounded-full border border-line-strong text-ink-2" aria-label={t('form.minusEp')}>
<Minus size={17} />
</button>
<span className="min-w-16 text-center text-2xl font-bold tabular-nums">
{form.episodesWatched}
{form.episodesTotal ? <span className="text-base text-ink-3">/{form.episodesTotal}</span> : null}
{pos ? pos.episode : form.episodesWatched}
{pos ? <span className="text-base text-ink-3">/{pos.size}</span> : form.episodesTotal ? <span className="text-base text-ink-3">/{form.episodesTotal}</span> : null}
</span>
<button type="button" onClick={() => changeEpisodes(1)} className="grid size-10 place-items-center rounded-full bg-accent-fill text-on-accent" aria-label={t('form.plusEp')}>
<Plus size={17} strokeWidth={2.5} />
</button>
</div>
</div>
{pos ? (
<div className="flex items-end justify-between gap-3">
<p className="pb-2 text-xs text-ink-3">{t('form.seasonsTotal', { seasons: form.seasons!.length, count: form.episodesTotal ?? 0 })}</p>
<div className="w-28 shrink-0">
<Field label={t('form.minPerEp')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.episodeDuration ?? ''} onChange={(e) => set('episodeDuration', toNum(e.target.value))} placeholder={String(typeInfo.episodeMinutes)} />
</Field>
</div>
</div>
) : (
<div className="grid grid-cols-3 gap-3">
<Field label={t('form.total')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.episodesTotal ?? ''} onChange={(e) => set('episodesTotal', toNum(e.target.value))} placeholder="?" />
@@ -436,6 +508,7 @@ export default function MediaForm({ item, onClose, onGoToSettings }: Props) {
<input className="field" type="number" inputMode="numeric" min={0} value={form.episodeDuration ?? ''} onChange={(e) => set('episodeDuration', toNum(e.target.value))} placeholder={String(typeInfo.episodeMinutes)} />
</Field>
</div>
)}
</div>
</Section>
) : (
+8
View File
@@ -761,6 +761,14 @@ const dict: Translations = {
'social.watching': "Schaut gerade",
'social.watchlist': "Möchte sehen",
'form.infoHint': "Daten, Jahr, Plattform und Genres – werden automatisch ausgefüllt",
'search.allKinds': "Filme, Serien und Anime",
'search.animeOnly': "Ohne TMDB-Schlüssel werden nur Animes gefunden.",
'search.alreadySeries': "schon in deiner Bibliothek – öffnen",
'form.episodesOfSeason': "Folgen von Staffel {season}",
'form.seasonsTotal_one': "{seasons} Staffeln · insgesamt {count} Folge",
'form.seasonsTotal_other': "{seasons} Staffeln · insgesamt {count} Folgen",
'form.seasonEpisodes_one': "{count} Folge",
'form.seasonEpisodes_other': "{count} Folgen",
}
export default dict
+8
View File
@@ -761,6 +761,14 @@ const dict: Translations = {
'social.watching': "Watching",
'social.watchlist': "Wants to watch",
'form.infoHint': "Dates, year, platform and genres — filled in automatically",
'search.allKinds': "Movies, series and anime",
'search.animeOnly': "Without a TMDB key, only anime can be found.",
'search.alreadySeries': "already in your library — open",
'form.episodesOfSeason': "Season {season} episodes",
'form.seasonsTotal_one': "{seasons} seasons · {count} episode in total",
'form.seasonsTotal_other': "{seasons} seasons · {count} episodes in total",
'form.seasonEpisodes_one': "{count} episode",
'form.seasonEpisodes_other': "{count} episodes",
}
export default dict
+8
View File
@@ -761,6 +761,14 @@ const dict: Translations = {
'social.watching': "Viendo",
'social.watchlist': "Quiere ver",
'form.infoHint': "Fechas, año, plataforma y géneros — se rellenan solos",
'search.allKinds': "Películas, series y anime",
'search.animeOnly': "Sin clave de TMDB solo se encuentran animes.",
'search.alreadySeries': "ya está en tu biblioteca — abrir",
'form.episodesOfSeason': "Episodios de la temporada {season}",
'form.seasonsTotal_one': "{seasons} temporadas · {count} episodio en total",
'form.seasonsTotal_other': "{seasons} temporadas · {count} episodios en total",
'form.seasonEpisodes_one': "{count} episodio",
'form.seasonEpisodes_other': "{count} episodios",
}
export default dict
+8
View File
@@ -763,6 +763,14 @@ const dict = {
'social.watching': "En cours",
'social.watchlist': "Envie de voir",
'form.infoHint': "Dates, année, plateforme et genres — remplis automatiquement",
'search.allKinds': "Films, séries et animes",
'search.animeOnly': "Sans clé TMDB, seuls les animes sont trouvés.",
'search.alreadySeries': "déjà dans ta bibliothèque — ouvrir",
'form.episodesOfSeason': "Épisodes de la saison {season}",
'form.seasonsTotal_one': "{seasons} saisons · {count} épisode au total",
'form.seasonsTotal_other': "{seasons} saisons · {count} épisodes au total",
'form.seasonEpisodes_one': "{count} épisode",
'form.seasonEpisodes_other': "{count} épisodes",
}
export default dict
+8
View File
@@ -761,6 +761,14 @@ const dict: Translations = {
'social.watching': "In corso",
'social.watchlist': "Vuole vedere",
'form.infoHint': "Date, anno, piattaforma e generi — compilati automaticamente",
'search.allKinds': "Film, serie e anime",
'search.animeOnly': "Senza chiave TMDB si trovano solo gli anime.",
'search.alreadySeries': "già nella tua libreria — apri",
'form.episodesOfSeason': "Episodi della stagione {season}",
'form.seasonsTotal_one': "{seasons} stagioni · {count} episodio in totale",
'form.seasonsTotal_other': "{seasons} stagioni · {count} episodi in totale",
'form.seasonEpisodes_one': "{count} episodio",
'form.seasonEpisodes_other': "{count} episodi",
}
export default dict
+8
View File
@@ -761,6 +761,14 @@ const dict: Translations = {
'social.watching': "視聴中",
'social.watchlist': "見たい",
'form.infoHint': "日付・年・配信サービス・ジャンル — 自動で入力されます",
'search.allKinds': "映画・ドラマ・アニメ",
'search.animeOnly': "TMDB キーがない場合はアニメのみ検索できます。",
'search.alreadySeries': "ライブラリにあります — 開く",
'form.episodesOfSeason': "シーズン{season}のエピソード",
'form.seasonsTotal_one': "{seasons}シーズン・全{count}話",
'form.seasonsTotal_other': "{seasons}シーズン・全{count}話",
'form.seasonEpisodes_one': "{count}話",
'form.seasonEpisodes_other': "{count}話",
}
export default dict
+8
View File
@@ -761,6 +761,14 @@ const dict: Translations = {
'social.watching': "보는 중",
'social.watchlist': "보고 싶어요",
'form.infoHint': "날짜, 연도, 플랫폼, 장르 — 자동으로 채워져요",
'search.allKinds': "영화, 시리즈, 애니",
'search.animeOnly': "TMDB 키가 없으면 애니만 찾을 수 있어요.",
'search.alreadySeries': "이미 라이브러리에 있어요 — 열기",
'form.episodesOfSeason': "시즌 {season} 에피소드",
'form.seasonsTotal_one': "{seasons}개 시즌 · 총 {count}화",
'form.seasonsTotal_other': "{seasons}개 시즌 · 총 {count}화",
'form.seasonEpisodes_one': "{count}화",
'form.seasonEpisodes_other': "{count}화",
}
export default dict
+8
View File
@@ -761,6 +761,14 @@ const dict: Translations = {
'social.watching': "Assistindo",
'social.watchlist': "Quer assistir",
'form.infoHint': "Datas, ano, plataforma e gêneros — preenchidos automaticamente",
'search.allKinds': "Filmes, séries e animes",
'search.animeOnly': "Sem chave do TMDB, só animes são encontrados.",
'search.alreadySeries': "já está na sua biblioteca — abrir",
'form.episodesOfSeason': "Episódios da temporada {season}",
'form.seasonsTotal_one': "{seasons} temporadas · {count} episódio no total",
'form.seasonsTotal_other': "{seasons} temporadas · {count} episódios no total",
'form.seasonEpisodes_one': "{count} episódio",
'form.seasonEpisodes_other': "{count} episódios",
}
export default dict
+8
View File
@@ -761,6 +761,14 @@ const dict: Translations = {
'social.watching': "正在看",
'social.watchlist': "想看",
'form.infoHint': "日期、年份、平台和类型——自动填写",
'search.allKinds': "电影、剧集和动画",
'search.animeOnly': "没有 TMDB 密钥时只能找到动画。",
'search.alreadySeries': "已在你的片库中——打开",
'form.episodesOfSeason': "第 {season} 季的集数",
'form.seasonsTotal_one': "{seasons} 季 · 共 {count} 集",
'form.seasonsTotal_other': "{seasons} 季 · 共 {count} 集",
'form.seasonEpisodes_one': "{count} 集",
'form.seasonEpisodes_other': "{count} 集",
}
export default dict
+14 -2
View File
@@ -3,7 +3,7 @@ import type { MediaItem } from '../types'
import { CLOUD_TMDB, isPlausibleTmdbKey } from './catalogApi'
import { tmdbViaCloud } from './cloud/api'
import { TYPE_BY_VALUE } from './constants'
import { isPlainObject, isSafeExternalId, isSafeId, readStorage, safeDay, safeIso } from './security'
import { isPlainObject, isSafeExternalId, isSafeId, readStorage, safeDay, safeIso, safeSeasons } from './security'
/**
* Suivi des nouveaux épisodes.
@@ -19,6 +19,8 @@ export interface AiringInfo {
/** Série terminée / annulée : plus besoin de vérifier souvent */
ended: boolean
seasons?: number
/** Épisodes de chaque saison (TMDB) */
seasonSizes?: number[]
checkedAt: string
}
@@ -27,6 +29,8 @@ export type AiringCache = Record<string, AiringInfo>
const KEY = 'azuucine:airing'
const RECHECK_MS = 12 * 3600 * 1000
const RECHECK_ENDED_MS = 30 * 24 * 3600 * 1000
/** Date d'arrivée du suivi par saison (les vérifications plus anciennes n'ont pas le découpage) */
const SEASONS_SINCE = '2026-10-04T00:00:00.000Z'
const n0 = (v: unknown, max = 100000) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v)) : 0)
@@ -40,7 +44,7 @@ export function loadAiring(): AiringCache {
const checkedAt = safeIso(v.checkedAt)
if (!checkedAt) continue
const next = isPlainObject(v.next) && safeDay(v.next.date) ? { episode: n0(v.next.episode), season: n0(v.next.season) || undefined, date: v.next.date as string } : undefined
out[id] = { aired: n0(v.aired), ended: v.ended === true, seasons: n0(v.seasons) || undefined, next, checkedAt }
out[id] = { aired: n0(v.aired), ended: v.ended === true, seasons: n0(v.seasons) || undefined, seasonSizes: safeSeasons(v.seasonSizes), next, checkedAt }
}
return out
}
@@ -71,6 +75,8 @@ export function trackable(items: MediaItem[]): MediaItem[] {
export function needsCheck(item: MediaItem, cache: AiringCache, force = false): boolean {
const info = cache[item.id]
if (!info || force) return true
// Fiche TMDB vérifiée avant le suivi par saison : on récupère le découpage une fois
if (item.externalId?.startsWith('tmdb:tv:') && !info.seasonSizes && (info.seasons ?? 0) > 1 && info.checkedAt < SEASONS_SINCE) return true
const age = Date.now() - new Date(info.checkedAt).getTime()
return age > (info.ended ? RECHECK_ENDED_MS : RECHECK_MS)
}
@@ -116,6 +122,12 @@ async function checkTmdb(tvId: string, key: string): Promise<Omit<AiringInfo, 'c
return {
aired,
seasons: n0(d.number_of_seasons) || undefined,
seasonSizes: safeSeasons(
(Array.isArray(d.seasons) ? d.seasons : [])
.filter((s) => n0(s.season_number) > 0 && n0(s.episode_count) > 0)
.sort((a, b) => a.season_number - b.season_number)
.map((s) => n0(s.episode_count)),
),
ended: d.status === 'Ended' || d.status === 'Canceled',
next: nx && nextDate ? { episode: n0(nx.episode_number), season: n0(nx.season_number) || undefined, date: nextDate } : undefined,
}
+4
View File
@@ -13,6 +13,7 @@ import {
safeDay,
safeIso,
safePosterUrl,
safeSeasons,
safeStringList,
} from './security'
import { todayISO, uid } from './utils'
@@ -60,6 +61,8 @@ function safeDates(v: unknown): string[] | undefined {
}
/** Valide et nettoie une fiche venant d'un fichier importé. Renvoie null si inutilisable. */
export function normalizeItem(raw: unknown): MediaItem | null {
if (!isPlainObject(raw)) return null
const r = raw
@@ -91,6 +94,7 @@ export function normalizeItem(raw: unknown): MediaItem | null {
episodesWatched,
episodesTotal,
season: int(r.season, 0, 1000) || undefined,
seasons: safeSeasons(r.seasons),
episodeDuration: int(r.episodeDuration, 0, 1440) || undefined,
duration: int(r.duration, 0, 6000) || undefined,
startDate: safeDay(r.startDate),
+66 -2
View File
@@ -3,7 +3,8 @@ import { region, t, tmdbLanguage } from '../i18n'
import { tmdbViaCloud } from './cloud/api'
import { TYPE_BY_VALUE } from './constants'
import { subtypeLabel, tmdbGenres } from './genres'
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, safeCountries, safePosterUrl, safeStringList } from './security'
import { franchiseKey } from './franchise'
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, safeCountries, safePosterUrl, safeSeasons, safeStringList } from './security'
/**
* Recherche dans les bases publiques :
@@ -29,6 +30,8 @@ export interface SearchResult {
prefill?: Partial<MediaInput>
/** URL de l'affiche en bonne qualité */
posterUrl?: string
/** Autres titres connus (romaji…), pour repérer les doublons */
altTitles?: string[]
}
// ─────────────────────────── Nettoyage des réponses ───────────────────────────
@@ -50,6 +53,7 @@ export function sanitizeMeta(d: Partial<MediaInput>): Partial<MediaInput> {
platform: cleanText(d.platform, LIMITS.shortText),
duration: count(d.duration, 6000),
episodesTotal: count(d.episodesTotal, 100000),
seasons: safeSeasons(d.seasons),
episodeDuration: count(d.episodeDuration, 1440),
externalId: isSafeExternalId(d.externalId) ? d.externalId : undefined,
countries: safeCountries(d.countries),
@@ -75,6 +79,7 @@ function safeResult(r: SearchResult): SearchResult | null {
thumb: safePosterUrl(r.thumb),
posterUrl: safePosterUrl(r.posterUrl),
kindLabel: cleanText(r.kindLabel, 40) ?? '',
altTitles: r.altTitles?.map((x) => cleanText(x, LIMITS.title)).filter((x): x is string => !!x).slice(0, 3),
prefill: r.prefill ? sanitizeMeta(r.prefill) : undefined,
}
}
@@ -208,6 +213,7 @@ interface TmdbDetails {
first_air_date?: string
poster_path?: string | null
last_episode_to_air?: { runtime?: number } | null
seasons?: { season_number?: number; episode_count?: number }[]
vote_average?: number
vote_count?: number
'watch/providers'?: { results?: Record<string, { flatrate?: { provider_name: string }[] }> }
@@ -279,7 +285,8 @@ export async function getTmdbDetails(result: SearchResult, key: string): Promise
genres: tmdbGenres((d.genres ?? []).map((g) => g.id)).filter((g) => guess.type === 'film' || g !== 'Animation'),
platform: provider ? (PROVIDER_NAMES[provider] ?? provider) : undefined,
duration: kind === 'movie' ? d.runtime || undefined : undefined,
episodesTotal: kind === 'tv' ? d.number_of_episodes || undefined : undefined,
episodesTotal: kind === 'tv' ? Math.max(d.number_of_episodes || 0, sumSeasons(tmdbSeasons(d))) || undefined : undefined,
seasons: kind === 'tv' ? tmdbSeasons(d) : undefined,
episodeDuration: kind === 'tv' ? epRuntime : undefined,
externalId: result.externalId,
countries: d.origin_country?.length ? d.origin_country : d.production_countries?.map((c) => c.iso_3166_1).slice(0, 3),
@@ -287,6 +294,24 @@ export async function getTmdbDetails(result: SearchResult, key: string): Promise
})
}
/** Épisodes par saison (hors épisodes spéciaux « saison 0 », et saisons annoncées sans épisode). */
function tmdbSeasons(d: TmdbDetails): number[] | undefined {
const list = (Array.isArray(d.seasons) ? d.seasons : [])
.filter((s) => typeof s.season_number === 'number' && s.season_number > 0 && typeof s.episode_count === 'number' && s.episode_count > 0)
.sort((a, b) => a.season_number! - b.season_number!)
.map((s) => s.episode_count!)
return safeSeasons(list)
}
const sumSeasons = (s?: number[]) => (s ?? []).reduce((a, b) => a + b, 0)
/** Saisons d'une série déjà dans la bibliothèque (pour les fiches ajoutées avant le suivi par saison). */
export async function getTmdbSeasons(externalId: string, key: string): Promise<{ seasons?: number[]; total?: number }> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:tv:')) return {}
const d = await tmdbFetch<TmdbDetails>(`/tv/${externalId.split(':')[2]}`, key)
const seasons = tmdbSeasons(d)
return { seasons, total: Math.max(d.number_of_episodes || 0, sumSeasons(seasons)) || undefined }
}
/** Vérifie qu'une clé TMDB fonctionne. */
export async function testTmdbKey(key: string): Promise<boolean> {
try {
@@ -399,6 +424,7 @@ function aniToResult(m: AniMedia): SearchResult | null {
externalId: `anilist:${m.id}`,
title,
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),
year: year ?? undefined,
thumb: m.coverImage?.medium ?? undefined,
posterUrl: m.coverImage?.large ?? m.coverImage?.medium ?? undefined,
@@ -421,6 +447,44 @@ function aniToResult(m: AniMedia): SearchResult | null {
})
}
const titlesOf = (r: SearchResult) => [r.title, r.originalTitle, ...(r.altTitles ?? [])].filter((x): x is string => !!x)
const exactKey = (s: string) => s.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '')
/**
* Recherche unique : films, séries et animes.
* TMDB d'abord (il regroupe toutes les saisons d'une série sous une seule fiche), puis les animes
* d'AniList qu'il ne connaît pas. Les saisons séparées d'AniList (« … Season 2 ») ne sont pas répétées.
*/
export async function searchAll(query: string, key?: string): Promise<SearchResult[]> {
const [tm, an] = await Promise.allSettled([key ? searchTmdb(query, key) : Promise.resolve([]), searchAniList(query)])
if (tm.status === 'rejected' && an.status === 'rejected') throw tm.reason
const tmdb = tm.status === 'fulfilled' ? tm.value : []
const ani = an.status === 'fulfilled' ? an.value : []
const seriesKeys = new Set(tmdb.filter((r) => r.typeGuess !== 'film').flatMap(titlesOf).map(franchiseKey))
const movieKeys = new Set(tmdb.filter((r) => r.typeGuess === 'film').flatMap(titlesOf).map(exactKey))
const seen = new Set<string>()
const extra = ani.filter((r) => {
const titles = titlesOf(r)
if (r.typeGuess === 'film') return !titles.some((x) => movieKeys.has(exactKey(x)))
const keys = titles.map(franchiseKey)
if (keys.some((k) => seriesKeys.has(k) || seen.has(k))) return false
keys.forEach((k) => seen.add(k))
return true
})
return [...tmdb, ...extra]
}
/** Retrouve sur TMDB la série (toutes saisons) correspondant à une saison d'anime AniList. */
export async function findTmdbSeries(titles: (string | undefined)[], key: string): Promise<SearchResult | undefined> {
const keys = new Set(titles.filter((x): x is string => !!x).map(franchiseKey))
for (const q of titles.filter((x): x is string => !!x).slice(0, 2)) {
const found = (await searchTmdb(q, key)).find((r) => r.typeGuess !== 'film' && r.externalId.startsWith('tmdb:tv:') && titlesOf(r).some((x) => keys.has(franchiseKey(x))))
if (found) return found
}
return undefined
}
/** Animes recommandés par AniList à partir d'un anime. */
export async function aniListRecommendations(externalId: string): Promise<SearchResult[]> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('anilist:')) return []
+78
View File
@@ -0,0 +1,78 @@
import { TYPE_BY_VALUE } from './constants'
import type { MediaItem, MediaType } from '../types'
/**
* Saisons et « franchises » de séries.
*
* TMDB range toutes les saisons d'une série sous une seule fiche ; AniList, lui, crée une entrée par saison
* (« Black Clover », « Black Clover Season 2 »…). Pour éviter les doublons, on compare les titres
* débarrassés de leurs marqueurs de saison.
*/
const SEASON_MARKERS = [
/\b(season|saison|temporada|stagione|staffel|part|partie|cour)\s*\d+\b/g,
/\b\d+(st|nd|rd|th|e|eme|ème)\s*(season|saison|part)\b/g,
/\b(the\s+)?(final|last)\s*season\b/g,
/第\s*\d+\s*(期|シーズン|部)/g,
/\s(ii|iii|iv|v|vi)$/g,
]
/** « Black Clover Season 2 », « Aoashi 2nd Season » → « blackclover », « aoashi ». */
export function franchiseKey(title: string): string {
let s = title.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
for (const re of SEASON_MARKERS) s = s.replace(re, ' ')
s = s.replace(/[^\p{L}\p{N}]+/gu, ' ').trim()
// « Black Clover 2 » : nombre final isolé (mais « 86 » reste « 86 »)
const stripped = s.replace(/\s\d{1,2}$/, '').trim()
return (stripped || s).replace(/\s+/g, '')
}
const episodic = (type: MediaType) => TYPE_BY_VALUE[type]?.episodic ?? false
/** Fiche de ma bibliothèque qui correspond à la même série (n'importe quelle saison). */
export function findFranchiseItem(items: MediaItem[], titles: (string | undefined)[], opts: { type?: MediaType; excludeId?: string } = {}): MediaItem | undefined {
if (opts.type && !episodic(opts.type)) return undefined
const keys = new Set(titles.filter((x): x is string => !!x).map(franchiseKey).filter((k) => k.length >= 2))
if (!keys.size) return undefined
return items.find(
(i) => i.id !== opts.excludeId && episodic(i.type) && [i.title, i.originalTitle].some((x) => x && keys.has(franchiseKey(x))),
)
}
export interface SeasonPosition {
/** Saison en cours (1 = première) */
season: number
/** Épisodes vus dans cette saison */
episode: number
/** Nombre d'épisodes de la saison */
size: number
/** Épisodes des saisons précédentes */
before: number
}
/**
* Où en est-on, saison par saison ? (à partir du nombre total d'épisodes vus)
* À la fin exacte d'une saison, on reste sur cette saison (« S1 · 24/24 ») : l'épisode suivant fait passer à la S2…
* sauf si la saison suivante a été choisie (`season`), auquel cas on affiche « S2 · 0/24 ».
*/
export function seasonPosition(item: Pick<MediaItem, 'episodesWatched' | 'seasons' | 'season'>): SeasonPosition | undefined {
const seasons = item.seasons
if (!seasons || seasons.length < 2) return undefined
const chosen = item.season
if (chosen && chosen >= 2 && chosen <= seasons.length) {
const start = episodesBeforeSeason(seasons, chosen)
if (item.episodesWatched === start) return { season: chosen, episode: 0, size: seasons[chosen - 1], before: start }
}
let before = 0
for (let k = 0; k < seasons.length; 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 }
}
before += size
}
return undefined
}
/** Nombre d'épisodes vus au début de la saison n (1 = première). */
export const episodesBeforeSeason = (seasons: number[], n: number) => seasons.slice(0, Math.max(0, n - 1)).reduce((a, b) => a + b, 0)
+7
View File
@@ -125,3 +125,10 @@ export function readStorage<T>(key: string, fallback: T): unknown | T {
/** Objet « simple » (pas un tableau, pas null). */
export const isPlainObject = (v: unknown): v is Record<string, unknown> =>
typeof v === 'object' && v !== null && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype
/** Épisodes par saison : liste d'entiers bornée (au plus 100 saisons). */
export function safeSeasons(v: unknown): number[] | undefined {
if (!Array.isArray(v)) return undefined
const out = v.slice(0, 100).map((n) => (typeof n === 'number' && Number.isInteger(n) && n > 0 && n <= 5000 ? n : 0))
return out.length > 1 && out.every((n) => n > 0) ? out : undefined
}
+9 -3
View File
@@ -53,9 +53,15 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
void refreshAiring(items, cache, settings.tmdbKey)
.then((next) => {
saveAiring(next)
const patches = trackable(items)
.filter((i) => i.status !== 'termine' && next[i.id] && next[i.id].aired > (i.episodesTotal ?? 0))
.map((i) => ({ id: i.id, patch: { episodesTotal: next[i.id].aired } }))
const patches = trackable(items).flatMap((i) => {
const info = next[i.id]
if (!info) return []
const patch: Partial<MediaItem> = {}
if (i.status !== 'termine' && 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)
if (info.seasonSizes && info.seasonSizes.join() !== (i.seasons ?? []).join()) patch.seasons = info.seasonSizes
return Object.keys(patch).length ? [{ id: i.id, patch }] : []
})
if (patches.length) return patchMany(patches)
})
.catch(() => {})
+4
View File
@@ -13,6 +13,7 @@ import { dbNameFor, scopedKey } from './lib/scope'
import { isPlainObject, LIMITS, readStorage } from './lib/security'
import { mediaDB, requestPersistentStorage } from './lib/db'
import { todayISO, uid } from './lib/utils'
import { seasonPosition } from './lib/franchise'
// Clés propres à l'espace actif (compte connecté, ou appareil sans compte)
const settingsKey = () => scopedKey('settings')
@@ -249,6 +250,9 @@ export function MediaProvider({ children, cloudUser }: { children: ReactNode; cl
if (item.episodesTotal) next = Math.min(next, item.episodesTotal)
if (next === item.episodesWatched) return
const patch: Partial<MediaInput> = { episodesWatched: next }
// Série en plusieurs saisons : la saison suit les épisodes vus
const pos = seasonPosition({ episodesWatched: next, seasons: item.seasons })
if (pos && pos.season !== item.season) patch.season = pos.season
if (delta > 0 && (item.status === 'a_voir' || item.status === 'pause')) {
patch.status = 'en_cours'
if (!item.startDate) patch.startDate = todayISO()
+2
View File
@@ -24,6 +24,8 @@ export interface MediaItem {
episodesWatched: number
episodesTotal?: number
season?: number
/** Nombre d'épisodes de chaque saison (TMDB), ex. [24, 24]. Les épisodes vus restent comptés au total. */
seasons?: number[]
/** Durée d'un épisode en minutes (sinon valeur par défaut selon le type). */
episodeDuration?: number
/** Durée totale en minutes (films / formats uniques). */