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

+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
}