Import depuis Letterboxd, TV Time, MyAnimeList et AniList

Réglages → Sauvegarde → « Importer depuis une autre app » ouvre un assistant :
choix de la source, instructions pour obtenir l'export, dépôt du fichier
(ZIP, CSV, XML ou XML.gz) ou nom d'utilisateur AniList, recherche des
fiches avec barre de progression annulable, aperçu (films / séries /
animes, nouvelles fiches, fiches complétées, non trouvés consultables),
fusion puis résumé.

- Lecture locale sans dépendance : mini-lecteur ZIP + DecompressionStream
  (deflate-raw / gzip), lecteur CSV tolérant, DOMParser pour MAL ; tailles
  bornées (anti zip bomb).
- Letterboxd : vus, notes (½ étoile → /10), journal (date de visionnage +
  revisionnages), avis, envies, coups de cœur.
- TV Time : colonnes détectées par nom ; séries suivies + épisodes vus →
  progression (saisons TMDB), archivées → abandonnées ; ID TVDB via
  TMDB /find (repli sur la recherche par titre).
- MAL : statuts, épisodes, note /10, dates ; résolu sur AniList par lots
  de 50 idMal. AniList : MediaListCollection public (score POINT_100).
- Correspondance TMDB par titre + année (titre traduit toléré), cache
  local des correspondances, 4 requêtes en parallèle, débit étalé avec
  un compte (proxy 600 req / 10 min) et reprise automatique sur 429.
- Fusion : pas de doublon (référence, même film, autre saison), saisons
  AniList regroupées en une fiche ; on complète sans jamais écraser, le
  statut / la progression n'avancent que si l'activité importée est plus
  récente.
- Proxy TMDB : chemin /find/{id} et paramètre external_source autorisés.
- i18n : clés import.* dans les 18 langues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-10-09 15:18:28 +00:00
1 parent c246b16e7e
commit 945ee32200
26 files changed
+2468 -3

No files matched your search

