import { ArrowLeft, Check, ChevronDown, FileUp, Loader2, X } from 'lucide-react' import { useEffect, useMemo, useRef, useState, type DragEvent } from 'react' import { t, type TKey } from '../i18n' import { useBackToClose } from '../lib/backNav' import { useEscape } from '../lib/escape' import { ImportFileError, readImportFile, type TextFile } from '../lib/import/files' import { buildImportPlan, countByKind, type ImportPlan } from '../lib/import/merge' import { CancelledError, fetchAniListUser, isAniListUserName, resolveEntries, type CancelToken, type Match, type Progress } from '../lib/import/resolve' import { letterboxdRole, parseLetterboxd, parseMal, parseTvTime, type ImportEntry, type ImportSource } from '../lib/import/sources' import { useScrollLock } from '../lib/scrollLock' import { LIMITS } from '../lib/security' import { cx } from '../lib/utils' import { useMedia } from '../store' /** * Assistant « Importer depuis une autre app » : Letterboxd, TV Time, MyAnimeList, AniList. * Source → fichier (ou nom d'utilisateur) → recherche des fiches → aperçu → fusion → résumé. * Tout se passe sur l'appareil ; la synchro existante enverra ensuite les fiches au compte. */ type Step = 'source' | 'input' | 'working' | 'preview' | 'done' const SOURCES: { id: ImportSource; name: string; mark: string; accept?: string; multiple?: boolean }[] = [ { id: 'letterboxd', name: 'Letterboxd', mark: 'Lb', accept: '.zip,.csv,application/zip,text/csv', multiple: true }, { id: 'tvtime', name: 'TV Time', mark: 'TV', accept: '.zip,.csv,application/zip,text/csv', multiple: true }, { id: 'mal', name: 'MyAnimeList', mark: 'MAL', accept: '.xml,.gz,application/xml,text/xml,application/gzip' }, { id: 'anilist', name: 'AniList', mark: 'AL' }, ] const NEEDS_TMDB: ImportSource[] = ['letterboxd', 'tvtime'] /** Message lisible pour une erreur de lecture / de réseau. */ function errorText(e: unknown): string { if (e instanceof ImportFileError) { const k = `import.err.${e.message}` as TKey return ['tooBig', 'badZip', 'encrypted', 'unsupported'].includes(e.message) ? t(k) : t('import.err.read') } const msg = (e as Error)?.message if (msg === 'anilist-user') return t('import.err.user') if (msg === 'rate') return t('err.anilistRate') if (!navigator.onLine) return t('search.offline') return msg || t('import.err.read') } async function readEntries(source: ImportSource, files: File[]): Promise { const texts: TextFile[] = [] for (const f of files.slice(0, 40)) { const keep = source === 'letterboxd' ? (p: string) => !!letterboxdRole(p) : source === 'mal' ? (p: string) => /\.xml$/.test(p) : (p: string) => /\.csv$/.test(p) texts.push(...(await readImportFile(f, keep, LIMITS.importFileBytes))) } if (source === 'letterboxd') return parseLetterboxd(texts) if (source === 'tvtime') return parseTvTime(texts) const xml = texts.find((x) => x.text.includes('')) if (!xml) throw new ImportFileError('read') return parseMal(xml.text) } export default function ImportWizard({ onClose }: { onClose: () => void }) { const { items, settings, importItems } = useMedia() const [step, setStep] = useState('source') const [source, setSource] = useState() const [userName, setUserName] = useState('') const [error, setError] = useState() const [phase, setPhase] = useState<'reading' | 'resolving' | 'saving'>('reading') const [progress, setProgress] = useState({ done: 0, total: 0 }) const [entries, setEntries] = useState([]) const [matches, setMatches] = useState>(new Map()) const [includeUnmatched, setIncludeUnmatched] = useState(false) const [showMissing, setShowMissing] = useState(false) const [result, setResult] = useState<{ added: number; updated: number; unchanged: number; notFound: number }>() const [dragging, setDragging] = useState(false) const [now, setNow] = useState(Date.now()) const token = useRef({ cancelled: false }) const fileRef = useRef(null) const close = () => { token.current.cancelled = true onClose() } useScrollLock() useEscape(close) useBackToClose(close) // Fermeture de l'assistant : la recherche en cours s'arrête useEffect(() => () => void (token.current.cancelled = true), []) // Compte à rebours pendant une pause imposée par la limite de débit useEffect(() => { if (!progress.waitUntil) return const id = setInterval(() => setNow(Date.now()), 500) return () => clearInterval(id) }, [progress.waitUntil]) const info = SOURCES.find((s) => s.id === source) const hasTmdb = !!settings.tmdbKey?.trim() const plan: ImportPlan | undefined = useMemo( () => (step === 'preview' ? buildImportPlan(entries, matches, items, { includeUnmatched }) : undefined), [step, entries, matches, items, includeUnmatched], ) const run = async (load: () => Promise) => { const tk = { cancelled: false } token.current = tk setError(undefined) setStep('working') setPhase('reading') setProgress({ done: 0, total: 0 }) try { const list = await load() if (tk.cancelled) return if (!list.length) throw new Error(t('import.err.empty')) setEntries(list) setPhase('resolving') const found = await resolveEntries(list, { tmdbKey: settings.tmdbKey, token: tk, onProgress: (p) => !tk.cancelled && setProgress(p) }) if (tk.cancelled) return setMatches(found) setShowMissing(false) setIncludeUnmatched(false) setStep('preview') } catch (e) { if (e instanceof CancelledError || tk.cancelled) return setError(errorText(e)) setStep('input') } } const onFiles = (list: FileList | null | undefined) => { const files = Array.from(list ?? []) if (fileRef.current) fileRef.current.value = '' if (!files.length || !source || source === 'anilist') return void run(() => readEntries(source, files)) } const onAniList = () => { const name = userName.trim() if (!isAniListUserName(name)) return setError(t('import.err.user')) void run(async () => (await fetchAniListUser(name)).entries) } const cancelWork = () => { token.current.cancelled = true setStep('input') } const confirm = async () => { if (!plan) return setStep('working') setPhase('saving') try { await importItems([...plan.added, ...plan.updated], 'merge') setResult({ added: plan.added.length, updated: plan.updated.length, unchanged: plan.unchanged, notFound: includeUnmatched ? 0 : plan.notFound.length }) setStep('done') } catch (e) { setError(errorText(e)) setStep('preview') } } const onDrop = (e: DragEvent) => { e.preventDefault() setDragging(false) onFiles(e.dataTransfer?.files) } const back = () => { setError(undefined) setStep(step === 'preview' ? 'input' : 'source') } const pct = progress.total ? Math.round((progress.done / progress.total) * 100) : 0 const wait = progress.waitUntil ? Math.max(0, Math.ceil((progress.waitUntil - now) / 1000)) : 0 const kinds = plan ? countByKind(plan.added) : undefined return (
{step === 'input' || step === 'preview' ? ( ) : ( )}

{info && step !== 'source' ? info.name : t('import.title')}

{step === 'source' && ( <>

{t('import.chooseSource')}

{SOURCES.map((s) => ( ))}

{t('import.mergeHint')}

)} {step === 'input' && info && ( <> {t('import.how')}
    {t(`import.steps.${info.id}` as TKey) .split('\n') .map((line, i) => (
  1. {i + 1} {line}
  2. ))}
{NEEDS_TMDB.includes(info.id) && !hasTmdb && (

{t('import.noTmdb')}

)} {info.id === 'anilist' ? (
{ e.preventDefault() onAniList() }} > setUserName(e.target.value.slice(0, 20))} placeholder={t('import.userName')} aria-label={t('import.userName')} autoCapitalize="off" autoComplete="off" spellCheck={false} enterKeyHint="go" />
) : ( <> onFiles(e.target.files)} /> )}

