From 945ee3220091ae725d09f5a532d576abf3922592 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 9 Oct 2026 15:18:28 +0000 Subject: [PATCH] Import depuis Letterboxd, TV Time, MyAnimeList et AniList MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe --- src/components/ImportWizard.tsx | 414 +++++++++++++++++++++++++++++++ src/i18n/locales/ar.ts | 47 ++++ src/i18n/locales/de.ts | 47 ++++ src/i18n/locales/en.ts | 47 ++++ src/i18n/locales/es.ts | 47 ++++ src/i18n/locales/fr.ts | 47 ++++ src/i18n/locales/hi.ts | 47 ++++ src/i18n/locales/id.ts | 47 ++++ src/i18n/locales/it.ts | 47 ++++ src/i18n/locales/ja.ts | 47 ++++ src/i18n/locales/ko.ts | 47 ++++ src/i18n/locales/nl.ts | 47 ++++ src/i18n/locales/pl.ts | 47 ++++ src/i18n/locales/pt.ts | 47 ++++ src/i18n/locales/ru.ts | 47 ++++ src/i18n/locales/th.ts | 47 ++++ src/i18n/locales/tr.ts | 47 ++++ src/i18n/locales/vi.ts | 47 ++++ src/i18n/locales/zh.ts | 47 ++++ src/lib/catalogApi.ts | 49 +++- src/lib/import/files.ts | 186 ++++++++++++++ src/lib/import/merge.ts | 299 ++++++++++++++++++++++ src/lib/import/resolve.ts | 315 +++++++++++++++++++++++ src/lib/import/sources.ts | 352 ++++++++++++++++++++++++++ src/pages/SettingsPage.tsx | 6 +- supabase/functions/tmdb/index.ts | 4 +- 26 files changed, 2468 insertions(+), 3 deletions(-) create mode 100644 src/components/ImportWizard.tsx create mode 100644 src/lib/import/files.ts create mode 100644 src/lib/import/merge.ts create mode 100644 src/lib/import/resolve.ts create mode 100644 src/lib/import/sources.ts diff --git a/src/components/ImportWizard.tsx b/src/components/ImportWizard.tsx new file mode 100644 index 0000000..2d105b2 --- /dev/null +++ b/src/components/ImportWizard.tsx @@ -0,0 +1,414 @@ +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} +
+ ) +} diff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.ts index f043a88..751d02d 100644 --- a/src/i18n/locales/ar.ts +++ b/src/i18n/locales/ar.ts @@ -1035,6 +1035,53 @@ const dict: Translations = { 'sync.pending_two': "تعديلان في الانتظار", 'sync.pending_few': "{count} تعديلات في الانتظار", 'sync.pending_many': "{count} تعديلًا في الانتظار", + // — Import depuis d'autres applis — + 'import.row': "الاستيراد من تطبيق آخر", + 'import.rowHint': "Letterboxd وTV Time وMyAnimeList وAniList", + 'import.title': "استيراد مكتبتي", + 'import.chooseSource': "من أين تأتي عناوينك؟", + 'import.src.letterboxd': "أفلام وتقييمات ويوميات وقائمة مشاهدة وإعجابات", + 'import.src.tvtime': "المسلسلات المتابَعة والحلقات المشاهَدة", + 'import.src.mal': "قائمة الأنمي (تصدير XML)", + 'import.src.anilist': "قائمة أنمي عامة، باسم المستخدم", + 'import.how': "الحصول على ملف التصدير", + 'import.steps.letterboxd': "على letterboxd.com افتح Settings ← Import & Export ← Export your data.\nستحصل على ملف ZIP: أفلته هنا كما هو (أو ملفات CSV التي فيه).", + 'import.steps.tvtime': "في TV Time اطلب نسخة من بياناتك (الإعدادات ← الخصوصية، أو الدعم «Request my data»).\nأفلت هنا ملف ZIP الذي وصلك بالبريد، أو ملفات CSV التي فيه.", + 'import.steps.mal': "على myanimelist.net افتح ملفك ← Export (Anime List) ← Export My List.\nأفلت هنا ملف ‎.xml.gz الذي نزّلته (أو ‎.xml).", + 'import.steps.anilist': "يجب أن تكون قائمتك على AniList عامة (Settings ← Lists).\nأدخل اسم المستخدم: لا حاجة لتسجيل الدخول.", + 'import.drop': "اختر الملف أو أفلته", + 'import.privacy': "يُقرأ الملف على جهازك: لا يُبحث على الإنترنت إلا عن العناوين.", + 'import.userName': "اسم المستخدم على AniList", + 'import.continue': "متابعة", + 'import.back': "رجوع", + 'import.reading': "جارٍ قراءة الملف…", + 'import.resolving': "جارٍ البحث عن العناوين…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "تم بلوغ حد الطلبات، الاستئناف بعد {s} ث…", + 'import.cancel': "إلغاء", + 'import.noTmdb': "بدون TMDB لا يمكن التعرف على الأفلام والمسلسلات: أضف مفتاحًا في الإعدادات ← قواعد البيانات (أو سجّل الدخول)، أو استوردها بلا ملصق.", + 'import.found': "العناوين المقروءة من التصدير: {n}", + 'import.new': "سجلات جديدة", + 'import.toUpdate': "سجلات مكتملة", + 'import.already': "محدّثة مسبقًا", + 'import.notFound': "غير موجودة", + 'import.showNotFound': "عرض العناوين غير الموجودة", + 'import.hideNotFound': "إخفاء القائمة", + 'import.includeUnmatched': "إضافة العناوين غير الموجودة أيضًا (بلا ملصق)", + 'import.mergeHint': "لا يُستبدل شيء: تبقى تقييماتك وحالاتك وتواريخك الأحدث، ولا تُنشأ أي نسخ مكررة.", + 'import.confirm': "استيراد ({n})", + 'import.importing': "جارٍ الاستيراد…", + 'import.nothing': "لا جديد للاستيراد.", + 'import.done': "اكتمل الاستيراد", + 'import.doneAdded': "المضافة", + 'import.close': "إنهاء", + 'import.err.tooBig': "الملف كبير جدًا.", + 'import.err.badZip': "تعذّرت قراءة أرشيف ZIP.", + 'import.err.encrypted': "أرشيف محمي بكلمة مرور: تتعذّر قراءته.", + 'import.err.unsupported': "لا يستطيع متصفحك فك ضغط هذا الملف: أفلت ملفات CSV / XML غير المضغوطة بدلًا منه.", + 'import.err.read': "الملف غير معروف لهذا المصدر.", + 'import.err.empty': "لم يُعثر على أي عنوان في هذا الملف.", + 'import.err.user': "مستخدم AniList غير موجود، أو القائمة خاصة.", } export default dict diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 27a5e64..645b5be 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} Änderung ausstehend", 'sync.pending_other': "{count} Änderungen ausstehend", 'sync.now': "Jetzt synchronisieren", + // — Import depuis d'autres applis — + 'import.row': "Aus einer anderen App importieren", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Meine Bibliothek importieren", + 'import.chooseSource': "Woher kommen deine Titel?", + 'import.src.letterboxd': "Filme, Bewertungen, Tagebuch, Watchlist und Likes", + 'import.src.tvtime': "Verfolgte Serien und gesehene Folgen", + 'import.src.mal': "Anime-Liste (XML-Export)", + 'import.src.anilist': "Öffentliche Anime-Liste, per Benutzername", + 'import.how': "Export besorgen", + 'import.steps.letterboxd': "Öffne auf letterboxd.com Settings → Import & Export → Export your data.\nDu erhältst eine ZIP-Datei: lege sie unverändert hier ab (oder ihre CSV-Dateien).", + 'import.steps.tvtime': "Fordere in TV Time eine Kopie deiner Daten an (Einstellungen → Datenschutz oder Support „Request my data“).\nLege die per E-Mail erhaltene ZIP-Datei oder ihre CSV-Dateien hier ab.", + 'import.steps.mal': "Öffne auf myanimelist.net dein Profil → Export (Anime List) → Export My List.\nLege die heruntergeladene .xml.gz-Datei (oder die .xml) hier ab.", + 'import.steps.anilist': "Deine AniList-Liste muss öffentlich sein (Settings → Lists).\nGib deinen Benutzernamen ein: keine Anmeldung nötig.", + 'import.drop': "Datei wählen oder ablegen", + 'import.privacy': "Die Datei wird auf deinem Gerät gelesen: nur die Titel werden online gesucht.", + 'import.userName': "AniList-Benutzername", + 'import.continue': "Weiter", + 'import.back': "Zurück", + 'import.reading': "Datei wird gelesen…", + 'import.resolving': "Titel werden gesucht…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Anfragelimit erreicht, weiter in {s} s…", + 'import.cancel': "Abbrechen", + 'import.noTmdb': "Ohne TMDB können Filme und Serien nicht erkannt werden: füge in Einstellungen → Datenbanken einen Schlüssel hinzu (oder melde dich an) oder importiere sie ohne Poster.", + 'import.found': "Aus dem Export gelesene Titel: {n}", + 'import.new': "Neue Einträge", + 'import.toUpdate': "Ergänzte Einträge", + 'import.already': "Bereits aktuell", + 'import.notFound': "Nicht gefunden", + 'import.showNotFound': "Nicht gefundene Titel anzeigen", + 'import.hideNotFound': "Liste ausblenden", + 'import.includeUnmatched': "Nicht gefundene Titel trotzdem hinzufügen (ohne Poster)", + 'import.mergeHint': "Nichts wird überschrieben: deine neueren Bewertungen, Status und Daten bleiben erhalten, und es entstehen keine Duplikate.", + 'import.confirm': "Importieren ({n})", + 'import.importing': "Import läuft…", + 'import.nothing': "Nichts Neues zu importieren.", + 'import.done': "Import abgeschlossen", + 'import.doneAdded': "Hinzugefügt", + 'import.close': "Fertig", + 'import.err.tooBig': "Datei zu groß.", + 'import.err.badZip': "ZIP-Archiv nicht lesbar.", + 'import.err.encrypted': "Passwortgeschütztes Archiv: kann nicht gelesen werden.", + 'import.err.unsupported': "Dein Browser kann diese Datei nicht entpacken: lege stattdessen die entpackten CSV-/XML-Dateien ab.", + 'import.err.read': "Datei für diese Quelle nicht erkannt.", + 'import.err.empty': "Keine Titel in dieser Datei gefunden.", + 'import.err.user': "AniList-Nutzer nicht gefunden oder Liste privat.", } export default dict diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 485d651..f0a1ba9 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} change waiting", 'sync.pending_other': "{count} changes waiting", 'sync.now': "Sync now", + // — Import depuis d'autres applis — + 'import.row': "Import from another app", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Import my library", + 'import.chooseSource': "Where are your titles coming from?", + 'import.src.letterboxd': "Films, ratings, diary, watchlist and likes", + 'import.src.tvtime': "Followed shows and watched episodes", + 'import.src.mal': "Anime list (XML export)", + 'import.src.anilist': "Public anime list, by username", + 'import.how': "Getting the export", + 'import.steps.letterboxd': "On letterboxd.com, open Settings → Import & Export → Export your data.\nYou get a ZIP file: drop it here as is (or its CSV files).", + 'import.steps.tvtime': "In TV Time, request a copy of your data (Settings → Privacy, or support “Request my data”).\nDrop the ZIP you received by email here, or its CSV files.", + 'import.steps.mal': "On myanimelist.net, open your profile → Export (Anime List) → Export My List.\nDrop the downloaded .xml.gz file here (or the .xml).", + 'import.steps.anilist': "Your AniList list must be public (Settings → Lists).\nEnter your username: no sign-in needed.", + 'import.drop': "Choose or drop the file", + 'import.privacy': "The file is read on your device: only titles are looked up online.", + 'import.userName': "AniList username", + 'import.continue': "Continue", + 'import.back': "Back", + 'import.reading': "Reading the file…", + 'import.resolving': "Finding titles…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Request limit reached, resuming in {s} s…", + 'import.cancel': "Cancel", + 'import.noTmdb': "Without TMDB, films and shows cannot be recognised: add a key in Settings → Databases (or sign in), or import them without posters.", + 'import.found': "Titles read from the export: {n}", + 'import.new': "New entries", + 'import.toUpdate': "Entries completed", + 'import.already': "Already up to date", + 'import.notFound': "Not found", + 'import.showNotFound': "Show titles not found", + 'import.hideNotFound': "Hide the list", + 'import.includeUnmatched': "Also add titles not found (without poster)", + 'import.mergeHint': "Nothing is overwritten: your newer ratings, statuses and dates are kept, and no duplicates are created.", + 'import.confirm': "Import ({n})", + 'import.importing': "Importing…", + 'import.nothing': "Nothing new to import.", + 'import.done': "Import complete", + 'import.doneAdded': "Added", + 'import.close': "Done", + 'import.err.tooBig': "File too large.", + 'import.err.badZip': "Unreadable ZIP archive.", + 'import.err.encrypted': "Password-protected archive: it cannot be read.", + 'import.err.unsupported': "Your browser cannot decompress this file: drop the uncompressed CSV / XML files instead.", + 'import.err.read': "File not recognised for this source.", + 'import.err.empty': "No titles found in this file.", + 'import.err.user': "AniList user not found, or the list is private.", } export default dict diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 7cf4d14..6f2c66f 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} cambio pendiente", 'sync.pending_other': "{count} cambios pendientes", 'sync.now': "Sincronizar", + // — Import depuis d'autres applis — + 'import.row': "Importar desde otra app", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Importar mi biblioteca", + 'import.chooseSource': "¿De dónde vienen tus títulos?", + 'import.src.letterboxd': "Películas, notas, diario, pendientes y favoritas", + 'import.src.tvtime': "Series seguidas y episodios vistos", + 'import.src.mal': "Lista de animes (exportación XML)", + 'import.src.anilist': "Lista de animes pública, por nombre de usuario", + 'import.how': "Obtener la exportación", + 'import.steps.letterboxd': "En letterboxd.com, abre Settings → Import & Export → Export your data.\nRecibes un archivo ZIP: suéltalo aquí tal cual (o sus archivos CSV).", + 'import.steps.tvtime': "En TV Time, solicita una copia de tus datos (Ajustes → Privacidad, o soporte «Request my data»).\nSuelta aquí el ZIP recibido por correo, o sus archivos CSV.", + 'import.steps.mal': "En myanimelist.net, abre tu perfil → Export (Anime List) → Export My List.\nSuelta aquí el archivo .xml.gz descargado (o el .xml).", + 'import.steps.anilist': "Tu lista de AniList debe ser pública (Settings → Lists).\nIndica tu nombre de usuario: no hace falta iniciar sesión.", + 'import.drop': "Elegir o soltar el archivo", + 'import.privacy': "El archivo se lee en tu dispositivo: solo se buscan los títulos en línea.", + 'import.userName': "Nombre de usuario de AniList", + 'import.continue': "Continuar", + 'import.back': "Volver", + 'import.reading': "Leyendo el archivo…", + 'import.resolving': "Buscando las fichas…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Límite de solicitudes alcanzado, se reanuda en {s} s…", + 'import.cancel': "Cancelar", + 'import.noTmdb': "Sin TMDB, las películas y series no se pueden reconocer: añade una clave en Ajustes → Bases de datos (o inicia sesión), o impórtalas sin póster.", + 'import.found': "Títulos leídos en la exportación: {n}", + 'import.new': "Fichas nuevas", + 'import.toUpdate': "Fichas completadas", + 'import.already': "Ya al día", + 'import.notFound': "No encontrados", + 'import.showNotFound': "Ver los títulos no encontrados", + 'import.hideNotFound': "Ocultar la lista", + 'import.includeUnmatched': "Añadir también los títulos no encontrados (sin póster)", + 'import.mergeHint': "No se sobrescribe nada: se conservan tus notas, estados y fechas más recientes, y no se crean duplicados.", + 'import.confirm': "Importar ({n})", + 'import.importing': "Importando…", + 'import.nothing': "Nada nuevo que importar.", + 'import.done': "Importación terminada", + 'import.doneAdded': "Añadidos", + 'import.close': "Terminar", + 'import.err.tooBig': "Archivo demasiado grande.", + 'import.err.badZip': "Archivo ZIP ilegible.", + 'import.err.encrypted': "Archivo protegido con contraseña: no se puede leer.", + 'import.err.unsupported': "Tu navegador no puede descomprimir este archivo: suelta mejor los archivos CSV / XML descomprimidos.", + 'import.err.read': "Archivo no reconocido para esta fuente.", + 'import.err.empty': "No se encontró ningún título en este archivo.", + 'import.err.user': "Usuario de AniList no encontrado, o lista privada.", } export default dict diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 1898226..d42017d 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -899,6 +899,53 @@ const dict = { 'sync.pending_one': "{count} modification en attente", 'sync.pending_other': "{count} modifications en attente", 'sync.now': "Synchroniser", + // — Import depuis d'autres applis — + 'import.row': "Importer depuis une autre app", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Importer ma bibliothèque", + 'import.chooseSource': "D'où viennent tes titres ?", + 'import.src.letterboxd': "Films, notes, journal, envies et coups de cœur", + 'import.src.tvtime': "Séries suivies et épisodes vus", + 'import.src.mal': "Liste d'animes (export XML)", + 'import.src.anilist': "Liste d'animes publique, par nom d'utilisateur", + 'import.how': "Récupérer l'export", + 'import.steps.letterboxd': "Sur letterboxd.com, ouvre Settings → Import & Export → Export your data.\nTu reçois un fichier ZIP : dépose-le ici tel quel (ou ses fichiers CSV).", + 'import.steps.tvtime': "Dans TV Time, demande une copie de tes données (Paramètres → Confidentialité, ou support « Request my data »).\nDépose ici le ZIP reçu par e-mail, ou ses fichiers CSV.", + 'import.steps.mal': "Sur myanimelist.net, ouvre ton profil → Export (Anime List) → Export My List.\nDépose ici le fichier .xml.gz téléchargé (ou le .xml).", + 'import.steps.anilist': "Ta liste AniList doit être publique (Settings → Lists).\nIndique ton nom d'utilisateur : aucune connexion n'est nécessaire.", + 'import.drop': "Choisir ou déposer le fichier", + 'import.privacy': "Le fichier est lu sur ton appareil : seuls les titres sont recherchés en ligne.", + 'import.userName': "Nom d'utilisateur AniList", + 'import.continue': "Continuer", + 'import.back': "Retour", + 'import.reading': "Lecture du fichier…", + 'import.resolving': "Recherche des fiches…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Limite de requêtes atteinte, reprise dans {s} s…", + 'import.cancel': "Annuler", + 'import.noTmdb': "Sans TMDB, les films et séries ne peuvent pas être reconnus : ajoute une clé dans Réglages → Bases de données (ou connecte-toi), ou importe-les sans affiche.", + 'import.found': "Titres lus dans l'export : {n}", + 'import.new': "Nouvelles fiches", + 'import.toUpdate': "Fiches complétées", + 'import.already': "Déjà à jour", + 'import.notFound': "Non trouvés", + 'import.showNotFound': "Voir les titres non trouvés", + 'import.hideNotFound': "Masquer la liste", + 'import.includeUnmatched': "Ajouter aussi les titres non trouvés (sans affiche)", + 'import.mergeHint': "Rien n'est écrasé : tes notes, statuts et dates plus récents sont gardés, et aucun doublon n'est créé.", + 'import.confirm': "Importer ({n})", + 'import.importing': "Import en cours…", + 'import.nothing': "Rien de nouveau à importer.", + 'import.done': "Import terminé", + 'import.doneAdded': "Ajoutés", + 'import.close': "Terminer", + 'import.err.tooBig': "Fichier trop volumineux.", + 'import.err.badZip': "Archive ZIP illisible.", + 'import.err.encrypted': "Archive protégée par un mot de passe : impossible de la lire.", + 'import.err.unsupported': "Ton navigateur ne sait pas décompresser ce fichier : dépose plutôt les fichiers CSV / XML décompressés.", + 'import.err.read': "Fichier non reconnu pour cette source.", + 'import.err.empty': "Aucun titre trouvé dans ce fichier.", + 'import.err.user': "Membre AniList introuvable, ou liste privée.", } export default dict diff --git a/src/i18n/locales/hi.ts b/src/i18n/locales/hi.ts index db825eb..020608d 100644 --- a/src/i18n/locales/hi.ts +++ b/src/i18n/locales/hi.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} बदलाव बाकी", 'sync.pending_other': "{count} बदलाव बाकी", 'sync.now': "अभी सिंक करें", + // — Import depuis d'autres applis — + 'import.row': "दूसरे ऐप से इंपोर्ट करें", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "मेरी लाइब्रेरी इंपोर्ट करें", + 'import.chooseSource': "आपके टाइटल कहाँ से आ रहे हैं?", + 'import.src.letterboxd': "फ़िल्में, रेटिंग, डायरी, वॉचलिस्ट और पसंद", + 'import.src.tvtime': "फ़ॉलो की गई सीरीज़ और देखे गए एपिसोड", + 'import.src.mal': "एनीमे सूची (XML एक्सपोर्ट)", + 'import.src.anilist': "सार्वजनिक एनीमे सूची, यूज़रनेम से", + 'import.how': "एक्सपोर्ट कैसे पाएँ", + 'import.steps.letterboxd': "letterboxd.com पर Settings → Import & Export → Export your data खोलें।\nआपको एक ZIP फ़ाइल मिलेगी: उसे जैसी है वैसी यहाँ छोड़ें (या उसकी CSV फ़ाइलें)।", + 'import.steps.tvtime': "TV Time में अपने डेटा की कॉपी माँगें (सेटिंग्स → प्राइवेसी, या सपोर्ट “Request my data”)।\nईमेल से मिली ZIP या उसकी CSV फ़ाइलें यहाँ छोड़ें।", + 'import.steps.mal': "myanimelist.net पर अपनी प्रोफ़ाइल → Export (Anime List) → Export My List खोलें।\nडाउनलोड की गई .xml.gz फ़ाइल (या .xml) यहाँ छोड़ें।", + 'import.steps.anilist': "आपकी AniList सूची सार्वजनिक होनी चाहिए (Settings → Lists)।\nअपना यूज़रनेम लिखें: लॉग इन की ज़रूरत नहीं।", + 'import.drop': "फ़ाइल चुनें या छोड़ें", + 'import.privacy': "फ़ाइल आपके डिवाइस पर पढ़ी जाती है: ऑनलाइन सिर्फ़ टाइटल खोजे जाते हैं।", + 'import.userName': "AniList यूज़रनेम", + 'import.continue': "आगे बढ़ें", + 'import.back': "वापस", + 'import.reading': "फ़ाइल पढ़ी जा रही है…", + 'import.resolving': "टाइटल खोजे जा रहे हैं…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "अनुरोध सीमा पूरी हुई, {s} सेकंड में फिर शुरू…", + 'import.cancel': "रद्द करें", + 'import.noTmdb': "TMDB के बिना फ़िल्में और सीरीज़ पहचानी नहीं जा सकतीं: सेटिंग्स → डेटाबेस में कुंजी जोड़ें (या लॉग इन करें), या उन्हें बिना पोस्टर के इंपोर्ट करें।", + 'import.found': "एक्सपोर्ट से पढ़े गए टाइटल: {n}", + 'import.new': "नई प्रविष्टियाँ", + 'import.toUpdate': "पूरी की गई प्रविष्टियाँ", + 'import.already': "पहले से अपडेट", + 'import.notFound': "नहीं मिले", + 'import.showNotFound': "न मिले टाइटल देखें", + 'import.hideNotFound': "सूची छिपाएँ", + 'import.includeUnmatched': "न मिले टाइटल भी जोड़ें (बिना पोस्टर)", + 'import.mergeHint': "कुछ भी ओवरराइट नहीं होता: आपकी नई रेटिंग, स्टेटस और तारीखें रहती हैं, और कोई डुप्लिकेट नहीं बनता।", + 'import.confirm': "इंपोर्ट करें ({n})", + 'import.importing': "इंपोर्ट हो रहा है…", + 'import.nothing': "इंपोर्ट करने को कुछ नया नहीं।", + 'import.done': "इंपोर्ट पूरा हुआ", + 'import.doneAdded': "जोड़े गए", + 'import.close': "पूरा", + 'import.err.tooBig': "फ़ाइल बहुत बड़ी है।", + 'import.err.badZip': "ZIP आर्काइव पढ़ा नहीं जा सका।", + 'import.err.encrypted': "पासवर्ड से सुरक्षित आर्काइव: पढ़ा नहीं जा सकता।", + 'import.err.unsupported': "आपका ब्राउज़र यह फ़ाइल अनज़िप नहीं कर सकता: अनज़िप की हुई CSV / XML फ़ाइलें छोड़ें।", + 'import.err.read': "इस स्रोत के लिए फ़ाइल पहचानी नहीं गई।", + 'import.err.empty': "इस फ़ाइल में कोई टाइटल नहीं मिला।", + 'import.err.user': "AniList यूज़र नहीं मिला, या सूची निजी है।", } export default dict diff --git a/src/i18n/locales/id.ts b/src/i18n/locales/id.ts index 5da9809..3fe53fc 100644 --- a/src/i18n/locales/id.ts +++ b/src/i18n/locales/id.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} perubahan menunggu", 'sync.pending_other': "{count} perubahan menunggu", 'sync.now': "Sinkronkan", + // — Import depuis d'autres applis — + 'import.row': "Impor dari aplikasi lain", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Impor perpustakaanku", + 'import.chooseSource': "Dari mana judul-judulmu berasal?", + 'import.src.letterboxd': "Film, rating, diary, watchlist, dan suka", + 'import.src.tvtime': "Serial yang diikuti dan episode yang ditonton", + 'import.src.mal': "Daftar anime (ekspor XML)", + 'import.src.anilist': "Daftar anime publik, lewat nama pengguna", + 'import.how': "Cara mendapatkan ekspor", + 'import.steps.letterboxd': "Di letterboxd.com, buka Settings → Import & Export → Export your data.\nKamu akan mendapat file ZIP: letakkan di sini apa adanya (atau file CSV-nya).", + 'import.steps.tvtime': "Di TV Time, minta salinan datamu (Pengaturan → Privasi, atau dukungan “Request my data”).\nLetakkan di sini ZIP yang diterima lewat email, atau file CSV-nya.", + 'import.steps.mal': "Di myanimelist.net, buka profil → Export (Anime List) → Export My List.\nLetakkan file .xml.gz yang diunduh (atau .xml) di sini.", + 'import.steps.anilist': "Daftar AniList-mu harus publik (Settings → Lists).\nMasukkan nama pengguna: tidak perlu masuk.", + 'import.drop': "Pilih atau letakkan file", + 'import.privacy': "File dibaca di perangkatmu: hanya judul yang dicari secara online.", + 'import.userName': "Nama pengguna AniList", + 'import.continue': "Lanjut", + 'import.back': "Kembali", + 'import.reading': "Membaca file…", + 'import.resolving': "Mencari judul…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Batas permintaan tercapai, lanjut dalam {s} dtk…", + 'import.cancel': "Batal", + 'import.noTmdb': "Tanpa TMDB, film dan serial tidak bisa dikenali: tambahkan kunci di Pengaturan → Basis data (atau masuk), atau impor tanpa poster.", + 'import.found': "Judul yang terbaca dari ekspor: {n}", + 'import.new': "Entri baru", + 'import.toUpdate': "Entri dilengkapi", + 'import.already': "Sudah terbaru", + 'import.notFound': "Tidak ditemukan", + 'import.showNotFound': "Lihat judul yang tidak ditemukan", + 'import.hideNotFound': "Sembunyikan daftar", + 'import.includeUnmatched': "Tambahkan juga judul yang tidak ditemukan (tanpa poster)", + 'import.mergeHint': "Tidak ada yang ditimpa: rating, status, dan tanggal terbarumu tetap disimpan, dan tidak ada duplikat.", + 'import.confirm': "Impor ({n})", + 'import.importing': "Mengimpor…", + 'import.nothing': "Tidak ada yang baru untuk diimpor.", + 'import.done': "Impor selesai", + 'import.doneAdded': "Ditambahkan", + 'import.close': "Selesai", + 'import.err.tooBig': "File terlalu besar.", + 'import.err.badZip': "Arsip ZIP tidak terbaca.", + 'import.err.encrypted': "Arsip dilindungi kata sandi: tidak bisa dibaca.", + 'import.err.unsupported': "Browsermu tidak bisa mengekstrak file ini: letakkan file CSV / XML yang sudah diekstrak.", + 'import.err.read': "File tidak dikenali untuk sumber ini.", + 'import.err.empty': "Tidak ada judul di file ini.", + 'import.err.user': "Pengguna AniList tidak ditemukan, atau daftarnya privat.", } export default dict diff --git a/src/i18n/locales/it.ts b/src/i18n/locales/it.ts index df1ce6b..6511b6a 100644 --- a/src/i18n/locales/it.ts +++ b/src/i18n/locales/it.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} modifica in attesa", 'sync.pending_other': "{count} modifiche in attesa", 'sync.now': "Sincronizza", + // — Import depuis d'autres applis — + 'import.row': "Importa da un'altra app", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Importa la mia libreria", + 'import.chooseSource': "Da dove arrivano i tuoi titoli?", + 'import.src.letterboxd': "Film, voti, diario, da vedere e preferiti", + 'import.src.tvtime': "Serie seguite ed episodi visti", + 'import.src.mal': "Lista anime (esportazione XML)", + 'import.src.anilist': "Lista anime pubblica, per nome utente", + 'import.how': "Ottenere l'esportazione", + 'import.steps.letterboxd': "Su letterboxd.com, apri Settings → Import & Export → Export your data.\nRicevi un file ZIP: rilascialo qui così com’è (o i suoi file CSV).", + 'import.steps.tvtime': "In TV Time, richiedi una copia dei tuoi dati (Impostazioni → Privacy, o supporto «Request my data»).\nRilascia qui lo ZIP ricevuto via e-mail, o i suoi file CSV.", + 'import.steps.mal': "Su myanimelist.net, apri il profilo → Export (Anime List) → Export My List.\nRilascia qui il file .xml.gz scaricato (o il .xml).", + 'import.steps.anilist': "La tua lista AniList deve essere pubblica (Settings → Lists).\nInserisci il nome utente: non serve accedere.", + 'import.drop': "Scegli o rilascia il file", + 'import.privacy': "Il file viene letto sul tuo dispositivo: online si cercano solo i titoli.", + 'import.userName': "Nome utente AniList", + 'import.continue': "Continua", + 'import.back': "Indietro", + 'import.reading': "Lettura del file…", + 'import.resolving': "Ricerca delle schede…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Limite di richieste raggiunto, si riprende tra {s} s…", + 'import.cancel': "Annulla", + 'import.noTmdb': "Senza TMDB, film e serie non possono essere riconosciuti: aggiungi una chiave in Impostazioni → Database (o accedi), oppure importali senza locandina.", + 'import.found': "Titoli letti dall'esportazione: {n}", + 'import.new': "Nuove schede", + 'import.toUpdate': "Schede completate", + 'import.already': "Già aggiornate", + 'import.notFound': "Non trovati", + 'import.showNotFound': "Vedi i titoli non trovati", + 'import.hideNotFound': "Nascondi la lista", + 'import.includeUnmatched': "Aggiungi anche i titoli non trovati (senza locandina)", + 'import.mergeHint': "Niente viene sovrascritto: i tuoi voti, stati e date più recenti restano, e non si creano doppioni.", + 'import.confirm': "Importa ({n})", + 'import.importing': "Importazione…", + 'import.nothing': "Niente di nuovo da importare.", + 'import.done': "Importazione completata", + 'import.doneAdded': "Aggiunti", + 'import.close': "Fine", + 'import.err.tooBig': "File troppo grande.", + 'import.err.badZip': "Archivio ZIP illeggibile.", + 'import.err.encrypted': "Archivio protetto da password: impossibile leggerlo.", + 'import.err.unsupported': "Il tuo browser non sa decomprimere questo file: rilascia piuttosto i file CSV / XML decompressi.", + 'import.err.read': "File non riconosciuto per questa fonte.", + 'import.err.empty': "Nessun titolo trovato in questo file.", + 'import.err.user': "Utente AniList non trovato, o lista privata.", } export default dict diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts index 67b6839..01ab11b 100644 --- a/src/i18n/locales/ja.ts +++ b/src/i18n/locales/ja.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} 件の変更が保留中", 'sync.pending_other': "{count} 件の変更が保留中", 'sync.now': "今すぐ同期", + // — Import depuis d'autres applis — + 'import.row': "他のアプリからインポート", + 'import.rowHint': "Letterboxd、TV Time、MyAnimeList、AniList", + 'import.title': "ライブラリをインポート", + 'import.chooseSource': "どのアプリから取り込みますか?", + 'import.src.letterboxd': "映画、評価、日記、ウォッチリスト、お気に入り", + 'import.src.tvtime': "フォロー中のシリーズと視聴済みエピソード", + 'import.src.mal': "アニメリスト(XML エクスポート)", + 'import.src.anilist': "公開アニメリスト(ユーザー名で)", + 'import.how': "エクスポートの入手方法", + 'import.steps.letterboxd': "letterboxd.com で Settings → Import & Export → Export your data を開きます。\nZIP ファイルが届くので、そのままここにドロップしてください(中の CSV でも可)。", + 'import.steps.tvtime': "TV Time でデータのコピーを依頼します(設定 → プライバシー、またはサポートの「Request my data」)。\nメールで届いた ZIP、またはその CSV をここにドロップしてください。", + 'import.steps.mal': "myanimelist.net でプロフィール → Export (Anime List) → Export My List を開きます。\nダウンロードした .xml.gz(または .xml)をここにドロップしてください。", + 'import.steps.anilist': "AniList のリストは公開設定にしてください(Settings → Lists)。\nユーザー名を入力するだけで、ログインは不要です。", + 'import.drop': "ファイルを選択またはドロップ", + 'import.privacy': "ファイルは端末上で読み込まれ、オンラインではタイトルのみを検索します。", + 'import.userName': "AniList のユーザー名", + 'import.continue': "続ける", + 'import.back': "戻る", + 'import.reading': "ファイルを読み込み中…", + 'import.resolving': "作品を検索中…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "リクエスト上限に達しました。{s} 秒後に再開します…", + 'import.cancel': "キャンセル", + 'import.noTmdb': "TMDB がないと映画やシリーズを認識できません。設定 → データベースでキーを追加する(またはログインする)か、ポスターなしでインポートしてください。", + 'import.found': "エクスポートから読み込んだ作品:{n}", + 'import.new': "新規", + 'import.toUpdate': "補完した作品", + 'import.already': "最新の状態", + 'import.notFound': "見つからない", + 'import.showNotFound': "見つからない作品を表示", + 'import.hideNotFound': "リストを隠す", + 'import.includeUnmatched': "見つからない作品も追加する(ポスターなし)", + 'import.mergeHint': "上書きはされません。新しい評価・ステータス・日付はそのまま残り、重複も作られません。", + 'import.confirm': "インポート({n})", + 'import.importing': "インポート中…", + 'import.nothing': "新しくインポートするものはありません。", + 'import.done': "インポート完了", + 'import.doneAdded': "追加", + 'import.close': "完了", + 'import.err.tooBig': "ファイルが大きすぎます。", + 'import.err.badZip': "ZIP アーカイブを読み込めません。", + 'import.err.encrypted': "パスワード付きのアーカイブは読み込めません。", + 'import.err.unsupported': "お使いのブラウザではこのファイルを展開できません。展開済みの CSV / XML をドロップしてください。", + 'import.err.read': "このソースのファイルではありません。", + 'import.err.empty': "このファイルに作品が見つかりません。", + 'import.err.user': "AniList ユーザーが見つからないか、リストが非公開です。", } export default dict diff --git a/src/i18n/locales/ko.ts b/src/i18n/locales/ko.ts index 54d2f0b..536c81a 100644 --- a/src/i18n/locales/ko.ts +++ b/src/i18n/locales/ko.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "변경 {count}개 대기 중", 'sync.pending_other': "변경 {count}개 대기 중", 'sync.now': "지금 동기화", + // — Import depuis d'autres applis — + 'import.row': "다른 앱에서 가져오기", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "내 라이브러리 가져오기", + 'import.chooseSource': "작품을 어디서 가져올까요?", + 'import.src.letterboxd': "영화, 평점, 다이어리, 보고 싶어요, 좋아요", + 'import.src.tvtime': "팔로우한 시리즈와 본 에피소드", + 'import.src.mal': "애니 목록 (XML 내보내기)", + 'import.src.anilist': "공개 애니 목록, 사용자 이름으로", + 'import.how': "내보내기 파일 받기", + 'import.steps.letterboxd': "letterboxd.com에서 Settings → Import & Export → Export your data를 여세요.\nZIP 파일을 받으면 그대로 여기에 놓으세요 (또는 안의 CSV 파일).", + 'import.steps.tvtime': "TV Time에서 내 데이터 사본을 요청하세요 (설정 → 개인정보, 또는 지원 “Request my data”).\n이메일로 받은 ZIP이나 그 안의 CSV 파일을 여기에 놓으세요.", + 'import.steps.mal': "myanimelist.net에서 프로필 → Export (Anime List) → Export My List를 여세요.\n다운로드한 .xml.gz 파일(또는 .xml)을 여기에 놓으세요.", + 'import.steps.anilist': "AniList 목록이 공개 상태여야 합니다 (Settings → Lists).\n사용자 이름만 입력하면 되고 로그인은 필요 없습니다.", + 'import.drop': "파일 선택 또는 놓기", + 'import.privacy': "파일은 기기에서 읽히며, 온라인에서는 제목만 검색합니다.", + 'import.userName': "AniList 사용자 이름", + 'import.continue': "계속", + 'import.back': "뒤로", + 'import.reading': "파일 읽는 중…", + 'import.resolving': "작품 찾는 중…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "요청 한도에 도달했어요. {s}초 후 다시 시작…", + 'import.cancel': "취소", + 'import.noTmdb': "TMDB 없이는 영화와 시리즈를 인식할 수 없어요. 설정 → 데이터베이스에서 키를 추가하거나(또는 로그인) 포스터 없이 가져오세요.", + 'import.found': "내보내기에서 읽은 작품: {n}", + 'import.new': "새 항목", + 'import.toUpdate': "보완된 항목", + 'import.already': "이미 최신", + 'import.notFound': "찾지 못함", + 'import.showNotFound': "찾지 못한 작품 보기", + 'import.hideNotFound': "목록 숨기기", + 'import.includeUnmatched': "찾지 못한 작품도 추가 (포스터 없음)", + 'import.mergeHint': "덮어쓰지 않아요. 더 최근의 평점, 상태, 날짜는 유지되고 중복도 생기지 않아요.", + 'import.confirm': "가져오기 ({n})", + 'import.importing': "가져오는 중…", + 'import.nothing': "새로 가져올 항목이 없어요.", + 'import.done': "가져오기 완료", + 'import.doneAdded': "추가됨", + 'import.close': "완료", + 'import.err.tooBig': "파일이 너무 커요.", + 'import.err.badZip': "ZIP 파일을 읽을 수 없어요.", + 'import.err.encrypted': "비밀번호로 보호된 압축 파일은 읽을 수 없어요.", + 'import.err.unsupported': "브라우저가 이 파일의 압축을 풀 수 없어요. 압축을 푼 CSV / XML 파일을 놓아 주세요.", + 'import.err.read': "이 소스의 파일이 아니에요.", + 'import.err.empty': "이 파일에서 작품을 찾지 못했어요.", + 'import.err.user': "AniList 사용자를 찾을 수 없거나 목록이 비공개예요.", } export default dict diff --git a/src/i18n/locales/nl.ts b/src/i18n/locales/nl.ts index dd2e4f3..094abc3 100644 --- a/src/i18n/locales/nl.ts +++ b/src/i18n/locales/nl.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} wijziging in wachtrij", 'sync.pending_other': "{count} wijzigingen in wachtrij", 'sync.now': "Nu synchroniseren", + // — Import depuis d'autres applis — + 'import.row': "Importeren uit een andere app", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Mijn bibliotheek importeren", + 'import.chooseSource': "Waar komen je titels vandaan?", + 'import.src.letterboxd': "Films, beoordelingen, dagboek, watchlist en likes", + 'import.src.tvtime': "Gevolgde series en bekeken afleveringen", + 'import.src.mal': "Animelijst (XML-export)", + 'import.src.anilist': "Openbare animelijst, via gebruikersnaam", + 'import.how': "Export ophalen", + 'import.steps.letterboxd': "Open op letterboxd.com Settings → Import & Export → Export your data.\nJe krijgt een ZIP-bestand: zet het hier neer zoals het is (of de CSV-bestanden).", + 'import.steps.tvtime': "Vraag in TV Time een kopie van je gegevens aan (Instellingen → Privacy, of support “Request my data”).\nZet de per e-mail ontvangen ZIP hier neer, of de CSV-bestanden.", + 'import.steps.mal': "Open op myanimelist.net je profiel → Export (Anime List) → Export My List.\nZet het gedownloade .xml.gz-bestand (of de .xml) hier neer.", + 'import.steps.anilist': "Je AniList-lijst moet openbaar zijn (Settings → Lists).\nVul je gebruikersnaam in: inloggen is niet nodig.", + 'import.drop': "Bestand kiezen of neerzetten", + 'import.privacy': "Het bestand wordt op je apparaat gelezen: alleen de titels worden online gezocht.", + 'import.userName': "AniList-gebruikersnaam", + 'import.continue': "Doorgaan", + 'import.back': "Terug", + 'import.reading': "Bestand lezen…", + 'import.resolving': "Titels zoeken…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Limiet van verzoeken bereikt, verder over {s} s…", + 'import.cancel': "Annuleren", + 'import.noTmdb': "Zonder TMDB kunnen films en series niet worden herkend: voeg een sleutel toe in Instellingen → Databases (of log in), of importeer ze zonder poster.", + 'import.found': "Titels gelezen uit de export: {n}", + 'import.new': "Nieuwe items", + 'import.toUpdate': "Aangevulde items", + 'import.already': "Al bijgewerkt", + 'import.notFound': "Niet gevonden", + 'import.showNotFound': "Niet gevonden titels tonen", + 'import.hideNotFound': "Lijst verbergen", + 'import.includeUnmatched': "Niet gevonden titels ook toevoegen (zonder poster)", + 'import.mergeHint': "Er wordt niets overschreven: je recentere beoordelingen, statussen en datums blijven behouden, en er ontstaan geen dubbele items.", + 'import.confirm': "Importeren ({n})", + 'import.importing': "Bezig met importeren…", + 'import.nothing': "Niets nieuws om te importeren.", + 'import.done': "Import voltooid", + 'import.doneAdded': "Toegevoegd", + 'import.close': "Klaar", + 'import.err.tooBig': "Bestand te groot.", + 'import.err.badZip': "ZIP-archief onleesbaar.", + 'import.err.encrypted': "Archief met wachtwoord: kan niet worden gelezen.", + 'import.err.unsupported': "Je browser kan dit bestand niet uitpakken: zet liever de uitgepakte CSV-/XML-bestanden neer.", + 'import.err.read': "Bestand niet herkend voor deze bron.", + 'import.err.empty': "Geen titels gevonden in dit bestand.", + 'import.err.user': "AniList-gebruiker niet gevonden, of lijst privé.", } export default dict diff --git a/src/i18n/locales/pl.ts b/src/i18n/locales/pl.ts index 8427a4b..d41e193 100644 --- a/src/i18n/locales/pl.ts +++ b/src/i18n/locales/pl.ts @@ -989,6 +989,53 @@ const dict: Translations = { 'sync.now': "Synchronizuj", 'sync.pending_few': "{count} zmiany oczekują", 'sync.pending_many': "{count} zmian oczekuje", + // — Import depuis d'autres applis — + 'import.row': "Importuj z innej aplikacji", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Importuj moją bibliotekę", + 'import.chooseSource': "Skąd pochodzą twoje tytuły?", + 'import.src.letterboxd': "Filmy, oceny, dziennik, do obejrzenia i polubione", + 'import.src.tvtime': "Obserwowane seriale i obejrzane odcinki", + 'import.src.mal': "Lista anime (eksport XML)", + 'import.src.anilist': "Publiczna lista anime, po nazwie użytkownika", + 'import.how': "Jak pobrać eksport", + 'import.steps.letterboxd': "Na letterboxd.com otwórz Settings → Import & Export → Export your data.\nOtrzymasz plik ZIP: upuść go tutaj bez zmian (albo jego pliki CSV).", + 'import.steps.tvtime': "W TV Time poproś o kopię swoich danych (Ustawienia → Prywatność lub wsparcie „Request my data”).\nUpuść tutaj ZIP otrzymany e-mailem albo jego pliki CSV.", + 'import.steps.mal': "Na myanimelist.net otwórz profil → Export (Anime List) → Export My List.\nUpuść tutaj pobrany plik .xml.gz (albo .xml).", + 'import.steps.anilist': "Twoja lista AniList musi być publiczna (Settings → Lists).\nPodaj nazwę użytkownika: logowanie nie jest potrzebne.", + 'import.drop': "Wybierz lub upuść plik", + 'import.privacy': "Plik jest odczytywany na twoim urządzeniu: online wyszukiwane są tylko tytuły.", + 'import.userName': "Nazwa użytkownika AniList", + 'import.continue': "Dalej", + 'import.back': "Wstecz", + 'import.reading': "Odczytywanie pliku…", + 'import.resolving': "Wyszukiwanie tytułów…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Osiągnięto limit zapytań, wznowienie za {s} s…", + 'import.cancel': "Anuluj", + 'import.noTmdb': "Bez TMDB filmy i seriale nie mogą zostać rozpoznane: dodaj klucz w Ustawienia → Bazy danych (lub zaloguj się) albo zaimportuj je bez plakatu.", + 'import.found': "Tytuły odczytane z eksportu: {n}", + 'import.new': "Nowe pozycje", + 'import.toUpdate': "Uzupełnione pozycje", + 'import.already': "Już aktualne", + 'import.notFound': "Nie znaleziono", + 'import.showNotFound': "Pokaż nieznalezione tytuły", + 'import.hideNotFound': "Ukryj listę", + 'import.includeUnmatched': "Dodaj też nieznalezione tytuły (bez plakatu)", + 'import.mergeHint': "Nic nie zostanie nadpisane: twoje nowsze oceny, statusy i daty zostają, a duplikaty nie powstają.", + 'import.confirm': "Importuj ({n})", + 'import.importing': "Importowanie…", + 'import.nothing': "Nic nowego do zaimportowania.", + 'import.done': "Import zakończony", + 'import.doneAdded': "Dodane", + 'import.close': "Zakończ", + 'import.err.tooBig': "Plik jest za duży.", + 'import.err.badZip': "Nieczytelne archiwum ZIP.", + 'import.err.encrypted': "Archiwum chronione hasłem: nie można go odczytać.", + 'import.err.unsupported': "Twoja przeglądarka nie potrafi rozpakować tego pliku: upuść rozpakowane pliki CSV / XML.", + 'import.err.read': "Plik nierozpoznany dla tego źródła.", + 'import.err.empty': "W tym pliku nie znaleziono żadnych tytułów.", + 'import.err.user': "Nie znaleziono użytkownika AniList lub lista jest prywatna.", } export default dict diff --git a/src/i18n/locales/pt.ts b/src/i18n/locales/pt.ts index dee6d12..1f24349 100644 --- a/src/i18n/locales/pt.ts +++ b/src/i18n/locales/pt.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} alteração pendente", 'sync.pending_other': "{count} alterações pendentes", 'sync.now': "Sincronizar", + // — Import depuis d'autres applis — + 'import.row': "Importar de outro app", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Importar minha biblioteca", + 'import.chooseSource': "De onde vêm seus títulos?", + 'import.src.letterboxd': "Filmes, notas, diário, watchlist e curtidas", + 'import.src.tvtime': "Séries seguidas e episódios vistos", + 'import.src.mal': "Lista de animes (exportação XML)", + 'import.src.anilist': "Lista de animes pública, pelo nome de usuário", + 'import.how': "Obter a exportação", + 'import.steps.letterboxd': "Em letterboxd.com, abra Settings → Import & Export → Export your data.\nVocê recebe um arquivo ZIP: solte-o aqui como está (ou os arquivos CSV dele).", + 'import.steps.tvtime': "No TV Time, peça uma cópia dos seus dados (Configurações → Privacidade, ou suporte “Request my data”).\nSolte aqui o ZIP recebido por e-mail, ou os arquivos CSV dele.", + 'import.steps.mal': "Em myanimelist.net, abra seu perfil → Export (Anime List) → Export My List.\nSolte aqui o arquivo .xml.gz baixado (ou o .xml).", + 'import.steps.anilist': "Sua lista do AniList precisa ser pública (Settings → Lists).\nInforme seu nome de usuário: não é preciso entrar.", + 'import.drop': "Escolher ou soltar o arquivo", + 'import.privacy': "O arquivo é lido no seu aparelho: só os títulos são buscados on-line.", + 'import.userName': "Nome de usuário do AniList", + 'import.continue': "Continuar", + 'import.back': "Voltar", + 'import.reading': "Lendo o arquivo…", + 'import.resolving': "Buscando os títulos…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Limite de solicitações atingido, retomando em {s} s…", + 'import.cancel': "Cancelar", + 'import.noTmdb': "Sem TMDB, filmes e séries não podem ser reconhecidos: adicione uma chave em Configurações → Bancos de dados (ou entre), ou importe-os sem pôster.", + 'import.found': "Títulos lidos na exportação: {n}", + 'import.new': "Novos registros", + 'import.toUpdate': "Registros completados", + 'import.already': "Já atualizados", + 'import.notFound': "Não encontrados", + 'import.showNotFound': "Ver títulos não encontrados", + 'import.hideNotFound': "Ocultar a lista", + 'import.includeUnmatched': "Adicionar também os títulos não encontrados (sem pôster)", + 'import.mergeHint': "Nada é sobrescrito: suas notas, status e datas mais recentes são mantidos, e nenhuma duplicata é criada.", + 'import.confirm': "Importar ({n})", + 'import.importing': "Importando…", + 'import.nothing': "Nada novo para importar.", + 'import.done': "Importação concluída", + 'import.doneAdded': "Adicionados", + 'import.close': "Concluir", + 'import.err.tooBig': "Arquivo grande demais.", + 'import.err.badZip': "Arquivo ZIP ilegível.", + 'import.err.encrypted': "Arquivo protegido por senha: não é possível lê-lo.", + 'import.err.unsupported': "Seu navegador não consegue descompactar este arquivo: solte os arquivos CSV / XML descompactados.", + 'import.err.read': "Arquivo não reconhecido para esta fonte.", + 'import.err.empty': "Nenhum título encontrado neste arquivo.", + 'import.err.user': "Usuário do AniList não encontrado, ou lista privada.", } export default dict diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index c95076d..c0b201a 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -989,6 +989,53 @@ const dict: Translations = { 'sync.now': "Синхронизировать", 'sync.pending_few': "{count} изменения ожидают", 'sync.pending_many': "{count} изменений ожидают", + // — Import depuis d'autres applis — + 'import.row': "Импорт из другого приложения", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Импорт моей библиотеки", + 'import.chooseSource': "Откуда твои тайтлы?", + 'import.src.letterboxd': "Фильмы, оценки, дневник, список «посмотреть» и лайки", + 'import.src.tvtime': "Отслеживаемые сериалы и просмотренные серии", + 'import.src.mal': "Список аниме (экспорт XML)", + 'import.src.anilist': "Публичный список аниме по имени пользователя", + 'import.how': "Как получить экспорт", + 'import.steps.letterboxd': "На letterboxd.com открой Settings → Import & Export → Export your data.\nТы получишь ZIP-файл: перетащи его сюда как есть (или его CSV-файлы).", + 'import.steps.tvtime': "В TV Time запроси копию своих данных (Настройки → Конфиденциальность или поддержка «Request my data»).\nПеретащи сюда ZIP из письма или его CSV-файлы.", + 'import.steps.mal': "На myanimelist.net открой профиль → Export (Anime List) → Export My List.\nПеретащи сюда скачанный файл .xml.gz (или .xml).", + 'import.steps.anilist': "Твой список AniList должен быть публичным (Settings → Lists).\nУкажи имя пользователя: входить не нужно.", + 'import.drop': "Выбрать или перетащить файл", + 'import.privacy': "Файл читается на твоём устройстве: в сети ищутся только названия.", + 'import.userName': "Имя пользователя AniList", + 'import.continue': "Продолжить", + 'import.back': "Назад", + 'import.reading': "Чтение файла…", + 'import.resolving': "Поиск тайтлов…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Достигнут лимит запросов, продолжение через {s} с…", + 'import.cancel': "Отмена", + 'import.noTmdb': "Без TMDB фильмы и сериалы не распознать: добавь ключ в Настройки → Базы данных (или войди в аккаунт) либо импортируй их без постера.", + 'import.found': "Тайтлов в экспорте: {n}", + 'import.new': "Новые записи", + 'import.toUpdate': "Дополненные записи", + 'import.already': "Уже актуальны", + 'import.notFound': "Не найдено", + 'import.showNotFound': "Показать ненайденные", + 'import.hideNotFound': "Скрыть список", + 'import.includeUnmatched': "Добавить и ненайденные тайтлы (без постера)", + 'import.mergeHint': "Ничего не перезаписывается: твои более новые оценки, статусы и даты сохраняются, дубликаты не создаются.", + 'import.confirm': "Импортировать ({n})", + 'import.importing': "Импорт…", + 'import.nothing': "Нечего импортировать.", + 'import.done': "Импорт завершён", + 'import.doneAdded': "Добавлено", + 'import.close': "Готово", + 'import.err.tooBig': "Файл слишком большой.", + 'import.err.badZip': "Не удаётся прочитать ZIP-архив.", + 'import.err.encrypted': "Архив защищён паролем: прочитать его нельзя.", + 'import.err.unsupported': "Браузер не может распаковать этот файл: перетащи распакованные файлы CSV / XML.", + 'import.err.read': "Файл не подходит для этого источника.", + 'import.err.empty': "В этом файле не найдено тайтлов.", + 'import.err.user': "Пользователь AniList не найден или список закрыт.", } export default dict diff --git a/src/i18n/locales/th.ts b/src/i18n/locales/th.ts index 4551741..396b4f2 100644 --- a/src/i18n/locales/th.ts +++ b/src/i18n/locales/th.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "รอซิงค์ {count} รายการ", 'sync.pending_other': "รอซิงค์ {count} รายการ", 'sync.now': "ซิงค์ตอนนี้", + // — Import depuis d'autres applis — + 'import.row': "นำเข้าจากแอปอื่น", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "นำเข้าคลังของฉัน", + 'import.chooseSource': "รายการของคุณมาจากที่ไหน?", + 'import.src.letterboxd': "ภาพยนตร์ คะแนน ไดอารี่ รายการอยากดู และที่ชอบ", + 'import.src.tvtime': "ซีรีส์ที่ติดตามและตอนที่ดูแล้ว", + 'import.src.mal': "รายการอนิเมะ (ส่งออก XML)", + 'import.src.anilist': "รายการอนิเมะสาธารณะ ด้วยชื่อผู้ใช้", + 'import.how': "วิธีรับไฟล์ส่งออก", + 'import.steps.letterboxd': "บน letterboxd.com เปิด Settings → Import & Export → Export your data\nคุณจะได้ไฟล์ ZIP: วางไว้ที่นี่ได้เลย (หรือไฟล์ CSV ข้างใน)", + 'import.steps.tvtime': "ใน TV Time ขอสำเนาข้อมูลของคุณ (การตั้งค่า → ความเป็นส่วนตัว หรือฝ่ายช่วยเหลือ “Request my data”)\nวาง ZIP ที่ได้รับทางอีเมล หรือไฟล์ CSV ข้างในไว้ที่นี่", + 'import.steps.mal': "บน myanimelist.net เปิดโปรไฟล์ → Export (Anime List) → Export My List\nวางไฟล์ .xml.gz ที่ดาวน์โหลด (หรือ .xml) ไว้ที่นี่", + 'import.steps.anilist': "รายการ AniList ของคุณต้องเป็นสาธารณะ (Settings → Lists)\nกรอกชื่อผู้ใช้: ไม่ต้องเข้าสู่ระบบ", + 'import.drop': "เลือกหรือวางไฟล์", + 'import.privacy': "ไฟล์ถูกอ่านบนอุปกรณ์ของคุณ: ค้นหาออนไลน์เฉพาะชื่อเรื่อง", + 'import.userName': "ชื่อผู้ใช้ AniList", + 'import.continue': "ต่อไป", + 'import.back': "ย้อนกลับ", + 'import.reading': "กำลังอ่านไฟล์…", + 'import.resolving': "กำลังค้นหารายการ…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "ถึงขีดจำกัดคำขอ จะทำต่อใน {s} วินาที…", + 'import.cancel': "ยกเลิก", + 'import.noTmdb': "หากไม่มี TMDB จะจดจำภาพยนตร์และซีรีส์ไม่ได้: เพิ่มคีย์ในการตั้งค่า → ฐานข้อมูล (หรือเข้าสู่ระบบ) หรือนำเข้าโดยไม่มีโปสเตอร์", + 'import.found': "รายการที่อ่านได้จากไฟล์ส่งออก: {n}", + 'import.new': "รายการใหม่", + 'import.toUpdate': "รายการที่เติมข้อมูล", + 'import.already': "อัปเดตแล้ว", + 'import.notFound': "ไม่พบ", + 'import.showNotFound': "ดูรายการที่ไม่พบ", + 'import.hideNotFound': "ซ่อนรายการ", + 'import.includeUnmatched': "เพิ่มรายการที่ไม่พบด้วย (ไม่มีโปสเตอร์)", + 'import.mergeHint': "ไม่มีอะไรถูกเขียนทับ: คะแนน สถานะ และวันที่ล่าสุดของคุณยังอยู่ และไม่มีรายการซ้ำ", + 'import.confirm': "นำเข้า ({n})", + 'import.importing': "กำลังนำเข้า…", + 'import.nothing': "ไม่มีอะไรใหม่ให้นำเข้า", + 'import.done': "นำเข้าเสร็จแล้ว", + 'import.doneAdded': "เพิ่มแล้ว", + 'import.close': "เสร็จสิ้น", + 'import.err.tooBig': "ไฟล์ใหญ่เกินไป", + 'import.err.badZip': "อ่านไฟล์ ZIP ไม่ได้", + 'import.err.encrypted': "ไฟล์ถูกป้องกันด้วยรหัสผ่าน: อ่านไม่ได้", + 'import.err.unsupported': "เบราว์เซอร์ของคุณแตกไฟล์นี้ไม่ได้: โปรดวางไฟล์ CSV / XML ที่แตกแล้วแทน", + 'import.err.read': "ไม่รู้จักไฟล์สำหรับแหล่งนี้", + 'import.err.empty': "ไม่พบรายการในไฟล์นี้", + 'import.err.user': "ไม่พบผู้ใช้ AniList หรือรายการเป็นส่วนตัว", } export default dict diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index ea49087..3703cb4 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} değişiklik bekliyor", 'sync.pending_other': "{count} değişiklik bekliyor", 'sync.now': "Şimdi eşitle", + // — Import depuis d'autres applis — + 'import.row': "Başka bir uygulamadan içe aktar", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Kütüphanemi içe aktar", + 'import.chooseSource': "Başlıkların nereden geliyor?", + 'import.src.letterboxd': "Filmler, puanlar, günlük, izleme listesi ve beğeniler", + 'import.src.tvtime': "Takip edilen diziler ve izlenen bölümler", + 'import.src.mal': "Anime listesi (XML dışa aktarımı)", + 'import.src.anilist': "Herkese açık anime listesi, kullanıcı adıyla", + 'import.how': "Dışa aktarımı alma", + 'import.steps.letterboxd': "letterboxd.com'da Settings → Import & Export → Export your data'yı aç.\nBir ZIP dosyası alırsın: olduğu gibi buraya bırak (ya da CSV dosyalarını).", + 'import.steps.tvtime': "TV Time’da verilerinin bir kopyasını iste (Ayarlar → Gizlilik ya da destek “Request my data”).\nE-postayla gelen ZIP’i ya da CSV dosyalarını buraya bırak.", + 'import.steps.mal': "myanimelist.net'te profilini aç → Export (Anime List) → Export My List.\nİndirilen .xml.gz dosyasını (ya da .xml) buraya bırak.", + 'import.steps.anilist': "AniList listen herkese açık olmalı (Settings → Lists).\nKullanıcı adını gir: giriş yapmak gerekmez.", + 'import.drop': "Dosya seç ya da bırak", + 'import.privacy': "Dosya cihazında okunur: çevrimiçi yalnızca başlıklar aranır.", + 'import.userName': "AniList kullanıcı adı", + 'import.continue': "Devam", + 'import.back': "Geri", + 'import.reading': "Dosya okunuyor…", + 'import.resolving': "Başlıklar aranıyor…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "İstek sınırına ulaşıldı, {s} sn sonra devam…", + 'import.cancel': "İptal", + 'import.noTmdb': "TMDB olmadan filmler ve diziler tanınamaz: Ayarlar → Veritabanları’na bir anahtar ekle (ya da giriş yap) veya afişsiz içe aktar.", + 'import.found': "Dışa aktarımdan okunan başlıklar: {n}", + 'import.new': "Yeni kayıtlar", + 'import.toUpdate': "Tamamlanan kayıtlar", + 'import.already': "Zaten güncel", + 'import.notFound': "Bulunamadı", + 'import.showNotFound': "Bulunamayanları göster", + 'import.hideNotFound': "Listeyi gizle", + 'import.includeUnmatched': "Bulunamayan başlıkları da ekle (afişsiz)", + 'import.mergeHint': "Hiçbir şeyin üzerine yazılmaz: daha yeni puanların, durumların ve tarihlerin korunur, kopya oluşturulmaz.", + 'import.confirm': "İçe aktar ({n})", + 'import.importing': "İçe aktarılıyor…", + 'import.nothing': "İçe aktarılacak yeni bir şey yok.", + 'import.done': "İçe aktarma tamamlandı", + 'import.doneAdded': "Eklendi", + 'import.close': "Bitti", + 'import.err.tooBig': "Dosya çok büyük.", + 'import.err.badZip': "ZIP arşivi okunamıyor.", + 'import.err.encrypted': "Parola korumalı arşiv: okunamıyor.", + 'import.err.unsupported': "Tarayıcın bu dosyayı açamıyor: bunun yerine açılmış CSV / XML dosyalarını bırak.", + 'import.err.read': "Dosya bu kaynak için tanınmadı.", + 'import.err.empty': "Bu dosyada başlık bulunamadı.", + 'import.err.user': "AniList kullanıcısı bulunamadı ya da liste gizli.", } export default dict diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.ts index 632c8a9..ef73883 100644 --- a/src/i18n/locales/vi.ts +++ b/src/i18n/locales/vi.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} thay đổi đang chờ", 'sync.pending_other': "{count} thay đổi đang chờ", 'sync.now': "Đồng bộ ngay", + // — Import depuis d'autres applis — + 'import.row': "Nhập từ ứng dụng khác", + 'import.rowHint': "Letterboxd, TV Time, MyAnimeList, AniList", + 'import.title': "Nhập thư viện của tôi", + 'import.chooseSource': "Các tựa của bạn đến từ đâu?", + 'import.src.letterboxd': "Phim, điểm, nhật ký, danh sách muốn xem và yêu thích", + 'import.src.tvtime': "Phim bộ đang theo dõi và tập đã xem", + 'import.src.mal': "Danh sách anime (xuất XML)", + 'import.src.anilist': "Danh sách anime công khai, theo tên người dùng", + 'import.how': "Cách lấy tệp xuất", + 'import.steps.letterboxd': "Trên letterboxd.com, mở Settings → Import & Export → Export your data.\nBạn nhận được tệp ZIP: thả nguyên tệp vào đây (hoặc các tệp CSV bên trong).", + 'import.steps.tvtime': "Trong TV Time, yêu cầu bản sao dữ liệu (Cài đặt → Quyền riêng tư, hoặc hỗ trợ “Request my data”).\nThả tệp ZIP nhận qua email, hoặc các tệp CSV bên trong, vào đây.", + 'import.steps.mal': "Trên myanimelist.net, mở hồ sơ → Export (Anime List) → Export My List.\nThả tệp .xml.gz đã tải (hoặc .xml) vào đây.", + 'import.steps.anilist': "Danh sách AniList của bạn phải công khai (Settings → Lists).\nNhập tên người dùng: không cần đăng nhập.", + 'import.drop': "Chọn hoặc thả tệp", + 'import.privacy': "Tệp được đọc trên thiết bị của bạn: chỉ tên tựa được tìm trực tuyến.", + 'import.userName': "Tên người dùng AniList", + 'import.continue': "Tiếp tục", + 'import.back': "Quay lại", + 'import.reading': "Đang đọc tệp…", + 'import.resolving': "Đang tìm các tựa…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "Đã chạm giới hạn yêu cầu, tiếp tục sau {s} giây…", + 'import.cancel': "Hủy", + 'import.noTmdb': "Không có TMDB thì không nhận diện được phim lẻ và phim bộ: thêm khóa trong Cài đặt → Cơ sở dữ liệu (hoặc đăng nhập), hoặc nhập mà không có áp phích.", + 'import.found': "Số tựa đọc được từ tệp xuất: {n}", + 'import.new': "Mục mới", + 'import.toUpdate': "Mục được bổ sung", + 'import.already': "Đã cập nhật", + 'import.notFound': "Không tìm thấy", + 'import.showNotFound': "Xem các tựa không tìm thấy", + 'import.hideNotFound': "Ẩn danh sách", + 'import.includeUnmatched': "Thêm cả các tựa không tìm thấy (không có áp phích)", + 'import.mergeHint': "Không ghi đè gì cả: điểm, trạng thái và ngày mới hơn của bạn được giữ, và không tạo bản trùng.", + 'import.confirm': "Nhập ({n})", + 'import.importing': "Đang nhập…", + 'import.nothing': "Không có gì mới để nhập.", + 'import.done': "Đã nhập xong", + 'import.doneAdded': "Đã thêm", + 'import.close': "Xong", + 'import.err.tooBig': "Tệp quá lớn.", + 'import.err.badZip': "Không đọc được tệp ZIP.", + 'import.err.encrypted': "Tệp nén có mật khẩu: không thể đọc.", + 'import.err.unsupported': "Trình duyệt không giải nén được tệp này: hãy thả các tệp CSV / XML đã giải nén.", + 'import.err.read': "Tệp không phù hợp với nguồn này.", + 'import.err.empty': "Không tìm thấy tựa nào trong tệp này.", + 'import.err.user': "Không tìm thấy người dùng AniList, hoặc danh sách ở chế độ riêng tư.", } export default dict diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index ad9a6c6..30bb85a 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -897,6 +897,53 @@ const dict: Translations = { 'sync.pending_one': "{count} 项更改待上传", 'sync.pending_other': "{count} 项更改待上传", 'sync.now': "立即同步", + // — Import depuis d'autres applis — + 'import.row': "从其他应用导入", + 'import.rowHint': "Letterboxd、TV Time、MyAnimeList、AniList", + 'import.title': "导入我的片库", + 'import.chooseSource': "你的作品来自哪里?", + 'import.src.letterboxd': "电影、评分、日记、想看和喜欢", + 'import.src.tvtime': "追的剧和看过的集", + 'import.src.mal': "动画列表(XML 导出)", + 'import.src.anilist': "公开的动画列表,按用户名", + 'import.how': "获取导出文件", + 'import.steps.letterboxd': "在 letterboxd.com 打开 Settings → Import & Export → Export your data。\n你会得到一个 ZIP 文件:直接拖到这里(或其中的 CSV 文件)。", + 'import.steps.tvtime': "在 TV Time 中申请数据副本(设置 → 隐私,或客服“Request my data”)。\n把邮件收到的 ZIP 或其中的 CSV 文件拖到这里。", + 'import.steps.mal': "在 myanimelist.net 打开个人主页 → Export (Anime List) → Export My List。\n把下载的 .xml.gz 文件(或 .xml)拖到这里。", + 'import.steps.anilist': "你的 AniList 列表需要公开(Settings → Lists)。\n输入用户名即可,无需登录。", + 'import.drop': "选择或拖入文件", + 'import.privacy': "文件在你的设备上读取:只会在线搜索作品名。", + 'import.userName': "AniList 用户名", + 'import.continue': "继续", + 'import.back': "返回", + 'import.reading': "正在读取文件…", + 'import.resolving': "正在查找作品…", + 'import.progress': "{done} / {total}", + 'import.rateWait': "已达请求上限,{s} 秒后继续…", + 'import.cancel': "取消", + 'import.noTmdb': "没有 TMDB 就无法识别电影和剧集:在 设置 → 数据库 中添加密钥(或登录),或不带海报导入。", + 'import.found': "从导出中读取的作品:{n}", + 'import.new': "新条目", + 'import.toUpdate': "补充的条目", + 'import.already': "已是最新", + 'import.notFound': "未找到", + 'import.showNotFound': "查看未找到的作品", + 'import.hideNotFound': "隐藏列表", + 'import.includeUnmatched': "同时添加未找到的作品(无海报)", + 'import.mergeHint': "不会覆盖任何内容:保留你较新的评分、状态和日期,也不会产生重复条目。", + 'import.confirm': "导入({n})", + 'import.importing': "正在导入…", + 'import.nothing': "没有新的内容可导入。", + 'import.done': "导入完成", + 'import.doneAdded': "已添加", + 'import.close': "完成", + 'import.err.tooBig': "文件太大。", + 'import.err.badZip': "无法读取 ZIP 压缩包。", + 'import.err.encrypted': "压缩包有密码保护:无法读取。", + 'import.err.unsupported': "你的浏览器无法解压此文件:请拖入解压后的 CSV / XML 文件。", + 'import.err.read': "该文件不属于此来源。", + 'import.err.empty': "此文件中没有找到作品。", + 'import.err.user': "找不到该 AniList 用户,或列表未公开。", } export default dict diff --git a/src/lib/catalogApi.ts b/src/lib/catalogApi.ts index 081e2a9..e30bd35 100644 --- a/src/lib/catalogApi.ts +++ b/src/lib/catalogApi.ts @@ -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 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 { + 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 { + 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 } diff --git a/src/lib/import/files.ts b/src/lib/import/files.ts new file mode 100644 index 0000000..b3b76cd --- /dev/null +++ b/src/lib/import/files.ts @@ -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 { + 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 { + 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 { + 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 + +/** 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 { + 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) }] +} diff --git a/src/lib/import/merge.ts b/src/lib/import/merge.ts new file mode 100644 index 0000000..ec2f0b4 --- /dev/null +++ b/src/lib/import/merge.ts @@ -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 = { 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 = 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() + 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: 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() +const refInUse = (ref: string) => usedRefs.has(ref) + +/** Prépare l'import (sans rien écrire). */ +export function buildImportPlan(entries: ImportEntry[], matches: Map, 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() + 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() + 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 } +} diff --git a/src/lib/import/resolve.ts b/src/lib/import/resolve.ts new file mode 100644 index 0000000..92ee35c --- /dev/null +++ b/src/lib/import/resolve.ts @@ -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 +} + +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 | null = null + +function loadCache(): Record { + if (cache) return cache + cache = Object.create(null) as Record + 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)) { + 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(list: T[], size: number, token: CancelToken, fn: (x: T) => Promise) { + 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): 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(fn: () => Promise, token: CancelToken, onWait: (until?: number) => void): Promise { + 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(query: string, variables: Record): Promise { + 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, 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() + 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> { + const { token } = opts + const found = new Map() + 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 = { ...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 +} diff --git a/src/lib/import/sources.ts b/src/lib/import/sources.ts new file mode 100644 index 0000000..36a60cc --- /dev/null +++ b/src/lib/import/sources.ts @@ -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 + /** 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() + 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() + const views = new Map() + 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() + 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() + 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 = { + 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 = { + 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() + 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()] +} diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index d8ab5cf..12c1097 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -1,9 +1,10 @@ import { t } from '../i18n' import { LanguageSelect } from '../i18n/react' -import { Check, Download, ExternalLink, Eye, EyeOff, HardDrive, ShieldCheck, Smartphone, Trash2, Upload, UserX } from 'lucide-react' +import { Check, Download, ExternalLink, Eye, EyeOff, HardDrive, Import, ShieldCheck, Smartphone, Trash2, Upload, UserX } from 'lucide-react' import { useEffect, useRef, useState, type ReactNode } from 'react' import AccountSection from '../components/AccountSection' import ConfirmDialog from '../components/ConfirmDialog' +import ImportWizard from '../components/ImportWizard' import { PageHeader, SectionTitle } from '../components/ui' import { exportBackup, parseBackupFile, type ParsedBackup } from '../lib/backup' import { testTmdbKey } from '../lib/catalogApi' @@ -151,6 +152,7 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void setMessage({ kind: 'ok', text: t('settings.cleared') }) } + const [showImport, setShowImport] = useState(false) const [showInstall, setShowInstall] = useState(false) useEscape(() => setShowInstall(false), showInstall) useBackToClose(() => setShowInstall(false), showInstall) @@ -443,7 +445,9 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void } title={t('settings.export')} hint={t('settings.exportHint', { count: items.length })} onClick={onExport} /> } title={t('settings.import')} hint={t('settings.importHint')} onClick={() => fileRef.current?.click()} /> onFile(e.target.files?.[0])} /> + } title={t('import.row')} hint={t('import.rowHint')} onClick={() => setShowImport(true)} />
+ {showImport && setShowImport(false)} />} {pending && (
diff --git a/supabase/functions/tmdb/index.ts b/supabase/functions/tmdb/index.ts index d0387de..4ff9d5b 100644 --- a/supabase/functions/tmdb/index.ts +++ b/supabase/functions/tmdb/index.ts @@ -7,7 +7,7 @@ import { corsHeaders, getUserId, json, rateLimited } from '../_shared/auth.ts' const TMDB_KEY = Deno.env.get('TMDB_API_KEY') ?? '' // Mêmes adresses que dans l'app — tout le reste est refusé -const PATHS = /^\/(search\/multi|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?)$/ +const PATHS = /^\/(search\/multi|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?|find\/(tt)?\d{1,10})$/ // Paramètres autorisés et forme de leur valeur const PARAMS: Record = { @@ -25,6 +25,8 @@ const PARAMS: Record = { sort_by: /^popularity\.desc$/, with_origin_country: /^[A-Z]{2}(\|[A-Z]{2}){0,20}$/, without_genres: /^\d{1,6}(\|\d{1,6}){0,10}$/, + // Import TV Time / IMDb : /find/{id} + external_source: /^(tvdb_id|imdb_id)$/, } Deno.serve(async (req) => {