Files
bobinoo/src/lib/catalogApi.ts
T
Claude ac27542947
deploy / deploy (push) Successful in 45s
Images d'épisodes et fiches affichées tout de suite
- Épisodes d'une saison gardés sur l'appareil (titres, dates, images) : la liste s'affiche dès l'ouverture, rafraîchie en arrière-plan après 12 h
- Images des épisodes autour du prochain à voir demandées tout de suite (plus en « paresseux ») et préchargées
- Préchargement au toucher d'une série en cours : saison en cours et images des épisodes suivants (data-prefetch-season / -ep)
- lazyPreload : un écran préchargé (fiche, stats, réglages, profils…) s'affiche sans l'attente d'environ 300 ms que React.lazy imposait à la première ouverture
- L'administration n'est plus préchargée pour tout le monde

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
2026-11-29 15:53:45 +00:00

1425 lines
63 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { MediaInput, MediaType } from '../types'
import { region, t, tmdbLanguage } from '../i18n'
import { ratingsViaCloud, tmdbViaCloud } from './cloud/api'
import { TYPE_BY_VALUE } from './constants'
import { subtypeLabel, tmdbGenres } from './genres'
import { franchiseKey } from './franchise'
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, remoteImage, safeCountries, safeDay, safePosterUrl, safeSeasons, safeStringList } from './security'
import { localDay } from './utils'
import { getWatchRegion, parseAniListLinks, parseTmdbProviders, type StreamLink, type WatchRegion } from './watchProviders'
/**
* Recherche dans les bases publiques :
* - TMDB : films, séries, K-dramas, C-dramas, documentaires… (clé API gratuite requise)
* - AniList : animes (aucune clé nécessaire)
* Seul le texte recherché est envoyé ; la bibliothèque reste sur l'appareil.
*/
export type Source = 'tmdb' | 'anilist'
export interface SearchResult {
source: Source
/** ex. « tmdb:movie:496243 », « tmdb:tv:1396 », « anilist:154587 » */
externalId: string
title: string
originalTitle?: string
year?: number
/** Petite image pour la liste de résultats */
thumb?: string
kindLabel: string
typeGuess: MediaType
/** Données déjà complètes (AniList) — sinon on va chercher le détail */
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 ───────────────────────────
const TYPES = new Set<MediaType>(['film', 'serie', 'anime', 'kdrama', 'cdrama', 'autre'])
const count = (n: unknown, max: number) => (typeof n === 'number' && Number.isFinite(n) && n > 0 ? Math.min(max, Math.round(n)) : undefined)
/** Les réponses des API sont non fiables : on borne et on filtre chaque champ. */
export function sanitizeMeta(d: Partial<MediaInput>): Partial<MediaInput> {
const genres = safeStringList(d.genres, LIMITS.genres)
return {
title: cleanText(d.title, LIMITS.title),
originalTitle: cleanText(d.originalTitle, LIMITS.title),
type: d.type && TYPES.has(d.type) ? d.type : undefined,
subtype: cleanText(d.subtype, LIMITS.shortText),
year: typeof d.year === 'number' && d.year >= 1870 && d.year <= 2200 ? Math.round(d.year) : undefined,
overview: cleanText(d.overview, LIMITS.overview),
genres: genres.length ? genres : undefined,
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),
poster: safePosterUrl(d.poster),
backdrop: remoteImage(d.backdrop),
publicRating:
typeof d.publicRating === 'number' && d.publicRating > 0 && d.publicRating <= 10 ? Math.round(d.publicRating * 10) / 10 : undefined,
}
}
/** Note TMDB sur 10, seulement s'il y a assez de votes pour qu'elle veuille dire quelque chose. */
export function tmdbPublicRating(avg?: number, count?: number): number | undefined {
return typeof avg === 'number' && avg > 0 && avg <= 10 && (count ?? 0) >= 20 ? Math.round(avg * 10) / 10 : undefined
}
function safeResult(r: SearchResult): SearchResult | null {
const title = cleanText(r.title, LIMITS.title)
if (!title || !isSafeExternalId(r.externalId)) return null
return {
...r,
title,
originalTitle: cleanText(r.originalTitle, LIMITS.title),
year: typeof r.year === 'number' && r.year >= 1870 && r.year <= 2200 ? r.year : undefined,
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,
}
}
// ─────────────────────────── TMDB ───────────────────────────
const TMDB = 'https://api.themoviedb.org/3'
const TMDB_IMG = 'https://image.tmdb.org/t/p'
interface TmdbItem {
id: number
media_type?: 'movie' | 'tv' | 'person'
title?: string
name?: string
original_title?: string
original_name?: string
release_date?: string
first_air_date?: string
poster_path?: string | null
genre_ids?: number[]
origin_country?: string[]
original_language?: string
vote_average?: number
vote_count?: number
popularity?: number
overview?: string
}
/** Clé v3 (32 caractères hexadécimaux) ou jeton de lecture v4 (JWT). */
export function isPlausibleTmdbKey(key: string): boolean {
const k = key.trim()
return /^[a-f0-9]{32}$/i.test(k) || /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(k)
}
/** Seules ces adresses de l'API TMDB peuvent être appelées. */
const TMDB_PATHS = /^\/(search\/(multi|person)|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?|find\/(tt)?\d{1,10}|person\/\d{1,10})$/
/** Délai max d'une requête vers TMDB / AniList (réseau lent ou serveur muet). */
const FETCH_TIMEOUT = 12_000
const timeout = () => AbortSignal.timeout(FETCH_TIMEOUT)
/** Texte recherché : sans caractères de contrôle, et pas plus long que ce qu'accepte le proxy (100 caractères). */
// eslint-disable-next-line no-control-regex
const searchText = (q: string) => q.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, 100)
/** « Clé » spéciale : avec un compte, les requêtes passent par le serveur qui détient la vraie clé TMDB. */
export const CLOUD_TMDB = 'cloud-proxy'
async function tmdbFetch<T>(path: string, key: string, params: Record<string, string> = {}): Promise<T> {
const k = key.trim()
if (!TMDB_PATHS.test(path)) throw new Error(t('err.tmdbRefused'))
if (typeof params.query === 'string') params = { ...params, query: searchText(params.query) }
if (k === CLOUD_TMDB) return tmdbViaCloud<T>(path, { language: tmdbLanguage(), ...params })
if (!isPlausibleTmdbKey(k)) throw new Error(t('err.tmdbKeyRefused'))
const isBearer = k.length > 40 // jeton de lecture v4 (JWT) vs clé v3 (32 caractères)
const url = new URL(TMDB + path)
url.searchParams.set('language', tmdbLanguage())
for (const [p, v] of Object.entries(params)) url.searchParams.set(p, v)
if (!isBearer) url.searchParams.set('api_key', k)
const res = await fetch(url, {
headers: isBearer ? { Authorization: `Bearer ${k}` } : {},
referrerPolicy: 'no-referrer',
credentials: 'omit',
signal: timeout(),
})
if (res.status === 401) throw new Error(t('err.tmdbKeyRefused'))
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
return res.json() as Promise<T>
}
const yearOf = (d?: string) => (d && /^\d{4}/.test(d) ? Number(d.slice(0, 4)) : undefined)
/** Devine le type Bobinoo à partir des métadonnées TMDB. */
function guessTmdbType(kind: 'movie' | 'tv', genreIds: number[], countries: string[], lang?: string): { type: MediaType; subtype?: string } {
const has = (c: string) => countries.includes(c)
if (genreIds.includes(99)) return { type: 'autre', subtype: 'Documentaire' }
if (kind === 'movie') return { type: 'film' }
if (genreIds.includes(10764)) return { type: 'autre', subtype: 'Télé-réalité' }
if (genreIds.includes(16) && (has('JP') || lang === 'ja')) return { type: 'anime' }
if (has('KR') || lang === 'ko') return { type: 'kdrama' }
if (has('CN') || has('TW') || has('HK') || lang === 'zh' || lang === 'cn') return { type: 'cdrama' }
return { type: 'serie' }
}
const kindLabel = (type: MediaType, subtype?: string) => (subtype ? subtypeLabel(subtype) : TYPE_BY_VALUE[type].label)
function tmdbToResult(r: TmdbItem, kind: 'movie' | 'tv'): SearchResult | null {
if (!Number.isInteger(r.id)) return null
const poster = isSafeTmdbPath(r.poster_path) ? r.poster_path : undefined
const guess = guessTmdbType(kind, r.genre_ids ?? [], r.origin_country ?? [], r.original_language)
const title = (kind === 'movie' ? r.title : r.name) ?? '?'
const original = kind === 'movie' ? r.original_title : r.original_name
return safeResult({
source: 'tmdb',
externalId: `tmdb:${kind}:${r.id}`,
title,
originalTitle: original && original !== title ? original : undefined,
year: yearOf(kind === 'movie' ? r.release_date : r.first_air_date),
thumb: poster ? `${TMDB_IMG}/w92${poster}` : undefined,
posterUrl: poster ? `${TMDB_IMG}/w342${poster}` : undefined,
kindLabel: kindLabel(guess.type, guess.subtype),
typeGuess: guess.type,
})
}
export async function searchTmdb(query: string, key: string): Promise<SearchResult[]> {
const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: searchText(query), include_adult: 'false' })
return (Array.isArray(data.results) ? data.results : [])
.filter((r) => r.media_type === 'movie' || r.media_type === 'tv')
.slice(0, 15)
.map((r) => tmdbToResult(r, r.media_type as 'movie' | 'tv'))
.filter((r): r is SearchResult => r !== null)
}
interface TmdbDetails {
title?: string
name?: string
original_title?: string
original_name?: string
overview?: string
runtime?: number
episode_run_time?: number[]
number_of_episodes?: number
number_of_seasons?: number
genres?: { id: number; name: string }[]
origin_country?: string[]
production_countries?: { iso_3166_1: string }[]
original_language?: string
release_date?: string
first_air_date?: string
poster_path?: string | null
backdrop_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 }[] }> }
}
const PROVIDER_NAMES: Record<string, string> = {
'Amazon Prime Video': 'Prime Video',
'Amazon Prime Video with Ads': 'Prime Video',
'Disney Plus': 'Disney+',
'Apple TV Plus': 'Apple TV+',
'Apple TV+': 'Apple TV+',
'Canal+ Séries': 'Canal+',
'Paramount Plus': 'Paramount+',
'Netflix Standard with Ads': 'Netflix',
'Netflix basic with Ads': 'Netflix',
'Rakuten Viki': 'Viki',
'Animation Digital Network': 'ADN',
}
const GENRE_ALIASES: Record<string, string> = {
'Science-Fiction': 'Sci-Fi',
'Science Fiction': 'Sci-Fi',
'Sci-Fi': 'Sci-Fi',
Adventure: 'Aventure',
Fantasy: 'Fantasy',
Fantastique: 'Fantasy',
War: 'Guerre',
Politics: 'Politique',
Kids: 'Enfants',
Musique: 'Musical',
Crime: 'Policier',
}
/**
* Découpe les genres combinés de TMDB (« Science-Fiction & Fantastique », « Action & Adventure »),
* harmonise les noms et retire les doublons.
*/
export function splitGenres(names: string[], keepAnimation = false): string[] {
const out = new Set<string>()
for (const n of names) {
for (const part of n.split('&')) {
const g = part.trim()
if (!g) continue
if (g === 'Animation' && !keepAnimation) continue // déjà exprimé par le type
out.add(GENRE_ALIASES[g] ?? g)
}
}
return [...out]
}
export async function getTmdbDetails(result: SearchResult, key: string): Promise<Partial<MediaInput>> {
if (!isSafeExternalId(result.externalId) || !result.externalId.startsWith('tmdb:')) throw new Error(t('err.tmdbRef'))
const [, kind, id] = result.externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const d = await tmdbFetch<TmdbDetails>(`/${kind}/${id}`, key, { append_to_response: 'watch/providers' })
const guess = guessTmdbType(kind, (d.genres ?? []).map((g) => g.id), d.origin_country ?? [], d.original_language)
const providers = d['watch/providers']?.results
// Même pays que « Où regarder » (choisi à la main, sinon celui du navigateur)
const provider = (providers?.[getWatchRegion()] ?? providers?.FR)?.flatrate?.[0]?.provider_name
const title = (kind === 'movie' ? d.title : d.name) ?? result.title
const original = kind === 'movie' ? d.original_title : d.original_name
const epRuntime = d.episode_run_time?.[0] || d.last_episode_to_air?.runtime || undefined
return sanitizeMeta({
title,
originalTitle: original && original !== title ? original : undefined,
type: guess.type,
subtype: guess.subtype,
year: yearOf(kind === 'movie' ? d.release_date : d.first_air_date),
overview: d.overview || undefined,
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' ? Math.max(d.number_of_episodes || 0, sumSeasons(tmdbSeasons(d))) || undefined : undefined,
seasons: kind === 'tv' ? tmdbSeasons(d) : undefined,
backdrop: tmdbBackdrop(d.backdrop_path),
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),
publicRating: tmdbPublicRating(d.vote_average, d.vote_count),
})
}
/** É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)
const tmdbBackdrop = (path?: string | null) => (isSafeTmdbPath(path) ? `${TMDB_IMG}/w780${path}` : undefined)
/** Grande image et saisons d'un titre déjà dans la bibliothèque (fiches ajoutées avant ces nouveautés). */
export async function getTmdbExtras(externalId: string, key: string): Promise<{ seasons?: number[]; total?: number; backdrop?: string }> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:')) return {}
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const d = await tmdbFetch<TmdbDetails>(`/${kind}/${id}`, key)
const seasons = kind === 'tv' ? tmdbSeasons(d) : undefined
return {
seasons,
total: kind === 'tv' ? Math.max(d.number_of_episodes || 0, sumSeasons(seasons)) || undefined : undefined,
backdrop: tmdbBackdrop(d.backdrop_path),
}
}
export interface EpisodeInfo {
number: number
name?: string
still?: string
date?: string
runtime?: number
}
// Épisodes d'une saison gardés sur l'appareil : la liste (titres, dates, images) s'affiche dès l'ouverture
// de la fiche, puis est rafraîchie en arrière-plan si elle date de plus de 12 h (nouveaux épisodes, images)
const SEASONS_KEY = 'azuucine:seasons'
const SEASONS_FRESH = 12 * 3600_000
const SEASONS_MAX_AGE = 30 * 24 * 3600_000
const SEASONS_BUDGET = 400_000
type SeasonEntry = { at: number; eps: EpisodeInfo[] }
let seasonsMem: Map<string, SeasonEntry> | undefined
let seasonsSave: ReturnType<typeof setTimeout> | undefined
const seasonsInflight = new Map<string, Promise<EpisodeInfo[]>>()
function toEpisode(v: unknown): EpisodeInfo | null {
if (!Array.isArray(v)) return null
const [number, name, still, date, runtime] = v as unknown[]
if (typeof number !== 'number' || !Number.isInteger(number) || number < 1) return null
return {
number,
name: typeof name === 'string' ? cleanText(name, LIMITS.title) : undefined,
still: typeof still === 'string' && isSafeTmdbPath(still) ? `${TMDB_IMG}/w300${still}` : undefined,
date: typeof date === 'string' ? safeDay(date) : undefined,
runtime: typeof runtime === 'number' && runtime > 0 && runtime < 1000 ? runtime : undefined,
}
}
function seasonsStore(): Map<string, SeasonEntry> {
if (seasonsMem) return seasonsMem
seasonsMem = new Map()
try {
const raw = JSON.parse(localStorage.getItem(SEASONS_KEY) ?? '{}') as Record<string, unknown>
const now = Date.now()
for (const [k, v] of Object.entries(raw ?? {})) {
const e = v as { at?: unknown; eps?: unknown }
if (!/^tmdb:tv:\d{1,10}:\d{1,3}:[a-z]{2}(-[A-Z]{2})?$/.test(k) || typeof e?.at !== 'number' || now - e.at > SEASONS_MAX_AGE || !Array.isArray(e.eps)) continue
seasonsMem.set(k, { at: e.at, eps: e.eps.map(toEpisode).filter((x): x is EpisodeInfo => !!x) })
}
} catch {
/* copie illisible ou stockage bloqué : on repart de zéro */
}
return seasonsMem
}
function saveSeasons() {
clearTimeout(seasonsSave)
seasonsSave = setTimeout(() => {
try {
// Les plus récentes d'abord ; on s'arrête avant de dépasser le budget (le stockage sert aussi au reste de l'app)
const out: Record<string, unknown> = {}
let size = 2
for (const [k, { at, eps }] of [...seasonsStore().entries()].sort((a, b) => b[1].at - a[1].at)) {
const value = { at, eps: eps.map((e) => [e.number, e.name ?? null, e.still ? e.still.replace(`${TMDB_IMG}/w300`, '') : null, e.date ?? null, e.runtime ?? null]) }
const piece = JSON.stringify(value).length + k.length + 4
if (size + piece > SEASONS_BUDGET) break
out[k] = value
size += piece
}
localStorage.setItem(SEASONS_KEY, JSON.stringify(out))
} catch {
/* stockage plein ou bloqué : la liste sera simplement redemandée */
}
}, 800)
}
const seasonKey = (externalId: string, season: number) => `${externalId}:${season}:${tmdbLanguage()}`
/** Épisodes d'une saison déjà connus sur l'appareil (affichage immédiat), même anciens. */
export function cachedSeasonEpisodes(externalId: string | undefined, season: number): EpisodeInfo[] | undefined {
return externalId?.startsWith('tmdb:tv:') ? seasonsStore().get(seasonKey(externalId, season))?.eps : undefined
}
/** Épisodes d'une saison (titre, image, date de diffusion), gardés sur l'appareil. */
export async function getTmdbSeasonEpisodes(externalId: string, season: number, key: string): Promise<EpisodeInfo[]> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:tv:') || !Number.isInteger(season) || season < 1 || season > 999) return []
const cacheKey = seasonKey(externalId, season)
const hit = seasonsStore().get(cacheKey)
if (hit && Date.now() - hit.at < SEASONS_FRESH) return hit.eps
let p = seasonsInflight.get(cacheKey)
if (!p) {
p = tmdbFetch<{ episodes?: { episode_number?: number; name?: string; still_path?: string | null; air_date?: string; runtime?: number }[] }>(
`/tv/${externalId.split(':')[2]}/season/${season}`,
key,
)
.then((d) => {
const list = (Array.isArray(d.episodes) ? d.episodes : [])
.filter((e) => Number.isInteger(e.episode_number) && e.episode_number! > 0)
.slice(0, 1000)
.map((e) => ({
number: e.episode_number!,
name: cleanText(e.name, LIMITS.title),
still: isSafeTmdbPath(e.still_path) ? `${TMDB_IMG}/w300${e.still_path}` : undefined,
date: safeDay(e.air_date),
runtime: typeof e.runtime === 'number' && e.runtime > 0 && e.runtime < 1000 ? Math.round(e.runtime) : undefined,
}))
seasonsStore().set(cacheKey, { at: Date.now(), eps: list })
saveSeasons()
return list
})
.finally(() => seasonsInflight.delete(cacheKey))
seasonsInflight.set(cacheKey, p)
}
return p
}
// Images déjà demandées pendant cette session (préchargement)
const preloaded = new Set<string>()
/** Fait télécharger des images à l'avance (le service worker les garde) : elles s'affichent sans attendre. */
export function preloadImages(urls: (string | undefined)[]): void {
for (const url of urls) {
if (!url || preloaded.has(url)) continue
if (preloaded.size > 500) preloaded.clear()
preloaded.add(url)
const img = new Image()
img.decoding = 'async'
img.referrerPolicy = 'no-referrer'
img.src = url
}
}
/** Images des épisodes autour du prochain à voir (ceux qu'on voit en ouvrant la fiche). */
export function episodeWindow(list: EpisodeInfo[], nextEpisode: number): EpisodeInfo[] {
const from = Math.max(1, nextEpisode - 2)
return list.filter((e) => e.number >= from && e.number < from + 8)
}
// ─────────────────────────── AniList ───────────────────────────
const ANILIST = 'https://graphql.anilist.co'
const ANILIST_FIELDS = `
id
format
episodes
duration
genres
seasonYear
startDate { year }
title { romaji english native }
coverImage { medium large }
countryOfOrigin
averageScore
description(asHtml: false)`
const ANILIST_QUERY = `
query ($search: String) {
Page(perPage: 15) {
media(search: $search, type: ANIME, sort: SEARCH_MATCH, isAdult: false) {${ANILIST_FIELDS}
}
}
}`
interface AniMedia {
id: number
format?: string | null
episodes?: number | null
duration?: number | null
genres?: string[]
seasonYear?: number | null
startDate?: { year?: number | null }
title?: { romaji?: string | null; english?: string | null; native?: string | null } | null
coverImage?: { medium?: string | null; large?: string | null }
description?: string | null
countryOfOrigin?: string | null
averageScore?: number | null
/** Demandé seulement par certaines requêtes (recommandations, fiche par id) */
isAdult?: boolean
}
const ANILIST_GENRES: Record<string, string> = {
Action: 'Action',
Adventure: 'Aventure',
Comedy: 'Comédie',
Drama: 'Drame',
Ecchi: 'Ecchi',
Fantasy: 'Fantasy',
Horror: 'Horreur',
'Mahou Shoujo': 'Magical Girl',
Mecha: 'Mecha',
Music: 'Musical',
Mystery: 'Mystère',
Psychological: 'Psychologique',
Romance: 'Romance',
'Sci-Fi': 'Sci-Fi',
'Slice of Life': 'Slice of Life',
Sports: 'Sport',
Supernatural: 'Surnaturel',
Thriller: 'Thriller',
}
const aniFormat = (f?: string | null): string =>
f === 'TV_SHORT' ? t('anilist.short') : f === 'MOVIE' ? t('anilist.movie') : f === 'SPECIAL' ? t('anilist.special') : f === 'MUSIC' ? t('anilist.music') : f === 'OVA' || f === 'ONA' ? f : t('type.anime')
function cleanDescription(html?: string | null): string | undefined {
if (!html) return undefined
return html
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<[^>]+>/g, '')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
export async function searchAniList(query: string): Promise<SearchResult[]> {
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query: ANILIST_QUERY, variables: { search: query.slice(0, LIMITS.searchQuery) } }),
referrerPolicy: 'no-referrer',
credentials: 'omit',
signal: timeout(),
})
if (res.status === 429) throw new Error(t('err.anilistRate'))
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Page?: { media?: AniMedia[] } } }
const list = Array.isArray(json.data?.Page?.media) ? json.data!.Page!.media! : []
return list.map(aniToResult).filter((r): r is SearchResult => r !== null)
}
function aniToResult(m: AniMedia): SearchResult | null {
if (!m || !Number.isInteger(m.id)) return null
const isMovie = m.format === 'MOVIE'
const title = m.title?.english || m.title?.romaji || m.title?.native || '?'
const original = m.title?.native || m.title?.romaji || undefined
const year = m.seasonYear ?? m.startDate?.year ?? undefined
const type: MediaType = isMovie ? 'film' : 'anime'
return safeResult({
source: 'anilist' as const,
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,
kindLabel: aniFormat(m.format),
typeGuess: type,
prefill: {
title,
originalTitle: original && original !== title ? original : undefined,
type,
year: year ?? undefined,
overview: cleanDescription(m.description),
genres: [...(isMovie ? ['Anime'] : []), ...(m.genres ?? []).map((g) => ANILIST_GENRES[g] ?? g)],
episodesTotal: isMovie ? undefined : (m.episodes ?? undefined),
episodeDuration: isMovie ? undefined : (m.duration ?? undefined),
duration: isMovie ? (m.duration ?? undefined) : undefined,
externalId: `anilist:${m.id}`,
countries: m.countryOfOrigin ? [m.countryOfOrigin] : undefined,
publicRating: typeof m.averageScore === 'number' && m.averageScore > 0 ? m.averageScore / 10 : undefined,
},
})
}
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
}
// ─────────────────────────── Générique (pour les affiches partagées) ───────────────────────────
export interface Credits {
/** Réalisateur·rices (films) ou créateur·rices (séries) */
directors: string[]
producers: string[]
cast: string[]
runtime?: number
/** Image de scène (paysage) en haute définition, sinon l'affiche en HD */
image?: string
}
interface TmdbCredits {
runtime?: number
backdrop_path?: string | null
poster_path?: string | null
created_by?: { name?: string }[]
credits?: {
cast?: { name?: string; order?: number }[]
crew?: { name?: string; job?: string }[]
}
}
const names = (list: (string | undefined)[], max: number) =>
[...new Set(list.map((n) => cleanText(n, 60)).filter((n): n is string => !!n))].slice(0, max)
const tmdbPersonId = (id: unknown) => (typeof id === 'number' && Number.isInteger(id) && id > 0 && id < 1e10 ? `tmdbp:${id}` : undefined)
const aniPersonId = (id: unknown) => (typeof id === 'number' && Number.isInteger(id) && id > 0 && id < 1e10 ? `anilistp:${id}` : undefined)
/** Noms + pages des personnes (sans doublon, 3 au plus). */
function crewRefs(list: { id?: number; name?: string }[], toId: (id: unknown) => string | undefined): CrewRef[] {
const out: CrewRef[] = []
for (const c of list) {
const name = cleanText(c.name, 60)
if (!name || out.some((o) => o.name === name)) continue
out.push({ name, personId: toId(c.id) })
if (out.length >= 3) break
}
return out
}
/** Réalisation, production et casting principal depuis TMDB. */
export async function getTmdbCredits(externalId: string, key: string): Promise<Credits | undefined> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:')) return undefined
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const d = await tmdbFetch<TmdbCredits>(`/${kind}/${id}`, key, { append_to_response: 'credits' })
const crew = Array.isArray(d.credits?.crew) ? d.credits!.crew! : []
const cast = Array.isArray(d.credits?.cast) ? d.credits!.cast! : []
return {
directors:
kind === 'movie'
? names(crew.filter((c) => c.job === 'Director').map((c) => c.name), 2)
: names((Array.isArray(d.created_by) ? d.created_by : []).map((c) => c.name), 2),
producers: names(crew.filter((c) => c.job === 'Producer').map((c) => c.name), 3),
cast: names([...cast].sort((a, b) => (a.order ?? 99) - (b.order ?? 99)).map((c) => c.name), 4),
runtime: typeof d.runtime === 'number' && d.runtime > 0 && d.runtime < 6000 ? Math.round(d.runtime) : undefined,
image: isSafeTmdbPath(d.backdrop_path)
? `${TMDB_IMG}/w1280${d.backdrop_path}`
: isSafeTmdbPath(d.poster_path)
? `${TMDB_IMG}/w780${d.poster_path}`
: undefined,
}
}
// ─────────────────────────── Dates de sortie (calendrier) ───────────────────────────
export interface ReleaseInfo {
date: string // AAAA-MM-JJ
label: string
}
interface TmdbReleaseDetails {
release_date?: string
first_air_date?: string
next_episode_to_air?: { air_date?: string; episode_number?: number; season_number?: number } | null
release_dates?: { results?: { iso_3166_1?: string; release_dates?: { release_date?: string; type?: number }[] }[] }
}
const day = (v?: string) => (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v) ? v.slice(0, 10) : undefined)
/** Prochaine date utile pour un titre « à voir » : sortie ciné en France, sortie en ligne, 1er épisode… */
export async function getTmdbRelease(externalId: string, key: string): Promise<ReleaseInfo | undefined> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:')) return undefined
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
if (kind === 'movie') {
const d = await tmdbFetch<TmdbReleaseDetails>(`/movie/${id}`, key, { append_to_response: 'release_dates' })
const results = Array.isArray(d.release_dates?.results) ? d.release_dates!.results! : []
const local = results.find((r) => r.iso_3166_1 === region())?.release_dates ?? []
const pick = (type: number) => day(local.filter((r) => r.type === type).map((r) => r.release_date ?? '').sort()[0])
const cinema = pick(3) ?? pick(2)
const online = pick(4)
const today = localDay()
if (cinema && cinema >= today) return { date: cinema, label: t('release.cinema') }
if (online && online >= today) return { date: online, label: t('release.online') }
const primary = day(d.release_date)
return cinema ? { date: cinema, label: t('release.cinema') } : primary ? { date: primary, label: t('release.release') } : undefined
}
const d = await tmdbFetch<TmdbReleaseDetails>(`/tv/${id}`, key)
const nx = d.next_episode_to_air
const nextDay = day(nx?.air_date)
if (nextDay) {
const ep = Number.isInteger(nx?.episode_number) ? nx!.episode_number! : undefined
const season = Number.isInteger(nx?.season_number) ? nx!.season_number! : undefined
return { date: nextDay, label: ep === 1 && season ? t('release.season', { season }) : ep ? t('release.episode', { ep }) : t('release.newEpisode') }
}
const first = day(d.first_air_date)
return first ? { date: first, label: t('release.firstEpisode') } : undefined
}
/** Dates de sortie AniList (1er épisode ou prochain épisode) pour plusieurs animes. */
export async function getAniListReleases(ids: number[]): Promise<Map<number, ReleaseInfo>> {
const out = new Map<number, ReleaseInfo>()
const clean = ids.filter((n) => Number.isInteger(n) && n > 0).slice(0, 500)
for (let i = 0; i < clean.length; i += 50) {
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer',
credentials: 'omit',
signal: timeout(),
body: JSON.stringify({
query:
'query ($ids: [Int]) { Page(perPage: 50) { media(id_in: $ids, type: ANIME) { id startDate { year month day } nextAiringEpisode { episode airingAt } } } }',
variables: { ids: clean.slice(i, i + 50) },
}),
})
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
type M = { id: number; startDate?: { year?: number; month?: number; day?: number }; nextAiringEpisode?: { episode?: number; airingAt?: number } | null }
const json = (await res.json()) as { data?: { Page?: { media?: M[] } } }
const media = json.data?.Page?.media
for (const m of Array.isArray(media) ? media : []) {
if (!Number.isInteger(m?.id)) continue
const nx = m.nextAiringEpisode
if (nx && typeof nx.airingAt === 'number' && nx.airingAt > 0 && nx.airingAt < 4102444800) {
out.set(m.id, { date: localDay(new Date(nx.airingAt * 1000)), label: nx.episode === 1 ? t('release.firstEpisode') : nx.episode ? t('release.episode', { ep: nx.episode }) : t('release.newEpisode') })
} else if (m.startDate?.year && m.startDate.month && m.startDate.day) {
const d = `${m.startDate.year}-${String(m.startDate.month).padStart(2, '0')}-${String(m.startDate.day).padStart(2, '0')}`
if (day(d)) out.set(m.id, { date: d, label: t('release.firstEpisode') })
}
}
}
return out
}
// ─────────────────────────── Sorties globales (calendrier) ───────────────────────────
export type ReleaseCategory = 'film' | 'serie' | 'anime' | 'kdrama' | 'cdrama'
/** Une sortie (film au cinéma ou épisode) venant des bases publiques, pas forcément dans ma bibliothèque. */
export interface GlobalRelease {
date: string // AAAA-MM-JJ (heure locale)
externalId: string
title: string
originalTitle?: string
year?: number
poster?: string
label: string
cat: ReleaseCategory
/** Popularité normalisée 0–100, pour trier les sorties d'un même jour */
pop: number
/** Vraie nouveauté : film qui sort, nouvelle série ou nouvelle saison (épisode 1) */
premiere?: boolean
}
function safeRelease(r: GlobalRelease): GlobalRelease | null {
const title = cleanText(r.title, LIMITS.title)
const date = day(r.date)
if (!title || !date || !isSafeExternalId(r.externalId)) return null
return {
date,
externalId: r.externalId,
title,
originalTitle: cleanText(r.originalTitle, LIMITS.title),
year: typeof r.year === 'number' && r.year >= 1870 && r.year <= 2200 ? r.year : undefined,
poster: safePosterUrl(r.poster),
label: cleanText(r.label, 40) ?? '',
cat: r.cat,
pop: Math.max(0, Math.min(100, Math.round(r.pop || 0))),
premiere: r.premiere === true || undefined,
}
}
export { safeRelease }
const popScore = (p?: number) => (typeof p === 'number' && p > 0 ? Math.min(100, Math.log10(p + 1) * 30) : 0)
/** Films qui sortent au cinéma en France entre deux dates (les plus attendus d'abord). */
export async function tmdbMovieReleases(key: string, from: string, to: string, pages = 2): Promise<GlobalRelease[]> {
const out: GlobalRelease[] = []
const toCheck: TmdbItem[] = []
for (let page = 1; page <= pages; page++) {
const data = await tmdbFetch<{ results?: TmdbItem[]; total_pages?: number }>('/discover/movie', key, {
region: region(),
'release_date.gte': from,
'release_date.lte': to,
with_release_type: '2|3',
sort_by: 'popularity.desc',
include_adult: 'false',
page: String(page),
})
for (const r of Array.isArray(data.results) ? data.results : []) {
if (!Number.isInteger(r.id) || (r.genre_ids ?? []).includes(99)) continue
const primary = day(r.release_date)
if (primary && primary >= from && primary <= to) out.push(movieRelease(r, primary))
else toCheck.push(r)
}
if ((data.total_pages ?? 1) <= page) break
}
// Date de sortie française quand elle diffère de la date mondiale
for (let k = 0; k < Math.min(toCheck.length, 24); k += 4) {
await Promise.all(
toCheck.slice(k, k + 4).map(async (r) => {
try {
const info = await getTmdbRelease(`tmdb:movie:${r.id}`, key)
if (info && info.date >= from && info.date <= to) out.push(movieRelease(r, info.date))
} catch {
/* ignore ce film */
}
}),
)
}
return out.map(safeRelease).filter((x): x is GlobalRelease => !!x)
}
function movieRelease(r: TmdbItem, date: string): GlobalRelease {
const poster = isSafeTmdbPath(r.poster_path) ? `${TMDB_IMG}/w342${r.poster_path}` : undefined
return {
date,
externalId: `tmdb:movie:${r.id}`,
title: r.title ?? '?',
originalTitle: r.original_title !== r.title ? r.original_title : undefined,
year: yearOf(r.release_date),
poster,
label: t('release.cinema'),
cat: 'film',
pop: popScore(r.popularity),
premiere: true,
}
}
const TV_FILTERS: Record<'serie' | 'kdrama' | 'cdrama', { countries: string; shows: number }> = {
serie: { countries: 'US|GB|FR|CA|AU|IE|NZ|ES|DE|IT|BE|SE|DK|NO', shows: 20 },
kdrama: { countries: 'KR', shows: 12 },
cdrama: { countries: 'CN|TW|HK', shows: 12 },
}
interface TmdbEpisode {
air_date?: string
episode_number?: number
season_number?: number
}
/** Épisodes des séries populaires (ou K-dramas / C-dramas) diffusés entre deux dates. */
export async function tmdbEpisodeReleases(
key: string,
cat: 'serie' | 'kdrama' | 'cdrama',
from: string,
to: string,
): Promise<GlobalRelease[]> {
const f = TV_FILTERS[cat]
const data = await tmdbFetch<{ results?: TmdbItem[] }>('/discover/tv', key, {
'air_date.gte': from,
'air_date.lte': to,
with_origin_country: f.countries,
without_genres: '16|10763|10764|10767',
sort_by: 'popularity.desc',
include_adult: 'false',
})
const shows = (Array.isArray(data.results) ? data.results : []).filter((r) => Number.isInteger(r.id)).slice(0, f.shows)
const out: GlobalRelease[] = []
for (let k = 0; k < shows.length; k += 4) {
await Promise.all(
shows.slice(k, k + 4).map(async (show) => {
try {
const d = await tmdbFetch<{ next_episode_to_air?: TmdbEpisode | null; last_episode_to_air?: TmdbEpisode | null }>(`/tv/${show.id}`, key)
const seasons = new Set<number>()
for (const e of [d.last_episode_to_air, d.next_episode_to_air]) {
const dd = day(e?.air_date)
if (e && Number.isInteger(e.season_number) && e.season_number! > 0 && dd && dd >= shiftDay(from, -120)) seasons.add(e.season_number!)
}
for (const n of [...seasons].slice(0, 2)) {
const season = await tmdbFetch<{ episodes?: TmdbEpisode[] }>(`/tv/${show.id}/season/${n}`, key)
// Regroupe les épisodes sortis le même jour (séries mises en ligne d'un bloc)
const byDay = new Map<string, number[]>()
for (const e of Array.isArray(season.episodes) ? season.episodes : []) {
const dd = day(e.air_date)
if (!dd || dd < from || dd > to || !Number.isInteger(e.episode_number)) continue
byDay.set(dd, [...(byDay.get(dd) ?? []), e.episode_number!])
}
for (const [date, eps] of byDay) out.push(episodeRelease(show, cat, date, n, eps))
}
} catch {
/* ignore cette série */
}
}),
)
}
return out.map(safeRelease).filter((x): x is GlobalRelease => !!x)
}
function shiftDay(d: string, days: number) {
const x = new Date(d + 'T12:00:00')
x.setDate(x.getDate() + days)
return localDay(x)
}
function episodeLabel(season: number | undefined, eps: number[]): string {
const sorted = [...eps].sort((a, b) => a - b)
const first = sorted[0]
const last = sorted[sorted.length - 1]
if (first === 1 && season === 1) return sorted.length > 1 ? t('release.newSeriesN', { count: sorted.length }) : t('release.firstEpisode')
if (first === 1) return sorted.length > 1 ? t('release.seasonN', { season: season ?? 1, count: sorted.length }) : t('release.seasonEp1', { season: season ?? 1 })
if (!season) return sorted.length > 1 ? t('release.episodes', { first, last }) : t('release.episode', { ep: first })
return sorted.length > 1 ? t('release.sEpisodes', { season, first, last }) : t('release.sEpisode', { season, ep: first })
}
function episodeRelease(show: TmdbItem, cat: ReleaseCategory, date: string, season: number, eps: number[]): GlobalRelease {
return {
date,
externalId: `tmdb:tv:${show.id}`,
title: show.name ?? '?',
originalTitle: show.original_name !== show.name ? show.original_name : undefined,
year: yearOf(show.first_air_date),
poster: isSafeTmdbPath(show.poster_path) ? `${TMDB_IMG}/w342${show.poster_path}` : undefined,
label: episodeLabel(season, eps),
cat,
pop: popScore(show.popularity),
premiere: eps.includes(1),
}
}
/** Tous les épisodes d'anime diffusés entre deux dates (AniList, sans clé). */
export async function aniListAiring(from: string, to: string, minPopularity = 4000): Promise<GlobalRelease[]> {
const start = Math.floor(new Date(from + 'T00:00:00').getTime() / 1000) - 1
const end = Math.floor(new Date(to + 'T23:59:59').getTime() / 1000) + 1
type S = {
airingAt?: number
episode?: number
media?: {
id?: number
title?: { romaji?: string | null; english?: string | null; native?: string | null }
coverImage?: { large?: string | null; medium?: string | null }
popularity?: number
isAdult?: boolean
countryOfOrigin?: string
format?: string
episodes?: number | null
seasonYear?: number | null
}
}
const byKey = new Map<string, { s: S; eps: number[] }>()
for (let page = 1; page <= 12; page++) {
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer',
credentials: 'omit',
signal: timeout(),
body: JSON.stringify({
query: `query ($start: Int, $end: Int, $page: Int) { Page(page: $page, perPage: 50) { pageInfo { hasNextPage }
airingSchedules(airingAt_greater: $start, airingAt_lesser: $end, sort: TIME) { airingAt episode
media { id title { romaji english native } coverImage { large medium } popularity isAdult countryOfOrigin format episodes seasonYear } } } }`,
variables: { start, end, page },
}),
})
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Page?: { pageInfo?: { hasNextPage?: boolean }; airingSchedules?: S[] } } }
const list = json.data?.Page?.airingSchedules
for (const s of Array.isArray(list) ? list : []) {
const m = s.media
if (!m || !Number.isInteger(m.id) || m.isAdult || m.countryOfOrigin !== 'JP' || (m.popularity ?? 0) < minPopularity) continue
if (typeof s.airingAt !== 'number' || !Number.isInteger(s.episode)) continue
const date = localDay(new Date(s.airingAt * 1000))
const k = `${m.id}|${date}`
const cur = byKey.get(k)
if (cur) cur.eps.push(s.episode!)
else byKey.set(k, { s, eps: [s.episode!] })
}
if (!json.data?.Page?.pageInfo?.hasNextPage) break
}
const out: GlobalRelease[] = []
for (const [k, { s, eps }] of byKey) {
const m = s.media!
const sorted = eps.sort((a, b) => a - b)
const total = Number.isInteger(m.episodes) ? m.episodes! : undefined
const isFinal = total != null && sorted[sorted.length - 1] === total
const label =
m.format === 'MOVIE'
? t('release.filmJapan')
: sorted[0] === 1
? t('release.firstEpisode')
: sorted.length > 1
? t('release.episodes', { first: sorted[0], last: sorted[sorted.length - 1] })
: isFinal
? t('release.episodeFinal', { ep: sorted[0] })
: t('release.episode', { ep: sorted[0] })
out.push({
date: k.split('|')[1],
externalId: `anilist:${m.id}`,
title: m.title?.english || m.title?.romaji || m.title?.native || '?',
originalTitle: m.title?.romaji || undefined,
year: m.seasonYear ?? undefined,
poster: m.coverImage?.large ?? m.coverImage?.medium ?? undefined,
label,
cat: 'anime',
pop: popScore(m.popularity) - 20,
premiere: m.format === 'MOVIE' || sorted[0] === 1,
})
}
return out.map(safeRelease).filter((x): x is GlobalRelease => !!x)
}
/** Fiche AniList complète à partir de son identifiant (ajout depuis le calendrier). */
export async function getAniListById(externalId: string): Promise<SearchResult | null> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('anilist:')) return null
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer',
credentials: 'omit',
signal: timeout(),
body: JSON.stringify({
query: `query ($id: Int) { Media(id: $id, type: ANIME) { isAdult ${ANILIST_FIELDS} } }`,
variables: { id: Number(externalId.split(':')[1]) },
}),
})
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Media?: AniMedia } }
const m = json.data?.Media
return m && !m.isAdult ? aniToResult(m) : null
}
/** Résultat « recherche » TMDB minimal à partir d'une sortie (pour l'ajout rapide). */
export function releaseToResult(r: GlobalRelease): SearchResult | null {
if (!r.externalId.startsWith('tmdb:')) return null
const type: MediaType = r.cat
return safeResult({
source: 'tmdb',
externalId: r.externalId,
title: r.title,
originalTitle: r.originalTitle,
year: r.year,
thumb: r.poster,
posterUrl: r.poster,
kindLabel: kindLabel(type),
typeGuess: type,
})
}
// ─────────────────────────── Fiche détaillée (note moyenne, casting) ───────────────────────────
export interface CastMember {
name: string
/** Personnage joué */
role?: string
photo?: string
/** Doubleur·se (animes) */
voice?: string
/** Page de la personne (acteur·rice, ou doubleur·se pour les animes) : « tmdbp:123 » / « anilistp:123 » */
personId?: string
}
/** Personne de l'équipe (réalisation, création) avec sa page. */
export interface CrewRef {
name: string
personId?: string
}
export interface TitleExtras {
/** Image de scène (paysage) */
backdrop?: string
/** Note moyenne du public, sur 10 */
average?: number
votes?: number
/** Répartition des notes du public (AniList) : note sur 10 → nombre de votes. Films et séries : voir getPublicRatings (Trakt) */
distribution?: { score: number; amount: number }[]
cast: CastMember[]
/** Réalisation (films) ou création (séries) */
directors: string[]
/** Les mêmes, avec de quoi ouvrir leur page */
directorPeople?: CrewRef[]
directorKind: 'director' | 'creator'
tagline?: string
runtime?: number
seasons?: number
/** Où regarder, par pays (TMDB / JustWatch). Absent = inconnu (ex. proxy pas encore à jour). */
watch?: Record<string, WatchRegion>
/** Liens directs vers les plateformes de streaming (AniList) */
streaming?: StreamLink[]
}
interface TmdbExtras {
vote_average?: number
vote_count?: number
backdrop_path?: string | null
tagline?: string
runtime?: number
episode_run_time?: number[]
number_of_seasons?: number
created_by?: { id?: number; name?: string }[]
credits?: {
cast?: { id?: number; name?: string; character?: string; profile_path?: string | null; order?: number }[]
crew?: { id?: number; name?: string; job?: string }[]
}
'watch/providers'?: unknown
}
const extrasCache = new Map<string, Promise<TitleExtras>>()
async function tmdbExtras(externalId: string, key: string): Promise<TitleExtras> {
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
// Une seule requête pour le casting et « Où regarder ». Si le proxy n'accepte pas encore la combinaison
// (fonction serveur pas redéployée), on retombe sur le casting seul.
const d = await tmdbFetch<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits,watch/providers' }).catch((e: unknown) => {
// Seul un refus du paramètre (400) justifie le second essai : hors ligne, 429, 5xx… on ne double pas la requête
if (key.trim() !== CLOUD_TMDB || !(e instanceof Error) || e.message !== t('err.tmdbStatus', { status: 400 })) throw e
return tmdbFetch<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits' })
})
const cast = (Array.isArray(d.credits?.cast) ? d.credits!.cast! : [])
.slice()
.sort((a, b) => (a.order ?? 99) - (b.order ?? 99))
.slice(0, 20)
.map((c): Partial<CastMember> => ({
name: cleanText(c.name, 60),
role: cleanText(c.character, 80),
photo: isSafeTmdbPath(c.profile_path) ? `${TMDB_IMG}/w185${c.profile_path}` : undefined,
personId: tmdbPersonId(c.id),
}))
.filter((c): c is CastMember => !!c.name)
const crew = Array.isArray(d.credits?.crew) ? d.credits!.crew! : []
const votes = count(d.vote_count, 100_000_000)
return {
backdrop: isSafeTmdbPath(d.backdrop_path) ? `${TMDB_IMG}/w780${d.backdrop_path}` : undefined,
average: tmdbPublicRating(d.vote_average, d.vote_count),
votes,
cast,
directors:
kind === 'movie'
? names(crew.filter((c) => c.job === 'Director').map((c) => c.name), 3)
: names((Array.isArray(d.created_by) ? d.created_by : []).map((c) => c.name), 3),
directorPeople: crewRefs(
kind === 'movie' ? crew.filter((c) => c.job === 'Director') : Array.isArray(d.created_by) ? d.created_by : [],
tmdbPersonId,
),
directorKind: kind === 'movie' ? 'director' : 'creator',
tagline: cleanText(d.tagline, 200),
runtime: count(kind === 'movie' ? d.runtime : d.episode_run_time?.[0], 6000),
seasons: kind === 'tv' ? count(d.number_of_seasons, 500) : undefined,
watch: parseTmdbProviders(d['watch/providers']),
}
}
const ANILIST_EXTRAS = `
query ($id: Int) {
Media(id: $id, type: ANIME) {
averageScore
bannerImage
duration
stats { scoreDistribution { score amount } }
characters(sort: [ROLE, RELEVANCE], perPage: 16) {
edges {
node { name { full } image { medium } }
voiceActors(language: JAPANESE, sort: [RELEVANCE]) { id name { full } }
}
}
staff(sort: [RELEVANCE], perPage: 12) { edges { role node { id name { full } } } }
externalLinks { site url type language color icon }
}
}`
interface AniExtras {
averageScore?: number | null
bannerImage?: string | null
duration?: number | null
stats?: { scoreDistribution?: { score?: number; amount?: number }[] | null } | null
characters?: { edges?: { node?: { name?: { full?: string }; image?: { medium?: string } }; voiceActors?: { id?: number; name?: { full?: string } }[] }[] } | null
staff?: { edges?: { role?: string; node?: { id?: number; name?: { full?: string } } }[] } | null
externalLinks?: unknown
}
async function aniListExtras(externalId: string): Promise<TitleExtras> {
const id = Number(externalId.split(':')[1])
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query: ANILIST_EXTRAS, variables: { id } }),
referrerPolicy: 'no-referrer',
credentials: 'omit',
signal: timeout(),
})
if (res.status === 429) throw new Error(t('err.anilistRate'))
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Media?: AniExtras } }
const m = json.data?.Media ?? {}
const distribution = (Array.isArray(m.stats?.scoreDistribution) ? m.stats!.scoreDistribution! : [])
.map((s) => ({ score: count(s.score, 100), amount: count(s.amount, 100_000_000) ?? 0 }))
.filter((s): s is { score: number; amount: number } => s.score != null && s.score % 10 === 0)
.map((s) => ({ score: s.score / 10, amount: s.amount }))
.sort((a, b) => a.score - b.score)
const votes = distribution.reduce((n, s) => n + s.amount, 0)
const cast = (Array.isArray(m.characters?.edges) ? m.characters!.edges! : [])
.map((e): Partial<CastMember> => ({
name: cleanText(e.node?.name?.full, 60),
photo: safePosterUrl(e.node?.image?.medium),
voice: cleanText(e.voiceActors?.[0]?.name?.full, 60),
personId: aniPersonId(e.voiceActors?.[0]?.id),
}))
.filter((c): c is CastMember => !!c.name)
const staff = Array.isArray(m.staff?.edges) ? m.staff!.edges! : []
return {
backdrop: safePosterUrl(m.bannerImage),
average: typeof m.averageScore === 'number' && m.averageScore > 0 ? Math.round(m.averageScore) / 10 : undefined,
votes: votes || undefined,
distribution: votes ? distribution : undefined,
cast,
directors: names(staff.filter((s) => /^Director$/i.test(s.role ?? '')).map((s) => s.node?.name?.full), 3),
directorPeople: crewRefs(
staff.filter((s) => /^Director$/i.test(s.role ?? '')).map((s) => ({ id: s.node?.id, name: s.node?.name?.full })),
aniPersonId,
),
directorKind: 'director',
runtime: count(m.duration, 6000),
streaming: parseAniListLinks(m.externalLinks),
}
}
// ─────────────────────────── Notes du public Trakt (films et séries) ───────────────────────────
/** Note du public Trakt : moyenne (sur 10), votes et répartition de 1 à 10. */
export interface PublicRatings {
average: number
votes: number
distribution: { score: number; amount: number }[]
}
// Gardées sur l'appareil : une fiche déjà ouverte affiche sa note tout de suite (et hors-ligne), puis la rafraîchit
const RATINGS_KEY = 'azuucine:ratings'
const RATINGS_MAX = 800
const RATINGS_FRESH = 2 * 24 * 3600_000
type RatingsEntry = { r: PublicRatings | null; at: number }
let ratingsMem: Map<string, RatingsEntry> | undefined
let ratingsSave: ReturnType<typeof setTimeout> | undefined
const ratingsInflight = new Map<string, Promise<PublicRatings | null>>()
function ratingsStore(): Map<string, RatingsEntry> {
if (ratingsMem) return ratingsMem
ratingsMem = new Map()
try {
const raw = JSON.parse(localStorage.getItem(RATINGS_KEY) ?? '{}') as Record<string, unknown>
for (const [k, v] of Object.entries(raw ?? {})) {
if (!/^tmdb:(movie|tv):\d{1,10}$/.test(k) || !Array.isArray(v) || typeof v[3] !== 'number') continue
const [average, votes, dist, at] = v as [unknown, unknown, unknown, number]
const ok = typeof average === 'number' && average > 0 && average <= 10 && typeof votes === 'number' && Array.isArray(dist) && dist.length === 10
ratingsMem.set(k, {
r: ok ? { average, votes, distribution: (dist as unknown[]).map((n, i) => ({ score: i + 1, amount: typeof n === 'number' && n >= 0 ? n : 0 })) } : null,
at,
})
}
} catch {
/* copie illisible ou stockage bloqué : on repart de zéro */
}
return ratingsMem
}
function saveRatings() {
clearTimeout(ratingsSave)
ratingsSave = setTimeout(() => {
try {
const entries = [...ratingsStore().entries()].sort((a, b) => b[1].at - a[1].at).slice(0, RATINGS_MAX)
const out: Record<string, unknown> = {}
for (const [k, { r, at }] of entries) out[k] = r ? [r.average, r.votes, r.distribution.map((d) => d.amount), at] : [0, 0, null, at]
localStorage.setItem(RATINGS_KEY, JSON.stringify(out))
} catch {
/* stockage plein ou bloqué : la note sera simplement redemandée */
}
}, 800)
}
/** Dernière note Trakt connue sur cet appareil (affichage immédiat). `undefined` : jamais demandée ; `null` : pas de note Trakt. */
export function cachedPublicRatings(externalId: string | undefined): PublicRatings | null | undefined {
return externalId ? ratingsStore().get(externalId)?.r : undefined
}
/** Note Trakt d'un film ou d'une série (via notre serveur), dédoublonnée et gardée sur l'appareil. */
export function getPublicRatings(externalId: string): Promise<PublicRatings | null> {
const m = /^tmdb:(movie|tv):(\d{1,10})$/.exec(externalId)
if (!m) return Promise.resolve(null)
const hit = ratingsStore().get(externalId)
if (hit && Date.now() - hit.at < RATINGS_FRESH) return Promise.resolve(hit.r)
let p = ratingsInflight.get(externalId)
if (!p) {
p = ratingsViaCloud(m[1] as 'movie' | 'tv', m[2])
.then((d) => {
// Trop peu de votes : la note TMDB reste plus parlante
const r: PublicRatings | null =
d && d.rating != null && d.votes >= 20
? {
average: Math.round(d.rating * 10) / 10,
votes: d.votes,
distribution: Object.entries(d.distribution).map(([score, amount]) => ({ score: Number(score), amount })).sort((a, b) => a.score - b.score),
}
: null
ratingsStore().set(externalId, { r, at: Date.now() })
saveRatings()
return r
})
.finally(() => ratingsInflight.delete(externalId))
ratingsInflight.set(externalId, p)
}
return p
}
// Clé TMDB du moment (compte, visiteur ou clé perso), pour le préchargement
let prefetchKey: string | undefined
export const setPrefetchKey = (key?: string) => void (prefetchKey = key)
/**
* Commence à charger une fiche dès qu'on touche son affiche : elle s'ouvre avec ses infos déjà là.
* Série : aussi la saison en cours et les images des épisodes autour du prochain à voir.
*/
export function prefetchTitle(externalId: string | null | undefined, season?: number, nextEpisode?: number): void {
if (!externalId || !navigator.onLine || !isSafeExternalId(externalId)) return
const isTmdb = externalId.startsWith('tmdb:')
const key = prefetchKey?.trim()
if (!isTmdb || key) void getTitleExtras(externalId, prefetchKey).catch(() => {})
if (isTmdb) void getPublicRatings(externalId).catch(() => {})
if (key && season && externalId.startsWith('tmdb:tv:')) {
void getTmdbSeasonEpisodes(externalId, season, key)
.then((list) => preloadImages(episodeWindow(list, nextEpisode ?? 1).map((e) => e.still)))
.catch(() => {})
}
}
/** Infos de la fiche (note moyenne, votes, casting…), gardées en mémoire le temps de la session. */
export function getTitleExtras(externalId: string, tmdbKey?: string): Promise<TitleExtras> {
if (!isSafeExternalId(externalId)) return Promise.reject(new Error(t('err.tmdbRef')))
const isTmdb = externalId.startsWith('tmdb:')
if (isTmdb && !tmdbKey?.trim()) return Promise.reject(new Error(t('search.animeOnly')))
// La langue fait partie de la clé : changer de langue ne doit pas resservir l'ancienne version
const cacheKey = `${externalId}:${tmdbLanguage()}`
const cached = extrasCache.get(cacheKey)
if (cached) return cached
const p = isTmdb ? tmdbExtras(externalId, tmdbKey!) : aniListExtras(externalId)
extrasCache.set(cacheKey, p)
p.catch(() => extrasCache.delete(cacheKey))
return p
}
// ─────────────────────────── Import depuis d'autres applis ───────────────────────────
/** Résultat TMDB avec de quoi créer une fiche sans requête de détail (import en masse). */
function tmdbWithPrefill(r: TmdbItem, kind: 'movie' | 'tv'): SearchResult | null {
const base = tmdbToResult(r, kind)
if (!base) return null
const guess = guessTmdbType(kind, r.genre_ids ?? [], r.origin_country ?? [], r.original_language)
return safeResult({
...base,
prefill: {
title: base.title,
originalTitle: base.originalTitle,
type: guess.type,
subtype: guess.subtype,
year: base.year,
overview: r.overview || undefined,
genres: tmdbGenres(r.genre_ids ?? []).filter((g) => guess.type === 'film' || g !== 'Animation'),
externalId: base.externalId,
countries: r.origin_country?.length ? r.origin_country.slice(0, 3) : undefined,
poster: base.posterUrl,
publicRating: tmdbPublicRating(r.vote_average, r.vote_count),
},
})
}
/** Recherche TMDB (films et séries) avec métadonnées de base, dans l'ordre de pertinence de TMDB. */
export async function tmdbImportSearch(query: string, key: string): Promise<SearchResult[]> {
const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: searchText(query), include_adult: 'false' })
return (Array.isArray(data.results) ? data.results : [])
.filter((r) => r && (r.media_type === 'movie' || r.media_type === 'tv'))
.slice(0, 20)
.map((r) => tmdbWithPrefill(r, r.media_type as 'movie' | 'tv'))
.filter((r): r is SearchResult => r !== null)
}
/** Fiche TMDB à partir d'un identifiant TVDB (TV Time) ou IMDb. */
export async function tmdbFindExternal(id: string, source: 'tvdb_id' | 'imdb_id', key: string): Promise<SearchResult | undefined> {
if (!(source === 'tvdb_id' ? /^\d{1,10}$/ : /^tt\d{1,10}$/).test(id)) return undefined
const data = await tmdbFetch<{ movie_results?: TmdbItem[]; tv_results?: TmdbItem[] }>(`/find/${id}`, key, { external_source: source })
const tv = Array.isArray(data.tv_results) ? data.tv_results[0] : undefined
const movie = Array.isArray(data.movie_results) ? data.movie_results[0] : undefined
return (tv && tmdbWithPrefill(tv, 'tv')) || (movie && tmdbWithPrefill(movie, 'movie')) || undefined
}
export { ANILIST, ANILIST_FIELDS, aniToResult, tmdbFetch, tmdbToResult, TMDB_IMG, type AniMedia, type TmdbItem }
/** Adresse de l'affiche TMDB d'un titre (listes partagées : la copie locale de l'affiche ne se partage pas). */
export async function getTmdbPosterUrl(externalId: string, key: string): Promise<string | undefined> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:')) return undefined
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const d = await tmdbFetch<{ poster_path?: string | null }>(`/${kind}/${id}`, key)
return isSafeTmdbPath(d.poster_path) ? `${TMDB_IMG}/w342${d.poster_path}` : undefined
}