{t('import.privacy')}

{error && (

{error}

)} )} {step === 'working' && (

{phase === 'reading' ? t('import.reading') : phase === 'saving' ? t('import.importing') : t('import.resolving')}

{phase === 'resolving' && progress.total > 0 && ( <>

{t('import.progress', { done: progress.done, total: progress.total })}

{wait > 0 &&

{t('import.rateWait', { s: wait })}

} )} {phase !== 'saving' && ( )}
)} {step === 'preview' && plan && kinds && ( <>

{t('import.found', { n: entries.length })}

{( [ [kinds.films, t('typePlural.film')], [kinds.series, t('typePlural.serie')], [kinds.anime, t('typePlural.anime')], ] as const ).map(([n, label]) => (
{n} {label}
))}
0} />
{plan.notFound.length > 0 && (
{showMissing && (
    {plan.notFound.slice(0, 500).map((e) => (
  • {e.title} {e.year && {e.year}}
  • ))}
)}
)}

{t('import.mergeHint')}

{error &&

{error}

} {plan.added.length + plan.updated.length > 0 ? ( ) : (

{t('import.nothing')}

)} )} {step === 'done' && result && (

{t('import.done')}

{result.notFound > 0 && }
)}
) } function Line({ label, value, strong, accent }: { label: string; value: number; strong?: boolean; accent?: boolean }) { return (
{label} {value}
) }