diff --git a/src/App.tsx b/src/App.tsx index 7246815..7eaee07 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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') diff --git a/src/components/CalendarView.tsx b/src/components/CalendarView.tsx index 4c47c8b..ee92a3b 100644 --- a/src/components/CalendarView.tsx +++ b/src/components/CalendarView.tsx @@ -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 = {} 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 diff --git a/src/components/DatabaseSearch.tsx b/src/components/DatabaseSearch.tsx index c97fe60..c1bbf7e 100644 --- a/src/components/DatabaseSearch.tsx +++ b/src/components/DatabaseSearch.tsx @@ -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(hasKey ? 'tmdb' : 'anilist') const [query, setQuery] = useState(initialQuery) const [results, setResults] = useState([]) const [loading, setLoading] = useState(false) @@ -33,13 +30,17 @@ export default function DatabaseSearch({ onPick, initialQuery = '', currentExter const [error, setError] = useState() 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
{t('search.fillFrom')} -
- {SOURCES.map((s) => ( - - ))} -
+ {t('search.allKinds')}
- {source === 'tmdb' && !hasKey ? ( -
- {t('search.needKey')} +
+ + setQuery(e.target.value)} + placeholder="Parasite, Frieren, Crash Landing on You…" + className="field pl-10" + enterKeyHint="search" + autoComplete="off" + /> + {loading && } +
+ + {!hasKey && ( +
+ {t('search.animeOnly')} {onGoToSettings && ( - )}
- ) : ( -
- - setQuery(e.target.value)} - placeholder={source === 'tmdb' ? 'Parasite, Crash Landing on You…' : 'Frieren, One Piece…'} - className="field pl-10" - enterKeyHint="search" - autoComplete="off" - /> - {loading && } -
)} {error &&

{error}

} @@ -127,7 +119,8 @@ export default function DatabaseSearch({ onPick, initialQuery = '', currentExter {results.length > 0 && (
    {results.map((r) => { - const already = existing.has(r.externalId) + const mine = inLibrary(r) + const already = !!mine return (
)} - {!loading && !error && query.trim().length >= 2 && results.length === 0 && !(source === 'tmdb' && !hasKey) && ( + {!loading && !error && query.trim().length >= 2 && results.length === 0 && (

{t('search.noResults')}

)}

- {t('search.privacy', { source: source === 'tmdb' ? 'TMDB' : 'AniList' })} + {t('search.privacy', { source: hasKey ? 'TMDB / AniList' : 'AniList' })}

) diff --git a/src/components/MediaCard.tsx b/src/components/MediaCard.tsx index 2100813..cc01140 100644 --- a/src/components/MediaCard.tsx +++ b/src/components/MediaCard.tsx @@ -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 (
- {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}` : ''}
- {item.episodesTotal ? ( + {size ? (
diff --git a/src/components/MediaForm.tsx b/src/components/MediaForm.tsx index 1fd131a..a315053 100644 --- a/src/components/MediaForm.tsx +++ b/src/components/MediaForm.tsx @@ -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 ( +
+ {t('form.season')} +
+ {seasons.map((size, k) => { + const n = k + 1 + const start = episodesBeforeSeason(seasons, n) + const done = watched >= start + size + const on = n === current.season + return ( + + ) + })} +
+
+ ) } /** « 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(() => { if (!item) return EMPTY @@ -142,10 +177,29 @@ export default function MediaForm({ item, onClose, onGoToSettings }: Props) { const fileRef = useRef(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 = (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)[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} /> ) : ( - {form.episodesWatched} - {form.episodesTotal ? /{form.episodesTotal} : null} + {pos ? pos.episode : form.episodesWatched} + {pos ? /{pos.size} : form.episodesTotal ? /{form.episodesTotal} : null}
+ {pos ? ( +
+

{t('form.seasonsTotal', { seasons: form.seasons!.length, count: form.episodesTotal ?? 0 })}

+
+ + set('episodeDuration', toNum(e.target.value))} placeholder={String(typeInfo.episodeMinutes)} /> + +
+
+ ) : (
set('episodesTotal', toNum(e.target.value))} placeholder="?" /> @@ -436,6 +508,7 @@ export default function MediaForm({ item, onClose, onGoToSettings }: Props) { set('episodeDuration', toNum(e.target.value))} placeholder={String(typeInfo.episodeMinutes)} />
+ )}
) : ( diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 470ad64..1b2724b 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -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 diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index ef6c8e3..d8559c9 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -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 diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 0153075..fcdf385 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -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 diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index aeb5b8a..1e5fa2f 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -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 diff --git a/src/i18n/locales/it.ts b/src/i18n/locales/it.ts index c05cd57..df3c547 100644 --- a/src/i18n/locales/it.ts +++ b/src/i18n/locales/it.ts @@ -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 diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts index 3730678..b719afd 100644 --- a/src/i18n/locales/ja.ts +++ b/src/i18n/locales/ja.ts @@ -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 diff --git a/src/i18n/locales/ko.ts b/src/i18n/locales/ko.ts index 7f6b720..e25e151 100644 --- a/src/i18n/locales/ko.ts +++ b/src/i18n/locales/ko.ts @@ -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 diff --git a/src/i18n/locales/pt.ts b/src/i18n/locales/pt.ts index fbd0c17..5f1dd94 100644 --- a/src/i18n/locales/pt.ts +++ b/src/i18n/locales/pt.ts @@ -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 diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index f3c0fa7..633d238 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -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 diff --git a/src/lib/airing.ts b/src/lib/airing.ts index c453054..8a1521a 100644 --- a/src/lib/airing.ts +++ b/src/lib/airing.ts @@ -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 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 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, } diff --git a/src/lib/backup.ts b/src/lib/backup.ts index b5ca367..cf56c89 100644 --- a/src/lib/backup.ts +++ b/src/lib/backup.ts @@ -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), diff --git a/src/lib/catalogApi.ts b/src/lib/catalogApi.ts index 486c4a5..ade69df 100644 --- a/src/lib/catalogApi.ts +++ b/src/lib/catalogApi.ts @@ -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 /** 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): Partial { 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 } @@ -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(`/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 { 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 { + 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() + 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 { + 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 { if (!isSafeExternalId(externalId) || !externalId.startsWith('anilist:')) return [] diff --git a/src/lib/franchise.ts b/src/lib/franchise.ts new file mode 100644 index 0000000..524c59e --- /dev/null +++ b/src/lib/franchise.ts @@ -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): 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) diff --git a/src/lib/security.ts b/src/lib/security.ts index 9e4f7de..03c8eb5 100644 --- a/src/lib/security.ts +++ b/src/lib/security.ts @@ -125,3 +125,10 @@ export function readStorage(key: string, fallback: T): unknown | T { /** Objet « simple » (pas un tableau, pas null). */ export const isPlainObject = (v: unknown): v is Record => 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 +} diff --git a/src/pages/HomePage.tsx b/src/pages/HomePage.tsx index cc4afc2..603beed 100644 --- a/src/pages/HomePage.tsx +++ b/src/pages/HomePage.tsx @@ -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 = {} + 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(() => {}) diff --git a/src/store.tsx b/src/store.tsx index 21dd254..9f11973 100644 --- a/src/store.tsx +++ b/src/store.tsx @@ -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 = { 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() diff --git a/src/types.ts b/src/types.ts index ea81038..d944ac7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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). */