+48 -1
View File
@@ -107,6 +107,7 @@ interface TmdbItem {
vote_average?: number
vote_count?: number
popularity?: number
overview?: string
}
/** Clé v3 (32 caractères hexadécimaux) ou jeton de lecture v4 (JWT). */
@@ -116,7 +117,7 @@ export function isPlausibleTmdbKey(key: string): boolean {
}
/** Seules ces adresses de l'API TMDB peuvent être appelées. */
const TMDB_PATHS = /^\/(search\/multi|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?)$/
const TMDB_PATHS = /^\/(search\/multi|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?|find\/(tt)?\d{1,10})$/
/** « 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'
@@ -1168,3 +1169,49 @@ export function getTitleExtras(externalId: string, tmdbKey?: string): Promise<Ti
p.catch(() => extrasCache.delete(externalId))
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: query.slice(0, 100), 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, type AniMedia }
+186
View File
@@ -0,0 +1,186 @@
/**
* Lecture des fichiers d'export (sans dépendance) :
* - mini-lecteur ZIP (entrées « stockées » ou « deflate », décompressées par le navigateur) ;
* - décompression gzip (.xml.gz de MyAnimeList) ;
* - lecteur CSV (guillemets, retours à la ligne dans les champs, BOM).
* Tout est borné : un fichier piégé (zip bomb, CSV géant) est refusé au lieu de bloquer l'appli.
*/
/** Taille maximale décompressée, toutes entrées confondues. */
const MAX_UNPACKED = 80 * 1024 * 1024
/** Nombre maximal de lignes lues dans un CSV. */
const MAX_ROWS = 200_000
export class ImportFileError extends Error {}
export interface TextFile {
/** Chemin dans l'archive (ou nom du fichier), en minuscules, avec « / » */
path: string
text: string
}
/** Décompresse avec le DecompressionStream du navigateur, en s'arrêtant au-delà de `max` octets. */
async function inflate(data: Uint8Array, format: 'deflate-raw' | 'gzip', max: number): Promise<Uint8Array> {
if (typeof DecompressionStream === 'undefined') throw new ImportFileError('unsupported')
const stream = new Blob([data as BlobPart]).stream().pipeThrough(new DecompressionStream(format))
const reader = stream.getReader()
const chunks: Uint8Array[] = []
let total = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
total += value.byteLength
if (total > max) {
void reader.cancel().catch(() => {})
throw new ImportFileError('tooBig')
}
chunks.push(value)
}
const out = new Uint8Array(total)
let pos = 0
for (const c of chunks) {
out.set(c, pos)
pos += c.byteLength
}
return out
}
const decoder = () => new TextDecoder('utf-8')
export const isZip = (b: Uint8Array) => b.length > 4 && b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04
export const isGzip = (b: Uint8Array) => b.length > 2 && b[0] === 0x1f && b[1] === 0x8b
/**
* Extrait les fichiers texte d'une archive ZIP dont le nom passe le filtre.
* Lit le répertoire central (fiable même quand les tailles locales sont différées).
*/
export async function unzipText(bytes: Uint8Array, keep: (path: string) => boolean): Promise<TextFile[]> {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
// Fin du répertoire central : signature 0x06054b50, dans les 64 Ko de la fin
let eocd = -1
for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 22 - 0xffff); i--) {
if (view.getUint32(i, true) === 0x06054b50) {
eocd = i
break
}
}
if (eocd < 0) throw new ImportFileError('badZip')
const count = view.getUint16(eocd + 10, true)
let p = view.getUint32(eocd + 16, true)
const out: TextFile[] = []
let unpacked = 0
for (let n = 0; n < count && n < 5000; n++) {
if (p + 46 > bytes.length || view.getUint32(p, true) !== 0x02014b50) throw new ImportFileError('badZip')
const method = view.getUint16(p + 10, true)
const flags = view.getUint16(p + 8, true)
const compSize = view.getUint32(p + 20, true)
const size = view.getUint32(p + 24, true)
const nameLen = view.getUint16(p + 28, true)
const extraLen = view.getUint16(p + 30, true)
const commentLen = view.getUint16(p + 32, true)
const local = view.getUint32(p + 42, true)
const rawName = bytes.subarray(p + 46, p + 46 + nameLen)
const name = (flags & 0x800 ? decoder().decode(rawName) : String.fromCharCode(...rawName)).replace(/\\/g, '/').toLowerCase()
p += 46 + nameLen + extraLen + commentLen
if (name.endsWith('/') || !keep(name)) continue
if (flags & 0x1) throw new ImportFileError('encrypted')
if (local + 30 > bytes.length || view.getUint32(local, true) !== 0x04034b50) throw new ImportFileError('badZip')
const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true)
const data = bytes.subarray(start, start + compSize)
if (data.length < compSize) throw new ImportFileError('badZip')
const budget = MAX_UNPACKED - unpacked
let content: Uint8Array
if (method === 0) content = data
else if (method === 8) content = await inflate(data, 'deflate-raw', Math.min(budget, Math.max(size, 1) + 1024))
else throw new ImportFileError('badZip')
unpacked += content.byteLength
if (unpacked > MAX_UNPACKED) throw new ImportFileError('tooBig')
out.push({ path: name, text: decoder().decode(content) })
}
return out
}
export async function gunzipText(bytes: Uint8Array): Promise<string> {
return decoder().decode(await inflate(bytes, 'gzip', MAX_UNPACKED))
}
/** Normalise un nom de colonne : « Watched Date » → « watched_date ». */
export const columnKey = (s: string) =>
s
.replace(/^/, '')
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_|_$/g, '')
export type CsvRow = Record<string, string>
/** Lit un CSV (virgule, point-virgule ou tabulation) en lignes indexées par nom de colonne normalisé. */
export function parseCsv(input: string): { columns: string[]; rows: CsvRow[] } {
const text = input.replace(/^/, '')
const nl = text.indexOf('\n')
const firstLine = nl < 0 ? text : text.slice(0, nl)
const counts = [',', ';', '\t'].map((d) => [d, firstLine.split(d).length] as const)
const sep = counts.sort((a, b) => b[1] - a[1])[0][0]
const records: string[][] = []
let field = ''
let row: string[] = []
let quoted = false
for (let i = 0; i < text.length; i++) {
const c = text[i]
if (quoted) {
if (c === '"') {
if (text[i + 1] === '"') {
field += '"'
i++
} else quoted = false
} else field += c
} else if (c === '"' && field === '') quoted = true
else if (c === sep) {
row.push(field)
field = ''
} else if (c === '\n' || c === '\r') {
if (c === '\r' && text[i + 1] === '\n') i++
row.push(field)
field = ''
if (row.length > 1 || row[0] !== '') records.push(row)
row = []
if (records.length > MAX_ROWS) break
} else field += c
}
if (field !== '' || row.length) {
row.push(field)
if (row.length > 1 || row[0] !== '') records.push(row)
}
const header = records.shift() ?? []
const columns = header.map(columnKey)
const rows = records.map((r) => {
const o: CsvRow = Object.create(null)
columns.forEach((k, j) => {
if (k && !(k in o)) o[k] = (r[j] ?? '').trim()
})
return o
})
return { columns, rows }
}
/** Première valeur non vide parmi plusieurs noms de colonne possibles. */
export function pick(row: CsvRow, names: string[]): string | undefined {
for (const n of names) {
const v = row[n]
if (v != null && v !== '') return v
}
return undefined
}
/** Lit un fichier choisi par l'utilisateur (zip, gz ou texte) en liste de fichiers texte. */
export async function readImportFile(file: File, keep: (path: string) => boolean, maxBytes: number): Promise<TextFile[]> {
if (file.size > maxBytes) throw new ImportFileError('tooBig')
const bytes = new Uint8Array(await file.arrayBuffer())
const name = file.name.toLowerCase()
if (isZip(bytes)) return unzipText(bytes, keep)
if (isGzip(bytes)) return [{ path: name.replace(/\.gz$/, ''), text: await gunzipText(bytes) }]
return [{ path: name, text: decoder().decode(bytes) }]
}
+299
View File
@@ -0,0 +1,299 @@
import type { MediaInput, MediaItem, MediaType, WatchStatus } from '../../types'
import { normalizeItem } from '../backup'
import { TYPE_BY_VALUE } from '../constants'
import { episodeCap, findFranchiseItem, franchiseKey, seasonPosition } from '../franchise'
import { cleanText, LIMITS } from '../security'
import { uid } from '../utils'
import type { Match } from './resolve'
import { titleKey, type ImportEntry } from './sources'
/**
* Transforme les entrées trouvées en fiches AzuuCine et les fusionne avec la bibliothèque :
* - pas de doublon (même référence TMDB / AniList, même film, ou autre saison de la même série) ;
* - une fiche existante n'est jamais écrasée : on complète ce qui manque, et le statut / la progression
* n'avancent que si l'activité importée est plus récente que la dernière modification de la fiche.
*/
export interface ImportPlan {
/** Nouvelles fiches */
added: MediaItem[]
/** Fiches existantes complétées */
updated: MediaItem[]
/** Titres déjà dans la bibliothèque, sans rien de nouveau */
unchanged: number
/** Entrées sans correspondance */
notFound: ImportEntry[]
}
const RANK: Record<WatchStatus, number> = { a_voir: 0, pause: 1, abandonne: 1, en_cours: 2, termine: 3 }
const episodic = (type: MediaType) => TYPE_BY_VALUE[type]?.episodic ?? false
const typeOfKind = (e: ImportEntry): MediaType => (e.kind === 'movie' ? 'film' : e.kind === 'anime' ? (e.format === 'MOVIE' ? 'film' : 'anime') : 'serie')
interface Candidate {
/** Fiche à créer (sans id définitif) */
item: MediaItem
/** Toutes les références externes couvertes (saisons AniList regroupées) */
externalIds: string[]
titles: string[]
/** L'activité importée a une date connue */
dated: boolean
entries: ImportEntry[]
}
/** Fiche à partir d'une entrée (et de sa correspondance, si trouvée). */
function entryToItem(e: ImportEntry, match: Match | undefined, now: string): MediaItem {
const meta: Partial<MediaInput> = match?.meta ?? { title: e.title, year: e.year, type: typeOfKind(e), genres: [] }
const type = meta.type ?? typeOfKind(e)
const isFilm = !episodic(type)
const seasons = meta.seasons
const cap = episodeCap({ episodesTotal: meta.episodesTotal, seasons })
let status = e.status
let episodesWatched = 0
let season: number | undefined
let { startDate, endDate } = e
if (!isFilm) {
if (e.seen) {
// TV Time : épisodes cochés un par un
episodesWatched = cap ? Math.min(cap, e.seen.size) : e.seen.size
if (episodesWatched === 0) status = e.archived ? 'abandonne' : 'a_voir'
else if (cap && episodesWatched >= cap) status = 'termine'
else status = e.archived ? 'abandonne' : 'en_cours'
if (status !== 'termine') endDate = undefined
if (!seasons || seasons.length < 2) {
const last = Math.max(0, ...[...e.seen].map((k) => Number(k.split(':')[0])))
if (last > 0) season = last
}
} else {
episodesWatched = e.episodesWatched ?? 0
if (status === 'termine' && cap && episodesWatched < cap) episodesWatched = cap
if (cap) episodesWatched = Math.min(cap, episodesWatched)
}
season = seasonPosition({ episodesWatched, seasons, season: undefined })?.season ?? season
}
if (status !== 'termine' && !isFilm) endDate = undefined
if (status === 'a_voir') startDate = undefined
return {
...meta,
id: uid(),
title: meta.title ?? e.title,
type,
genres: meta.genres ?? [],
criteria: {},
status,
rating: status === 'a_voir' ? undefined : e.rating,
favorite: e.favorite || undefined,
episodesWatched,
season,
startDate,
endDate: status === 'termine' || isFilm ? endDate : undefined,
rewatchDates: e.rewatchDates,
notes: e.notes,
createdAt: e.firstSeen ?? now,
updatedAt: e.activity ?? now,
}
}
/** Saisons AniList d'une même série (« … Season 2 ») regroupées en une fiche, comme dans l'appli. */
function groupAnimeSeasons(cands: Candidate[]): Candidate[] {
const out: Candidate[] = []
const groups = new Map<string, Candidate[]>()
for (const c of cands) {
const e = c.entries[0]
const isAniSeries = (e.media || e.malId) && c.item.type === 'anime' && c.externalIds[0]?.startsWith('anilist:')
if (!isAniSeries) {
out.push(c)
continue
}
const romaji = e.media?.title?.romaji ?? c.item.originalTitle ?? c.item.title
const k = franchiseKey(romaji)
groups.set(k, [...(groups.get(k) ?? []), c])
}
for (const list of groups.values()) {
if (list.length === 1) {
out.push(list[0])
continue
}
list.sort((a, b) => (a.item.year ?? 9999) - (b.item.year ?? 9999) || Number(a.externalIds[0].split(':')[1]) - Number(b.externalIds[0].split(':')[1]))
const first = list[0].item
const sizes = list.map((c) => c.item.episodesTotal)
const allKnown = sizes.every((n): n is number => !!n)
const statuses = list.map((c) => c.item.status)
const status: WatchStatus = statuses.every((s) => s === 'termine')
? 'termine'
: statuses.every((s) => s === 'a_voir')
? 'a_voir'
: statuses.includes('en_cours') || (statuses.includes('termine') && statuses.includes('a_voir'))
? 'en_cours'
: statuses.includes('pause')
? 'pause'
: statuses.includes('abandonne')
? 'abandonne'
: 'en_cours'
const seasons = allKnown ? (sizes as number[]) : undefined
const watched = list.reduce((sum, c) => sum + c.item.episodesWatched, 0)
const rated = [...list].reverse().find((c) => c.item.rating != null)
const days = (pickDay: (i: MediaItem) => string | undefined) => list.map((c) => pickDay(c.item)).filter((d): d is string => !!d).sort()
const item: MediaItem = {
...first,
status,
seasons,
episodesTotal: allKnown ? (sizes as number[]).reduce((a, b) => a + b, 0) : first.episodesTotal,
episodesWatched: watched,
season: seasonPosition({ episodesWatched: watched, seasons, season: undefined })?.season,
rating: status === 'a_voir' ? undefined : rated?.item.rating,
favorite: list.some((c) => c.item.favorite) || undefined,
startDate: status === 'a_voir' ? undefined : days((i) => i.startDate)[0],
endDate: status === 'termine' ? days((i) => i.endDate).pop() : undefined,
notes: cleanText(list.map((c) => c.item.notes).filter(Boolean).join('\n\n'), LIMITS.notes),
createdAt: list.map((c) => c.item.createdAt).sort()[0],
updatedAt: list.map((c) => c.item.updatedAt).sort().pop()!,
}
out.push({
item,
externalIds: list.flatMap((c) => c.externalIds),
titles: list.flatMap((c) => c.titles),
dated: list.some((c) => c.dated),
entries: list.flatMap((c) => c.entries),
})
}
return out
}
/** Même film déjà dans la bibliothèque, ou même série (n'importe quelle saison). */
function findExisting(library: MediaItem[], c: Candidate): MediaItem | undefined {
const byRef = library.find((i) => i.externalId && c.externalIds.includes(i.externalId))
if (byRef) return byRef
const keys = new Set(c.titles.map(titleKey).filter(Boolean))
if (!episodic(c.item.type)) {
return library.find(
(i) =>
!episodic(i.type) &&
[i.title, i.originalTitle].some((x) => x && keys.has(titleKey(x))) &&
(!i.year || !c.item.year || Math.abs(i.year - c.item.year) <= 1),
)
}
return findFranchiseItem(library, c.titles, { type: c.item.type })
}
/** Complète une fiche existante sans jamais écraser ce que l'utilisateur a saisi. Renvoie null si rien ne change. */
function mergeInto(existing: MediaItem, c: Candidate, now: string): MediaItem | null {
const inc = c.item
const next: MediaItem = { ...existing }
let changed = false
const set = <K extends keyof MediaItem>(k: K, v: MediaItem[K]) => {
next[k] = v
changed = true
}
// L'activité importée est-elle plus récente que la dernière modification de ma fiche ?
const newer = c.dated && inc.updatedAt > existing.updatedAt
const canAdvance = existing.status === 'a_voir' || newer
if (RANK[inc.status] > RANK[existing.status] && canAdvance) set('status', inc.status)
if (episodic(existing.type) && inc.episodesWatched > existing.episodesWatched && canAdvance && (!existing.externalId || existing.externalId === inc.externalId)) {
const cap = episodeCap(existing)
set('episodesWatched', cap ? Math.min(cap, inc.episodesWatched) : inc.episodesWatched)
const pos = seasonPosition({ episodesWatched: next.episodesWatched, seasons: existing.seasons, season: undefined })
if (pos) next.season = pos.season
}
if (existing.rating == null && inc.rating != null) set('rating', inc.rating)
if (!existing.favorite && inc.favorite) set('favorite', true)
if (!existing.notes && inc.notes) set('notes', inc.notes)
if (!existing.startDate && inc.startDate && next.status !== 'a_voir') set('startDate', inc.startDate)
if (!existing.endDate && inc.endDate && next.status === 'termine') set('endDate', inc.endDate)
if (inc.rewatchDates?.length) {
const all = [...new Set([...(existing.rewatchDates ?? []), ...inc.rewatchDates])].filter((d) => d !== next.endDate).sort()
if (all.length !== (existing.rewatchDates?.length ?? 0)) set('rewatchDates', all.slice(-200))
}
// Métadonnées manquantes (fiche saisie à la main) : on les complète
if (!existing.externalId && inc.externalId && !refInUse(inc.externalId)) set('externalId', inc.externalId)
if (!existing.poster && inc.poster) set('poster', inc.poster)
if (!existing.overview && inc.overview) set('overview', inc.overview)
if (!existing.year && inc.year) set('year', inc.year)
if (!existing.genres.length && inc.genres.length) set('genres', inc.genres)
if (!changed) return null
next.updatedAt = now
return normalizeItem(next)
}
// Références déjà utilisées par une autre fiche (évite deux fiches avec la même référence)
let usedRefs = new Set<string>()
const refInUse = (ref: string) => usedRefs.has(ref)
/** Prépare l'import (sans rien écrire). */
export function buildImportPlan(entries: ImportEntry[], matches: Map<string, Match>, library: MediaItem[], opts: { includeUnmatched: boolean }): ImportPlan {
const now = new Date().toISOString()
usedRefs = new Set(library.map((i) => i.externalId).filter((x): x is string => !!x))
const notFound: ImportEntry[] = []
const byRef = new Map<string, Candidate>()
const loose: Candidate[] = []
for (const e of entries) {
const match = matches.get(e.key)
if (!match && !opts.includeUnmatched) {
notFound.push(e)
continue
}
if (!match) notFound.push(e)
const item = entryToItem(e, match, now)
const ref = match?.result.externalId
const cand: Candidate = {
item,
externalIds: ref ? [ref] : [],
titles: [item.title, item.originalTitle, e.title, ...(match?.result.altTitles ?? [])].filter((x): x is string => !!x),
dated: !!e.activity,
entries: [e],
}
if (!ref) {
loose.push(cand)
continue
}
// Deux lignes du même titre (ex. deux années saisies différemment) : une seule fiche
const prev = byRef.get(ref)
if (prev) {
const merged = mergeInto(prev.item, cand, prev.item.updatedAt)
if (merged) prev.item = { ...merged, updatedAt: [prev.item.updatedAt, cand.item.updatedAt].sort().pop()! }
prev.entries.push(e)
} else byRef.set(ref, cand)
}
const cands = groupAnimeSeasons([...byRef.values()]).concat(loose)
const added: MediaItem[] = []
const updated = new Map<string, MediaItem>()
let unchanged = 0
const pool = [...library]
for (const c of cands) {
const existing = findExisting(pool, c)
if (existing) {
const base = updated.get(existing.id) ?? existing
const merged = mergeInto(base, c, now)
if (merged) {
updated.set(existing.id, merged)
const k = pool.indexOf(existing)
if (k >= 0) pool[k] = merged
if (merged.externalId) usedRefs.add(merged.externalId)
} else if (!updated.has(existing.id)) unchanged++
continue
}
const item = normalizeItem(c.item)
if (!item) continue
added.push(item)
pool.push(item)
if (item.externalId) usedRefs.add(item.externalId)
}
return { added, updated: [...updated.values()], unchanged, notFound }
}
/** Nombre de fiches par grande catégorie (aperçu). */
export function countByKind(items: MediaItem[]): { films: number; series: number; anime: number } {
let films = 0
let series = 0
let anime = 0
for (const i of items) {
if (i.type === 'film') films++
else if (i.type === 'anime') anime++
else series++
}
return { films, series, anime }
}
+315
View File
@@ -0,0 +1,315 @@
import { t } from '../../i18n'
import { ANILIST, ANILIST_FIELDS, aniToResult, CLOUD_TMDB, getTmdbDetails, tmdbFindExternal, tmdbImportSearch, type AniMedia, type SearchResult } from '../catalogApi'
import type { MediaInput } from '../../types'
import { anilistEntries, titleKey, type AniListEntry, type ImportEntry } from './sources'
/**
* Recherche des fiches correspondantes (TMDB pour les films et séries, AniList pour les animes).
* - petites rafales : 4 requêtes en parallèle au plus ;
* - avec un compte, TMDB passe par le serveur (600 requêtes / 10 min) : on étale les requêtes ;
* - AniList (90 requêtes / min) : les identifiants sont demandés par lots de 50 ;
* - les correspondances trouvées sont gardées en cache (un nouvel essai ne refait pas tout).
*/
export interface Match {
result: SearchResult
/** Métadonnées prêtes pour la fiche (titre, type, affiche, saisons…) */
meta: Partial<MediaInput>
}
export interface Progress {
done: number
total: number
/** Pause imposée par la limite de débit : reprise à cette heure (ms) */
waitUntil?: number
}
export interface CancelToken {
cancelled: boolean
}
export class CancelledError extends Error {}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
// ─── Cache des correspondances (données publiques uniquement) ───
const CACHE_KEY = 'azuucine:import-match'
const CACHE_MAX = 4000
let cache: Record<string, SearchResult> | null = null
function loadCache(): Record<string, SearchResult> {
if (cache) return cache
cache = Object.create(null) as Record<string, SearchResult>
try {
const raw = JSON.parse(localStorage.getItem(CACHE_KEY) ?? '{}') as unknown
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
if (v && typeof v === 'object' && typeof (v as SearchResult).externalId === 'string') cache[k] = v as SearchResult
}
}
} catch {
/* cache illisible : on repart de zéro */
}
return cache
}
function saveCache() {
if (!cache) return
try {
const keys = Object.keys(cache)
if (keys.length > CACHE_MAX) for (const k of keys.slice(0, keys.length - CACHE_MAX)) delete cache[k]
localStorage.setItem(CACHE_KEY, JSON.stringify(cache))
} catch {
/* stockage plein ou bloqué : tant pis pour le cache */
}
}
// ─── Limite de débit ───
/** Seau à jetons : `burst` requêtes d'un coup, puis une toutes les `everyMs`. */
function limiter(burst: number, everyMs: number) {
let tokens = burst
let last = Date.now()
return async (token: CancelToken) => {
for (;;) {
if (token.cancelled) throw new CancelledError()
const now = Date.now()
tokens = Math.min(burst, tokens + (now - last) / everyMs)
last = now
if (tokens >= 1) {
tokens -= 1
return
}
await sleep(Math.min(1000, (1 - tokens) * everyMs))
}
}
}
const isRateError = (e: unknown) => {
const msg = (e as Error)?.message ?? ''
return msg === t('err.searchRate') || msg === t('err.anilistRate') || msg === t('err.tmdbStatus', { status: 429 }) || msg === 'rate'
}
/** Exécute les tâches avec au plus `size` en parallèle. */
async function pool<T>(list: T[], size: number, token: CancelToken, fn: (x: T) => Promise<void>) {
let i = 0
const worker = async () => {
while (i < list.length) {
if (token.cancelled) throw new CancelledError()
await fn(list[i++])
}
}
await Promise.all(Array.from({ length: Math.min(size, list.length) }, worker))
}
// ─── TMDB ───
/** Meilleur candidat : bon type, même année (± 1), titre identique en priorité. */
export function bestTmdbMatch(results: SearchResult[], entry: Pick<ImportEntry, 'kind' | 'title' | 'year'>): SearchResult | undefined {
const prefix = entry.kind === 'movie' ? 'tmdb:movie:' : 'tmdb:tv:'
const cands = results.filter((r) => r.externalId.startsWith(prefix))
const want = titleKey(entry.title)
const same = (r: SearchResult) => [r.title, r.originalTitle].some((x) => x && titleKey(x) === want)
if (entry.year) {
const y = entry.year
const exact = cands.filter((r) => r.year === y)
const close = cands.filter((r) => r.year != null && Math.abs(r.year - y) <= 1)
return exact.find(same) ?? close.find(same) ?? exact[0] ?? close[0]
}
return cands.find(same) ?? cands[0]
}
/** Requête TMDB avec reprise automatique quand la limite de débit est atteinte. */
async function withRetry<T>(fn: () => Promise<T>, token: CancelToken, onWait: (until?: number) => void): Promise<T> {
let delay = 15_000
for (let attempt = 0; ; attempt++) {
if (token.cancelled) throw new CancelledError()
try {
return await fn()
} catch (e) {
if (!isRateError(e) || attempt >= 30) throw e
const until = Date.now() + delay
onWait(until)
while (Date.now() < until) {
if (token.cancelled) throw new CancelledError()
await sleep(500)
}
onWait(undefined)
delay = Math.min(60_000, delay * 1.5)
}
}
}
// ─── AniList ───
async function anilistPost<T>(query: string, variables: Record<string, unknown>): Promise<T> {
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer',
credentials: 'omit',
body: JSON.stringify({ query, variables }),
})
if (res.status === 429) throw new Error('rate')
const json = (await res.json().catch(() => ({}))) as { data?: T; errors?: { message?: string; status?: number }[] }
if (!res.ok || !json.data) {
const msg = json.errors?.[0]?.message ?? ''
if (res.status === 404 || /not found|private/i.test(msg)) throw new Error('anilist-user')
throw new Error(t('err.anilistStatus', { status: res.status }))
}
return json.data
}
/** Nom d'utilisateur AniList valide (lettres et chiffres, 2 à 20 caractères). */
export const isAniListUserName = (v: string) => /^[A-Za-z0-9_-]{2,20}$/.test(v.trim())
/** Liste d'animes publique d'un membre AniList (sans connexion). */
export async function fetchAniListUser(userName: string): Promise<{ entries: ImportEntry[]; adult: number }> {
const name = userName.trim()
if (!isAniListUserName(name)) throw new Error('anilist-user')
const query = `query ($name: String) {
MediaListCollection(userName: $name, type: ANIME, forceSingleCompletedList: true) {
lists { isCustomList entries {
status score(format: POINT_100) progress repeat notes updatedAt
startedAt { year month day } completedAt { year month day }
media { isAdult ${ANILIST_FIELDS} }
} }
}
}`
const data = await anilistPost<{ MediaListCollection?: { lists?: { isCustomList?: boolean; entries?: (AniListEntry & { media?: AniMedia & { isAdult?: boolean } })[] }[] } }>(query, {
name,
})
const lists = Array.isArray(data.MediaListCollection?.lists) ? data.MediaListCollection!.lists! : []
const all = lists.filter((l) => !l.isCustomList).flatMap((l) => (Array.isArray(l.entries) ? l.entries : []))
const adult = all.filter((e) => e.media?.isAdult).length
return { entries: anilistEntries(all.filter((e) => !e.media?.isAdult)), adult }
}
/** Fiches AniList à partir d'identifiants MyAnimeList, par lots de 50. */
async function aniListByMal(ids: number[], token: CancelToken, onBatch: (found: Map<number, AniMedia>, count: number) => void, onWait: (until?: number) => void) {
const query = `query ($ids: [Int]) { Page(perPage: 50) { media(idMal_in: $ids, type: ANIME) { idMal isAdult ${ANILIST_FIELDS} } } }`
const rate = limiter(2, 900) // ~66 requêtes / min, sous la limite d'AniList
for (let i = 0; i < ids.length; i += 50) {
await rate(token)
const chunk = ids.slice(i, i + 50)
const data = await withRetry(() => anilistPost<{ Page?: { media?: (AniMedia & { idMal?: number; isAdult?: boolean })[] } }>(query, { ids: chunk }), token, onWait)
const found = new Map<number, AniMedia>()
for (const m of Array.isArray(data.Page?.media) ? data.Page!.media! : []) {
if (m && Number.isInteger(m.idMal) && !m.isAdult) found.set(m.idMal!, m)
}
onBatch(found, chunk.length)
}
}
// ─── Résolution ───
export interface ResolveOptions {
/** Clé TMDB (ou CLOUD_TMDB avec un compte) ; sans elle, films et séries ne sont pas cherchés */
tmdbKey?: string
token: CancelToken
onProgress: (p: Progress) => void
}
/** Cherche la fiche de chaque entrée. Renvoie les correspondances par clé d'entrée. */
export async function resolveEntries(entries: ImportEntry[], opts: ResolveOptions): Promise<Map<string, Match>> {
const { token } = opts
const found = new Map<string, Match>()
const progress: Progress = { done: 0, total: entries.length }
const emit = () => opts.onProgress({ ...progress })
const step = (n = 1) => {
progress.done += n
emit()
}
const onWait = (until?: number) => {
progress.waitUntil = until
emit()
}
emit()
// 1. Animes déjà fournis par AniList
const viaMal: ImportEntry[] = []
const viaTmdb: ImportEntry[] = []
let alreadyDone = 0
for (const e of entries) {
if (e.media) {
const result = aniToResult(e.media)
if (result) found.set(e.key, { result, meta: { ...result.prefill, poster: result.posterUrl } })
alreadyDone++
} else if (e.malId) viaMal.push(e)
else if (e.kind !== 'anime') viaTmdb.push(e)
else alreadyDone++
}
step(alreadyDone)
// 2. MyAnimeList → AniList par lots d'identifiants
if (viaMal.length) {
const byMal = new Map(viaMal.map((e) => [e.malId!, e]))
await aniListByMal([...byMal.keys()], token, (media, count) => {
for (const [malId, m] of media) {
const e = byMal.get(malId)
const result = e && aniToResult(m)
if (e && result) found.set(e.key, { result, meta: { ...result.prefill, poster: result.posterUrl } })
}
step(count)
}, onWait)
}
// 3. Films et séries → TMDB
const key = opts.tmdbKey?.trim()
if (!key) {
step(viaTmdb.length)
return found
}
const cloud = key === CLOUD_TMDB
// Avec un compte, le serveur accepte 600 requêtes / 10 min : rafale de 150 puis ~1 par seconde
const rate = cloud ? limiter(150, 1050) : limiter(20, 60)
const c = loadCache()
let sinceSave = 0
const lang = document.documentElement.lang || 'x'
await pool(viaTmdb, 4, token, async (e) => {
try {
const cacheKey = e.tvdbId ? `tvdb:${e.tvdbId}:${lang}` : e.imdbId ? `imdb:${e.imdbId}:${lang}` : `${e.kind}:${titleKey(e.title)}|${e.year ?? ''}:${lang}`
let result: SearchResult | undefined = c[cacheKey]
if (!result && (e.tvdbId || e.imdbId)) {
await rate(token)
result = await withRetry(() => tmdbFindExternal(e.tvdbId ?? e.imdbId!, e.tvdbId ? 'tvdb_id' : 'imdb_id', key), token, onWait).catch((err) => {
if (err instanceof CancelledError) throw err
return undefined // ancien serveur sans /find, ou identifiant inconnu : recherche par titre
})
}
if (!result && !e.title.startsWith('#')) {
await rate(token)
const list = await withRetry(() => tmdbImportSearch(e.title, key), token, onWait)
result = bestTmdbMatch(list, e)
}
if (!result) return
if (!c[cacheKey]) {
c[cacheKey] = result
if (++sinceSave >= 25) {
sinceSave = 0
saveCache()
}
}
let meta: Partial<MediaInput> = { ...result.prefill, poster: result.posterUrl }
// Séries : saisons et nombre d'épisodes, pour reprendre la progression
if (result.externalId.startsWith('tmdb:tv:')) {
await rate(token)
const details = await withRetry(() => getTmdbDetails(result!, key), token, onWait).catch((err) => {
if (err instanceof CancelledError) throw err
return undefined
})
if (details) meta = { ...meta, ...details, poster: result.posterUrl ?? meta.poster }
}
found.set(e.key, { result, meta })
} catch (err) {
if (err instanceof CancelledError) throw err
if (!navigator.onLine) throw new Error(t('search.offline'))
// Erreur ponctuelle sur un titre : il sera compté comme « non trouvé »
} finally {
step()
}
}).finally(saveCache)
return found
}
+352
View File
@@ -0,0 +1,352 @@
import type { WatchStatus } from '../../types'
import type { AniMedia } from '../catalogApi'
import { cleanText, LIMITS, safeDay, safeIso } from '../security'
import { parseCsv, pick, type CsvRow, type TextFile } from './files'
/**
* Lecture des exports d'autres applis (Letterboxd, TV Time, MyAnimeList, AniList)
* vers un format commun, avant la recherche des fiches correspondantes.
*/
export type ImportSource = 'letterboxd' | 'tvtime' | 'mal' | 'anilist'
export type EntryKind = 'movie' | 'tv' | 'anime'
export interface ImportEntry {
/** Identifiant unique dans l'import */
key: string
kind: EntryKind
title: string
year?: number
/** Identifiants externes connus */
tvdbId?: string
imdbId?: string
anilistId?: number
malId?: number
/** Fiche AniList déjà fournie (import AniList) */
media?: AniMedia
/** Format AniList / MAL (« MOVIE », « TV »…) */
format?: string
status: WatchStatus
/** Note sur 10 (pas de 0,5) */
rating?: number
favorite?: boolean
/** Nombre d'épisodes vus (MAL / AniList) */
episodesWatched?: number
/** Épisodes vus « saison:épisode » (TV Time) */
seen?: Set<string>
/** Série mise de côté dans TV Time */
archived?: boolean
startDate?: string
endDate?: string
rewatchDates?: string[]
notes?: string
/** Date de la dernière activité connue (ISO) — sert à ne jamais écraser une donnée plus récente */
activity?: string
/** Date de la première activité connue (ISO) */
firstSeen?: string
}
/** Clé de comparaison d'un titre : sans accents, casse ni ponctuation. */
export const titleKey = (s: string) =>
s
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/&/g, 'and')
.replace(/[^\p{L}\p{N}]+/gu, '')
const yearOf = (v?: string) => {
const n = v && /^\d{4}$/.test(v.trim()) ? Number(v) : NaN
return n >= 1870 && n <= 2200 ? n : undefined
}
/** « 2024-03-05 », « 2024-03-05 18:22:01 », « 2024-03-05T18:22:01Z » → AAAA-MM-JJ */
export const toDay = (v?: string) => (v ? safeDay(v.trim().slice(0, 10)) : undefined)
/** Date → ISO (pour comparer avec la date de modification des fiches) */
export const toIso = (v?: string) => {
if (!v) return undefined
const s = v.trim()
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return safeIso(s + 'T12:00:00Z')
return safeIso(s.includes('T') ? s : s.replace(' ', 'T') + (/[zZ]|[+-]\d{2}:?\d{2}$/.test(s) ? '' : 'Z'))
}
/** Garde la date la plus ancienne / la plus récente vue pour une entrée. */
function touch(e: ImportEntry, raw?: string) {
const iso = toIso(raw)
if (!iso) return
if (!e.activity || iso > e.activity) e.activity = iso
if (!e.firstSeen || iso < e.firstSeen) e.firstSeen = iso
}
const appendNote = (prev: string | undefined, add?: string) => cleanText([prev, add].filter(Boolean).join('\n\n'), LIMITS.notes)
// ─────────────────────────── Letterboxd ───────────────────────────
const basename = (p: string) => p.split('/').pop() ?? p
/** Fichiers Letterboxd reconnus (on ignore les dossiers « deleted », « orphaned » et les listes). */
export function letterboxdRole(path: string): 'watched' | 'ratings' | 'diary' | 'reviews' | 'watchlist' | 'likes' | undefined {
if (/(^|\/)(deleted|orphaned|lists)\//.test(path)) return undefined
if (/(^|\/)likes\/films\.csv$/.test(path)) return 'likes'
const b = basename(path)
// Fichier déposé seul (hors archive) : likes/films.csv arrive sous le nom « films.csv »
if (b === path && b === 'films.csv') return 'likes'
if (b === 'watched.csv') return 'watched'
if (b === 'ratings.csv') return 'ratings'
if (b === 'diary.csv') return 'diary'
if (b === 'reviews.csv') return 'reviews'
if (b === 'watchlist.csv') return 'watchlist'
return undefined
}
export function parseLetterboxd(files: TextFile[]): ImportEntry[] {
const order = ['watched', 'ratings', 'diary', 'reviews', 'watchlist', 'likes'] as const
const byRole = new Map<string, CsvRow[]>()
for (const f of files) {
const role = letterboxdRole(f.path)
if (role) byRole.set(role, [...(byRole.get(role) ?? []), ...parseCsv(f.text).rows])
}
const films = new Map<string, ImportEntry>()
const views = new Map<string, { day: string; rewatch: boolean }[]>()
const get = (row: CsvRow) => {
const title = cleanText(row.name, LIMITS.title)
if (!title) return undefined
const year = yearOf(row.year)
const key = `lb:${titleKey(title)}|${year ?? ''}`
let e = films.get(key)
if (!e) {
if (films.size >= LIMITS.items) return undefined
e = { key, kind: 'movie', title, year, status: 'a_voir' }
films.set(key, e)
}
touch(e, row.date)
return e
}
const ratingOf = (v?: string) => {
const n = Number(v)
return v && Number.isFinite(n) && n > 0 && n <= 5 ? Math.min(10, Math.round(n * 2 * 2) / 2) : undefined
}
for (const role of order) {
for (const row of byRole.get(role) ?? []) {
const e = get(row)
if (!e) continue
if (role === 'watched') e.status = 'termine'
else if (role === 'ratings') {
e.rating = ratingOf(row.rating) ?? e.rating
e.status = 'termine'
} else if (role === 'diary' || role === 'reviews') {
e.status = 'termine'
if (e.rating == null) e.rating = ratingOf(row.rating)
const day = toDay(row.watched_date) ?? (role === 'diary' ? toDay(row.date) : undefined)
touch(e, row.watched_date)
if (day) views.set(e.key, [...(views.get(e.key) ?? []), { day, rewatch: /^(yes|true|1)$/i.test(row.rewatch ?? '') }])
if (role === 'reviews') e.notes = appendNote(e.notes, cleanText(row.review, LIMITS.notes))
} else if (role === 'likes') e.favorite = true
// watchlist : « à voir » par défaut, sauf si déjà vu
}
}
// Premier visionnage = date de fin, les suivants = revisionnages
for (const [key, list] of views) {
const e = films.get(key)!
const sorted = [...new Map(list.sort((a, b) => a.day.localeCompare(b.day)).map((v) => [v.day, v])).values()]
const first = sorted.find((v) => !v.rewatch)
if (first && first === sorted[0]) e.endDate = first.day
const rewatches = sorted.filter((v) => v.day !== e.endDate).map((v) => v.day)
if (rewatches.length) e.rewatchDates = rewatches.slice(-200)
}
return [...films.values()]
}
// ─────────────────────────── TV Time ───────────────────────────
const SHOW_NAME = ['tv_show_name', 'series_name', 'show_name', 'serie_name', 'series_title', 'show_title', 'tv_show_title']
const SHOW_ID = ['tv_show_id', 'tvdb_show_id', 'series_id', 'serie_id', 'show_id', 'tvdb_id', 's_id', 'tvdb']
const MOVIE_NAME = ['movie_name', 'movie_title', 'film_name']
const SEASON = ['episode_season_number', 'season_number', 'season_num', 'season']
const EPISODE = ['episode_number', 'episode_num', 'number', 'episode']
const DATE = ['watched_at', 'seen_at', 'watch_date', 'created_at', 'updated_at', 'date']
const KIND = ['entity_type', 'media_type', 'object_type', 'item_type', 'type']
export function parseTvTime(files: TextFile[]): ImportEntry[] {
type Row = { row: CsvRow; path: string; generic: boolean }
const rows: Row[] = []
for (const f of files) {
if (!/\.(csv|txt)$/.test(f.path)) continue
const { columns, rows: list } = parseCsv(f.text)
const specific = columns.some((c) => SHOW_NAME.includes(c) || SHOW_ID.includes(c) || MOVIE_NAME.includes(c))
// Colonne « name » / « title » générique : seulement dans un fichier qui parle de séries ou de films
const generic = !specific && (columns.includes('name') || columns.includes('title')) && /(show|serie|series|tv|movie|film)/.test(basename(f.path))
if (!specific && !generic) continue
for (const row of list) rows.push({ row, path: basename(f.path), generic })
}
// Les fichiers n'ont pas tous l'identifiant : on relie les noms aux identifiants TVDB connus
const nameToId = new Map<string, string>()
const showName = (r: Row) => cleanText(pick(r.row, r.generic ? [...SHOW_NAME, 'name', 'title'] : SHOW_NAME), LIMITS.title)
const showId = (r: Row) => {
const v = pick(r.row, SHOW_ID)
return v && /^\d{1,10}$/.test(v) && v !== '0' ? v : undefined
}
for (const r of rows) {
const name = showName(r)
const id = showId(r)
if (name && id && !nameToId.has(titleKey(name))) nameToId.set(titleKey(name), id)
}
const out = new Map<string, ImportEntry>()
for (const r of rows) {
const kindRaw = (pick(r.row, KIND) ?? '').toLowerCase()
const movieName = cleanText(pick(r.row, MOVIE_NAME), LIMITS.title)
const date = pick(r.row, DATE)
const isMovie = !!movieName || /movie|film/.test(kindRaw) || /movie|film/.test(r.path)
if (isMovie) {
const title = movieName ?? showName(r)
if (!title) continue
const imdb = pick(r.row, ['imdb_id', 'imdb'])
const key = `tvt:m:${titleKey(title)}`
const e = out.get(key) ?? { key, kind: 'movie' as const, title, status: 'a_voir' as WatchStatus }
if (imdb && /^tt\d{1,10}$/.test(imdb)) e.imdbId = imdb
e.year ??= yearOf(pick(r.row, ['year', 'release_year', 'movie_year']))
if (/watch|seen|view/.test(kindRaw + ' ' + r.path + ' ' + (pick(r.row, ['type', 'action', 'status']) ?? '').toLowerCase())) {
e.status = 'termine'
const day = toDay(date)
if (day && (!e.endDate || day < e.endDate)) e.endDate = day
}
touch(e, date)
if (out.size < LIMITS.items) out.set(key, e)
continue
}
const name = showName(r)
const id = showId(r) ?? (name ? nameToId.get(titleKey(name)) : undefined)
if (!name && !id) continue
const key = id ? `tvt:${id}` : `tvt:n:${titleKey(name!)}`
let e = out.get(key)
if (!e) {
if (out.size >= LIMITS.items) continue
e = { key, kind: 'tv', title: name ?? `#${id}`, tvdbId: id, status: 'a_voir', seen: new Set() }
out.set(key, e)
} else if (name && e.title.startsWith('#')) e.title = name
const season = Number(pick(r.row, SEASON))
const episode = Number(pick(r.row, EPISODE))
if (Number.isInteger(season) && Number.isInteger(episode) && season >= 1 && season < 1000 && episode >= 1 && episode < 10000) {
if (e.seen!.size < 20000) e.seen!.add(`${season}:${episode}`)
const day = toDay(date)
if (day && (!e.startDate || day < e.startDate)) e.startDate = day
if (day && (!e.endDate || day > e.endDate)) e.endDate = day
}
if (/^(1|true|yes)$/i.test(pick(r.row, ['is_archived', 'archived']) ?? '')) e.archived = true
touch(e, date)
}
return [...out.values()]
}
// ─────────────────────────── MyAnimeList ───────────────────────────
const MAL_STATUS: Record<string, WatchStatus> = {
watching: 'en_cours',
'1': 'en_cours',
completed: 'termine',
'2': 'termine',
'on-hold': 'pause',
onhold: 'pause',
'3': 'pause',
dropped: 'abandonne',
'4': 'abandonne',
'plan to watch': 'a_voir',
plantowatch: 'a_voir',
'6': 'a_voir',
}
export function parseMal(xml: string): ImportEntry[] {
const doc = new DOMParser().parseFromString(xml, 'application/xml')
if (doc.getElementsByTagName('parsererror').length) throw new Error('xml')
const out: ImportEntry[] = []
const nodes = Array.from(doc.getElementsByTagName('anime')).slice(0, LIMITS.items)
for (const n of nodes) {
const get = (tag: string) => n.getElementsByTagName(tag)[0]?.textContent?.trim() ?? ''
const malId = Number(get('series_animedb_id'))
const title = cleanText(get('series_title'), LIMITS.title)
if (!title || !Number.isInteger(malId) || malId <= 0) continue
const score = Number(get('my_score'))
const watched = Number(get('my_watched_episodes'))
const updated = Number(get('my_last_updated'))
const e: ImportEntry = {
key: `mal:${malId}`,
kind: 'anime',
title,
malId,
format: get('series_type').toUpperCase() || undefined,
status: MAL_STATUS[get('my_status').toLowerCase()] ?? 'a_voir',
rating: Number.isFinite(score) && score > 0 && score <= 10 ? score : undefined,
episodesWatched: Number.isInteger(watched) && watched > 0 ? Math.min(watched, 100000) : undefined,
startDate: toDay(get('my_start_date')),
endDate: toDay(get('my_finish_date')),
notes: cleanText(get('my_comments'), LIMITS.notes),
}
if (Number.isFinite(updated) && updated > 0) touch(e, new Date(updated * 1000).toISOString())
touch(e, e.startDate)
touch(e, e.endDate)
out.push(e)
}
return out
}
// ─────────────────────────── AniList (réponse déjà téléchargée) ───────────────────────────
export interface AniListEntry {
status?: string | null
score?: number | null
progress?: number | null
repeat?: number | null
notes?: string | null
updatedAt?: number | null
startedAt?: { year?: number | null; month?: number | null; day?: number | null } | null
completedAt?: { year?: number | null; month?: number | null; day?: number | null } | null
media?: AniMedia | null
}
const ANILIST_STATUS: Record<string, WatchStatus> = {
CURRENT: 'en_cours',
REPEATING: 'en_cours',
COMPLETED: 'termine',
PAUSED: 'pause',
DROPPED: 'abandonne',
PLANNING: 'a_voir',
}
const fuzzyDay = (d?: AniListEntry['startedAt']) => {
if (!d?.year || !d.month || !d.day) return undefined
return safeDay(`${d.year}-${String(d.month).padStart(2, '0')}-${String(d.day).padStart(2, '0')}`)
}
/** Entrées d'une liste AniList (score demandé en POINT_100). */
export function anilistEntries(list: AniListEntry[]): ImportEntry[] {
const out = new Map<string, ImportEntry>()
for (const x of list.slice(0, LIMITS.items)) {
const m = x?.media
if (!m || !Number.isInteger(m.id) || m.id <= 0) continue
const title = cleanText(m.title?.english || m.title?.romaji || m.title?.native, LIMITS.title)
if (!title) continue
const score = typeof x.score === 'number' && x.score > 0 ? Math.min(10, Math.round(x.score / 10 * 2) / 2) : undefined
const e: ImportEntry = {
key: `al:${m.id}`,
kind: 'anime',
title,
year: m.seasonYear ?? m.startDate?.year ?? undefined,
anilistId: m.id,
media: m,
format: m.format ?? undefined,
status: ANILIST_STATUS[x.status ?? ''] ?? 'a_voir',
rating: score || undefined,
episodesWatched: typeof x.progress === 'number' && x.progress > 0 ? Math.min(100000, Math.round(x.progress)) : undefined,
startDate: fuzzyDay(x.startedAt),
endDate: fuzzyDay(x.completedAt),
notes: cleanText(x.notes, LIMITS.notes),
}
if (typeof x.updatedAt === 'number' && x.updatedAt > 0) touch(e, new Date(x.updatedAt * 1000).toISOString())
touch(e, e.startDate)
touch(e, e.endDate)
out.set(e.key, e)
}
return [...out.values()]
}