Import « Coller une liste » : depuis l'app Notes ou n'importe quel texte
deploy / deploy (push) Successful in 52s
deploy / deploy (push) Successful in 52s
- Une ligne par titre : note (4,5/5, 8/10, ★★★★), année, statut (vu, en cours, à voir), progression S3E12 et avis reconnus - Sections « Films », « Séries à voir »… appliquées aux lignes suivantes - Recherche TMDB + AniList, écran de vérification : décocher une ligne ou choisir un autre titre - Textes dans les 18 langues Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
23 files changed
+884
-17
No files matched your search
+106
-1
@@ -1,7 +1,8 @@
|
||||
import { t } from '../../i18n'
|
||||
import { ANILIST, ANILIST_FIELDS, aniToResult, CLOUD_TMDB, getTmdbDetails, sanitizeMeta, tmdbFindExternal, tmdbImportSearch, type AniMedia, type SearchResult } from '../catalogApi'
|
||||
import { ANILIST, ANILIST_FIELDS, aniToResult, CLOUD_TMDB, getTmdbDetails, sanitizeMeta, searchAll, tmdbFindExternal, tmdbImportSearch, type AniMedia, type SearchResult } from '../catalogApi'
|
||||
import type { MediaInput } from '../../types'
|
||||
import { anilistEntries, titleKey, type AniListEntry, type ImportEntry } from './sources'
|
||||
import type { TextEntry } from './textList'
|
||||
|
||||
/**
|
||||
* Recherche des fiches correspondantes (TMDB pour les films et séries, AniList pour les animes).
|
||||
@@ -390,3 +391,107 @@ export async function resolveEntries(entries: ImportEntry[], opts: ResolveOption
|
||||
}).finally(saveCache)
|
||||
return found
|
||||
}
|
||||
|
||||
// ─── Liste collée (app Notes…) ───
|
||||
|
||||
const KIND_OK: Record<ImportEntry['kind'], (r: SearchResult) => boolean> = {
|
||||
movie: (r) => r.typeGuess === 'film',
|
||||
// Une section « Séries » contient souvent aussi des animes
|
||||
tv: (r) => r.typeGuess !== 'film',
|
||||
anime: (r) => r.typeGuess === 'anime' || r.source === 'anilist',
|
||||
}
|
||||
|
||||
/** Meilleur résultat pour une ligne de texte. `sure` : même titre (et même année / bon type si connus). */
|
||||
export function pickTextMatch(list: SearchResult[], e: Pick<TextEntry, 'title' | 'year' | 'kind' | 'kindKnown'>): { result?: SearchResult; sure: boolean } {
|
||||
const typed = e.kindKnown ? list.filter(KIND_OK[e.kind]) : list
|
||||
const cands = typed.length ? typed : list
|
||||
const want = titleKey(e.title)
|
||||
const same = (r: SearchResult) => [r.title, r.originalTitle, ...(r.altTitles ?? [])].some((x) => x && titleKey(x) === want)
|
||||
if (e.year) {
|
||||
const sameYear = cands.filter((r) => r.year === e.year)
|
||||
const hit = sameYear.find(same) ?? sameYear[0]
|
||||
if (hit) return { result: hit, sure: true }
|
||||
}
|
||||
const hit = cands.find(same)
|
||||
if (hit) return { result: hit, sure: !e.kindKnown || typed.length > 0 }
|
||||
return { result: cands[0], sure: false }
|
||||
}
|
||||
|
||||
/** Métadonnées d'un résultat choisi : la fiche TMDB complète (référence, année, durée, saisons…). */
|
||||
export async function matchFor(result: SearchResult, key?: string): Promise<Match> {
|
||||
let meta: Partial<MediaInput> = {
|
||||
title: result.title,
|
||||
originalTitle: result.originalTitle,
|
||||
year: result.year,
|
||||
type: result.typeGuess,
|
||||
externalId: result.externalId,
|
||||
...result.prefill,
|
||||
poster: result.posterUrl,
|
||||
}
|
||||
if (key && result.externalId.startsWith('tmdb:')) {
|
||||
const details = await getTmdbDetails(result, key).catch((err) => {
|
||||
if (isRateError(err)) throw err // la recherche attend et réessaie
|
||||
return undefined
|
||||
})
|
||||
if (details) meta = { ...meta, ...details, poster: result.posterUrl ?? meta.poster }
|
||||
}
|
||||
return { result, meta }
|
||||
}
|
||||
|
||||
/** Recherche de chaque ligne (même recherche que l'ajout d'un titre : TMDB puis AniList). */
|
||||
export async function resolveTextEntries(entries: TextEntry[], opts: ResolveOptions): Promise<{ found: Map<string, Match>; unsure: Set<string> }> {
|
||||
const { token } = opts
|
||||
const key = opts.tmdbKey?.trim() || undefined
|
||||
const found = new Map<string, Match>()
|
||||
const unsure = new Set<string>()
|
||||
const progress: Progress = { done: 0, total: entries.length }
|
||||
const emit = () => opts.onProgress({ ...progress })
|
||||
const onWait = (until?: number) => {
|
||||
progress.waitUntil = until
|
||||
emit()
|
||||
}
|
||||
emit()
|
||||
// AniList est interrogé à chaque recherche : ~66 par minute au plus
|
||||
const rate = limiter(4, 900)
|
||||
await pool(entries, 3, token, async (e) => {
|
||||
try {
|
||||
await rate(token)
|
||||
let list = await withRetry(() => searchAll(e.title, key), token, onWait)
|
||||
let pick = pickTextMatch(list, e)
|
||||
// « Déjà vu » : le mot retiré faisait partie du titre
|
||||
if (e.fullTitle && !pick.sure) {
|
||||
await rate(token)
|
||||
const fullList = await withRetry(() => searchAll(e.fullTitle!, key), token, onWait)
|
||||
const full = pickTextMatch(fullList, { ...e, title: e.fullTitle })
|
||||
if (full.sure) {
|
||||
list = fullList
|
||||
pick = full
|
||||
e.title = e.fullTitle
|
||||
e.status = e.fullStatus ?? e.status
|
||||
if (e.status === 'a_voir') e.rating = undefined
|
||||
}
|
||||
}
|
||||
if (!pick.result) return
|
||||
found.set(e.key, await withRetry(() => matchFor(pick.result!, key), token, onWait))
|
||||
if (!pick.sure) unsure.add(e.key)
|
||||
} catch (err) {
|
||||
if (err instanceof CancelledError) throw err
|
||||
if (!navigator.onLine) throw new Error(t('search.offline'))
|
||||
} finally {
|
||||
progress.done++
|
||||
emit()
|
||||
}
|
||||
})
|
||||
return { found, unsure }
|
||||
}
|
||||
|
||||
/** « S3E12 » → épisodes vus, une fois les saisons connues. */
|
||||
export function withProgress(e: TextEntry, match?: Match): TextEntry {
|
||||
if (!e.progress) return e
|
||||
const seasons = match?.meta.seasons
|
||||
const { season, episode } = e.progress
|
||||
let watched: number | undefined
|
||||
if (seasons?.length) watched = seasons.slice(0, season - 1).reduce((a, b) => a + b, 0) + episode
|
||||
else if (season === 1) watched = episode
|
||||
return watched ? { ...e, episodesWatched: Math.min(100000, watched) } : e
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { parseCsv, pick, type CsvRow, type TextFile } from './files'
|
||||
* vers un format commun, avant la recherche des fiches correspondantes.
|
||||
*/
|
||||
|
||||
export type ImportSource = 'letterboxd' | 'tvtime' | 'mal' | 'anilist'
|
||||
export type ImportSource = 'text' | 'letterboxd' | 'tvtime' | 'mal' | 'anilist'
|
||||
export type EntryKind = 'movie' | 'tv' | 'anime'
|
||||
|
||||
export interface ImportEntry {
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import type { WatchStatus } from '../../types'
|
||||
import { cleanText, LIMITS } from '../security'
|
||||
import { titleKey, type EntryKind, type ImportEntry } from './sources'
|
||||
|
||||
/**
|
||||
* Liste collée depuis l'app Notes (ou n'importe quel texte) : une ligne par titre.
|
||||
* « Inception (2010) 4,5/5 trop bien » « Breaking Bad ★★★★★ » « One Piece - en cours S3E12 »
|
||||
* « - [x] Dune 2 : 8/10 » « Films à voir : » (titre de section, s'applique aux lignes suivantes)
|
||||
* Ce qui suit le titre peut contenir une note, une année, un statut, une progression et un avis (le reste du texte).
|
||||
*/
|
||||
|
||||
export const TEXT_MAX_LINES = 500
|
||||
export const TEXT_MAX_CHARS = 100_000
|
||||
|
||||
/** Texte sans accents, en minuscules (pour reconnaître les mots-clés). */
|
||||
const plain = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
|
||||
|
||||
// ─── Titres de section (« Films », « Séries à voir », « Animes vus :») ───
|
||||
|
||||
const HEAD_KIND: [RegExp, EntryKind][] = [
|
||||
[/\b(films?|movies?|cinema)\b/, 'movie'],
|
||||
[/\b(series?|shows?|tv shows?|tv|k-?dramas?|c-?dramas?|dramas?)\b/, 'tv'],
|
||||
[/\b(animes?|animations? japonaises?|mangas?)\b/, 'anime'],
|
||||
]
|
||||
const HEAD_STATUS: [RegExp, WatchStatus][] = [
|
||||
[/\b(a voir|a regarder|a mater|to watch|watchlist|plan to watch|envies?|wishlist)\b/, 'a_voir'],
|
||||
[/\b(en cours|watching|currently watching)\b/, 'en_cours'],
|
||||
[/\b(deja vus?|vus?|vues|termines?|terminees?|finis?|finies|watched|seen|completed|done)\b/, 'termine'],
|
||||
[/\b(en pause|on hold|paused)\b/, 'pause'],
|
||||
[/\b(abandonnes?|abandonnees?|dropped)\b/, 'abandonne'],
|
||||
]
|
||||
const HEAD_FILLER = /\b(mes|my|les|the|a|et|and|de|des|du|to|ma|liste|list|que|j'ai|i|ve|have|pour|plus|tard|later)\b/g
|
||||
|
||||
function heading(line: string, colon: boolean): { kind?: EntryKind; status?: WatchStatus } | undefined {
|
||||
const whole = plain(line).replace(/[^\p{L}\p{N}' -]+/gu, ' ').replace(/\s+/g, ' ').trim()
|
||||
let s = plain(line).replace(/[^\p{L}\p{N}' -]+/gu, ' ').replace(/\s+/g, ' ').trim()
|
||||
if (!s || s.length > 40) return undefined
|
||||
let kind: EntryKind | undefined
|
||||
let status: WatchStatus | undefined
|
||||
for (const [re, k] of HEAD_KIND) if (re.test(s)) ((kind ??= k), (s = s.replace(re, ' ')))
|
||||
for (const [re, st] of HEAD_STATUS) if (re.test(s)) ((status ??= st), (s = s.replace(re, ' ')))
|
||||
if (!kind && !status) return undefined
|
||||
// Statut seul (« Déjà vu » est aussi un film) : avec « : » ou sous une forme typique de liste
|
||||
if (!kind && !colon && !/^(?:mes |my )?(a voir|a regarder|to watch|watchlist|en cours|vus|deja vus|termines|finis|watched|seen)$/.test(whole)) return undefined
|
||||
// Tout le reste doit être du remplissage (« Mes films à voir plus tard ») : sinon c'est un titre (« Drive », « Vu du ciel »)
|
||||
return s.replace(HEAD_FILLER, ' ').replace(/[' -]/g, '').trim() ? undefined : { kind, status }
|
||||
}
|
||||
|
||||
// ─── Morceaux reconnus après le titre ───
|
||||
|
||||
const STATUS_WORDS: [RegExp, WatchStatus][] = [
|
||||
[/\b(a voir|a regarder|a mater|to watch|plan to watch|watchlist|pas vu|pas encore vu|not seen)\b/, 'a_voir'],
|
||||
[/\b(en cours|encours|commence|commencee|watching|ongoing)\b/, 'en_cours'],
|
||||
[/\b(en pause|pause|on hold)\b/, 'pause'],
|
||||
[/\b(abandonnee?s?|lache|lachee|drop|dropped|arrete|arretee)\b/, 'abandonne'],
|
||||
[/\b(deja vus?|vus?|vues?|fini|finie|termine|terminee|watched|seen|done|finished|completed)\b/, 'termine'],
|
||||
]
|
||||
|
||||
/** Note trouvée dans le texte → sur 10 (pas d'un demi-point d'étoile). */
|
||||
function findRating(s: string): { rating: number; index: number; length: number } | undefined {
|
||||
const toTen = (v: number) => Math.min(10, Math.max(1, Math.round(v)))
|
||||
// 4,5/5 · 8/10 · 16/20 · 85/100
|
||||
let m = /(\d{1,3}(?:[.,]\d{1,2})?)\s*\/\s*(5|10|20|100)\b/.exec(s)
|
||||
if (m) {
|
||||
const v = Number(m[1].replace(',', '.'))
|
||||
const den = Number(m[2])
|
||||
if (v > 0 && v <= den) return { rating: toTen((v / den) * 10), index: m.index, length: m[0].length }
|
||||
}
|
||||
// ★★★★½ · ⭐⭐⭐ · 🌟🌟
|
||||
m = /(?:[★⭐🌟]️?){1,5}\s*(½|,5|\.5)?/u.exec(s)
|
||||
if (m) {
|
||||
const stars = (m[0].match(/[★⭐🌟]/gu) ?? []).length
|
||||
return { rating: toTen(stars * 2 + (m[1] ? 1 : 0)), index: m.index, length: m[0].length }
|
||||
}
|
||||
// 4,5 étoiles · 4 stars · 3.5★ · 4*
|
||||
m = /(\d(?:[.,]5)?)\s*(?:etoiles?|étoiles?|stars?|\*|☆)/iu.exec(s)
|
||||
if (m) {
|
||||
const v = Number(m[1].replace(',', '.'))
|
||||
if (v > 0 && v <= 5) return { rating: toTen(v * 2), index: m.index, length: m[0].length }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export interface TextOptions {
|
||||
/** Statut des lignes qui n'en donnent aucun (ni note, ni avis, ni section) */
|
||||
defaultStatus: 'termine' | 'a_voir'
|
||||
}
|
||||
|
||||
export interface TextEntry extends ImportEntry {
|
||||
/** Ligne d'origine, affichée à la vérification */
|
||||
line: string
|
||||
/** Type donné par une section (« Films : ») : sinon on cherche partout */
|
||||
kindKnown: boolean
|
||||
/** Progression « S2E5 » (convertie en épisodes vus une fois les saisons connues) */
|
||||
progress?: { season: number; episode: number }
|
||||
/** « Déjà vu », « Ni vu ni connu » : le mot de statut fait peut-être partie du titre. Titre complet et statut à reprendre dans ce cas. */
|
||||
fullTitle?: string
|
||||
fullStatus?: WatchStatus
|
||||
}
|
||||
|
||||
/** Puces, cases à cocher et numéros en début de ligne. */
|
||||
const BULLET = /^\s*(?:[-*•◦▪▫‣⁃·–—>]+|\d{1,4}\s*[.)-]|\[[ xX✓✔]?\]|[☐☑☒✅✔✓❌🔲🔳]️?)\s*/u
|
||||
const DONE_MARK = /^\s*(?:[-*•]\s*)?(?:\[[xX✓✔]\]|[☑☒✅✔✓]️?)/u
|
||||
const TODO_MARK = /^\s*(?:[-*•]\s*)?(?:\[ ?\]|[☐🔲🔳])/u
|
||||
|
||||
function parseLine(raw: string, ctx: { kind?: EntryKind; status?: WatchStatus }, opts: TextOptions, n: number): TextEntry | undefined {
|
||||
let s = raw.replace(/\s+/g, ' ').trim()
|
||||
const checked = DONE_MARK.test(s) ? 'termine' : TODO_MARK.test(s) ? 'a_voir' : undefined
|
||||
for (let i = 0; i < 3 && BULLET.test(s); i++) s = s.replace(BULLET, '')
|
||||
if (!s) return undefined
|
||||
|
||||
// Coupure entre le titre et la suite : séparateur entouré d'espaces, note, année entre parenthèses, épisode
|
||||
const cuts: number[] = []
|
||||
const sep = /\s[-–—|:=>]+\s|\s?\|\s?|\s→\s/.exec(s)
|
||||
if (sep) cuts.push(sep.index)
|
||||
const rating = findRating(s)
|
||||
if (rating) cuts.push(rating.index)
|
||||
const yearParen = /[([](\d{4})[)\]]/.exec(s)
|
||||
if (yearParen) cuts.push(yearParen.index)
|
||||
const ep = /\b(?:s|saison|season)\s?(\d{1,3})\s?(?:e|ep|épisode|episode|x)\s?(\d{1,4})\b/i.exec(s) ?? /\b(\d{1,2})x(\d{1,4})\b/.exec(s)
|
||||
if (ep) cuts.push(ep.index)
|
||||
const cut = Math.min(s.length, ...cuts.filter((i) => i > 0))
|
||||
let title = s.slice(0, cut)
|
||||
let rest = s.slice(cut)
|
||||
|
||||
// Statut collé à la fin du titre sans séparateur : « Inception vu », « Dune à voir »
|
||||
let status: WatchStatus | undefined
|
||||
let fullTitle: string | undefined
|
||||
const titlePlain = plain(title)
|
||||
for (const [re, st] of STATUS_WORDS) {
|
||||
const end = new RegExp(`\\s(?:${re.source.slice(2, -2)})\\s*$`)
|
||||
const m = end.exec(titlePlain)
|
||||
if (m && m.index > 0) {
|
||||
status = st
|
||||
fullTitle = title
|
||||
title = title.slice(0, m.index)
|
||||
break
|
||||
}
|
||||
}
|
||||
title = cleanText(title.replace(/^[^\p{L}\p{N}"'«“(]+|[\s,;:.!?\-–—]+$/gu, '').replace(/^["'«“]\s*|\s*["'»”]$/g, ''), LIMITS.title) ?? ''
|
||||
if (!title || title.length < 1 || !/[\p{L}\p{N}]/u.test(title)) return undefined
|
||||
|
||||
// Ce qui suit : on retire la note, l'année, l'épisode, le statut ; le reste est l'avis
|
||||
let year: number | undefined
|
||||
if (rating) rest = rest.replace(s.slice(rating.index, rating.index + rating.length), ' ')
|
||||
if (yearParen) {
|
||||
const y = Number(yearParen[1])
|
||||
if (y >= 1870 && y <= 2200) year = y
|
||||
rest = rest.replace(yearParen[0], ' ')
|
||||
} else {
|
||||
const m = /^\s*[-–—|:,]?\s*(\d{4})\b/.exec(rest)
|
||||
const y = m ? Number(m[1]) : NaN
|
||||
if (y >= 1870 && y <= 2200) {
|
||||
year = y
|
||||
rest = rest.replace(m![0], ' ')
|
||||
}
|
||||
}
|
||||
let progress: TextEntry['progress']
|
||||
if (ep) {
|
||||
const season = Number(ep[1])
|
||||
const episode = Number(ep[2])
|
||||
if (season >= 1 && episode >= 1) progress = { season, episode }
|
||||
rest = rest.replace(ep[0], ' ')
|
||||
}
|
||||
const restPlain = plain(rest)
|
||||
if (!status) {
|
||||
for (const [re, st] of STATUS_WORDS) {
|
||||
const m = re.exec(restPlain)
|
||||
// Seulement un statut posé seul (« - vu », « : en cours »), pas un mot au milieu de l'avis
|
||||
if (m && /^[\s\-–—|:,.()[\]!]*$/.test(restPlain.slice(0, m.index))) {
|
||||
status = st
|
||||
rest = rest.slice(0, m.index) + rest.slice(m.index + m[0].length)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
const notes = cleanText(rest.replace(/^[\s\-–—|:,;.=>→()[\]]+|[\s\-–—|:,;=>→([]+$/g, '').replace(/\s+/g, ' '), LIMITS.notes)
|
||||
const review = notes && /[\p{L}]{2}/u.test(notes) ? notes : undefined
|
||||
|
||||
const pickStatus = (st?: WatchStatus): WatchStatus =>
|
||||
st ?? checked ?? (progress ? 'en_cours' : rating || review ? 'termine' : (ctx.status ?? opts.defaultStatus))
|
||||
const finalStatus = pickStatus(status)
|
||||
const clean = (v: string) => cleanText(v.replace(/^[^\p{L}\p{N}"'«“(]+|[\s,;:.!?\-–—]+$/gu, ''), LIMITS.title)
|
||||
return {
|
||||
key: `txt:${n}:${titleKey(title)}`,
|
||||
line: s.slice(0, 300),
|
||||
kind: ctx.kind ?? (progress ? 'tv' : 'movie'),
|
||||
kindKnown: !!ctx.kind,
|
||||
title,
|
||||
year,
|
||||
status: finalStatus,
|
||||
rating: finalStatus === 'a_voir' ? undefined : rating?.rating,
|
||||
notes: review,
|
||||
progress,
|
||||
fullTitle: fullTitle ? clean(fullTitle) : undefined,
|
||||
fullStatus: fullTitle ? pickStatus(undefined) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** Lit le texte collé : une entrée par titre (les doublons exacts sont fusionnés). */
|
||||
export function parseTextList(text: string, opts: TextOptions): TextEntry[] {
|
||||
const lines = text.slice(0, TEXT_MAX_CHARS).split(/\r?\n/)
|
||||
const ctx: { kind?: EntryKind; status?: WatchStatus } = {}
|
||||
const out = new Map<string, TextEntry>()
|
||||
let n = 0
|
||||
for (const raw of lines) {
|
||||
if (out.size >= TEXT_MAX_LINES) break
|
||||
const line = raw.trim()
|
||||
if (!line) continue
|
||||
const head = heading(line.replace(/:\s*$/, ''), /:\s*$/.test(line))
|
||||
if (head) {
|
||||
// Nouvelle section : « Films » remet le statut à zéro, « À voir » garde le type en cours
|
||||
if (head.kind) {
|
||||
ctx.kind = head.kind
|
||||
ctx.status = head.status
|
||||
} else ctx.status = head.status
|
||||
continue
|
||||
}
|
||||
const e = parseLine(line, ctx, opts, n++)
|
||||
if (!e) continue
|
||||
const dup = `${e.kind}|${titleKey(e.title)}|${e.year ?? ''}`
|
||||
const prev = out.get(dup)
|
||||
if (prev) {
|
||||
// Même titre deux fois : on garde ce qui est le plus renseigné
|
||||
prev.rating ??= e.rating
|
||||
prev.notes ??= e.notes
|
||||
if (prev.status === 'a_voir') prev.status = e.status
|
||||
continue
|
||||
}
|
||||
out.set(dup, e)
|
||||
}
|
||||
return [...out.values()]
|
||||
}
|
||||
Reference in new issue
Block a user