From 5c0c0e086d91c34b325dc0d811a014a9d2360fb0 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 18:51:23 +0000 Subject: [PATCH 01/16] Fix multi-file and structured leaf book names and keep reverted titles Scan revision 6: a multi-file book whose album is its series, or that has no album, takes its folder title rather than the series or the first file's tag; a leaf folder's position goes with its own series only, an untagged leaf uses its title part (or its series and position), 'Books 01-03' reads like 'Book 01-03', and a disc folder under a leaf no longer takes the whole leaf as its series. Only books the new rules may read differently are re-read once. A title an admin reverted is locked against a later fill's tidy. server#272, #325 (leaf names), #307. --- CLAUDE.md | 2 +- CONVENTIONS.md | 31 +++++-- internal/catalog/books.go | 5 +- internal/catalog/metadatasource_test.go | 14 +-- internal/catalog/overrides.go | 47 ++++++---- internal/catalog/pathreading.go | 25 ++++-- internal/catalog/pathreading_test.go | 8 +- internal/library/pathreading_test.go | 114 +++++++++++++++++++++--- internal/library/scanner.go | 19 ++-- internal/matchrun/offered_test.go | 62 +++++++++++++ internal/matchrun/runner.go | 3 +- internal/meta/prefill.go | 35 +------- internal/meta/prefill_test.go | 10 --- internal/metadata/layout.go | 15 ++++ internal/metadata/layout_test.go | 4 + internal/metadata/metadata.go | 81 ++++++++++++----- internal/metadata/metadata_test.go | 50 +++++++---- internal/metadata/seriestitle.go | 11 ++- internal/metadata/seriestitle_test.go | 34 +++---- pkg/match/match.go | 18 ++++ 20 files changed, 421 insertions(+), 167 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4ad43047f..6f875c81e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -125,7 +125,7 @@ internal/auth/ users, argon2id, opaque hashed tokens, auth codes; hash.go internal/relpath/ library-relative path rules shared by catalog and auth: Clean (canonical form) and Within (the segment-boundary rule of share scopes and cast tokens) internal/catalog/ libraries, access grants, books, FTS search, listening state (the data layer) internal/library/ filesystem view (fsview.go: SafeJoin, SafeJoinListed for the stream, /fs and a book read on demand (each name looked for in its folder's listing first, see Path spelling), and ContentPath/ContentJoin, the one hidden-segment rule) + background scanner (scanner.go: incl. IndexMoved and the .audiosilo/ walk; scanread.go: a scan reads several files at once, `scan.concurrency`, default one per CPU up to 8, and writes the index alone in discovery order, so the result is a serial scan's, a few books a transaction: `catalog.UpsertBooks`, `writeBatch`, each book under its own savepoint); attachments.go (a book's Bridge attachments: signatures, RefreshAttachments); givenup.go (givenUp: a file beside a book's audio whose bounded look was given up on keeps the book as stored, its problem recorded); ebook.go (BookEbook, the Bridge's own .epub rule, for the estimate and, through the one rule function ebookCandidate fed by the walk, books.ebook_path, the reader's ebook; a readable one only: a zip whose directory lists META-INF/container.xml, as the Bridge reads it; OpenEbook, every open of one: a regular file inside the library, checked before it is opened and the same file once open; OpenEbookBounded, the reader's, a bounded call) -internal/metadata/ dhowden/tag + ffprobe extraction (fastprobe*.go: the in-process probe, ffprobe's answer read in Go by the configured ffprobe's release's rules, but a header-less VBR MP3's frames counted where ffprobe estimates, ffprobe for a file it is unsure of, see In-process probe; probeview.go: ProbeView, the comparison cmd/probediff and the fixture tests make; bounded.go: Bounded, every other look at a library file a share that stopped answering would hold (a stat, a listing, an open and its reads) under a scan read's bounds and per-mount cap, given up on as GaveUp (see In-process probe), TransientFault (the share-fault rule's transient list, see Share faults), and NamesListed; openbelow.go: Below, a request's open through an os.Root at the library's root (OpenRegularBelow, ReadDirBelow); belowcache.go: BelowFolder, the scan's (OpenBelow, StatBelow, LstatBelow), through the file's folder kept open a moment, one openat a file; toolinput.go: ToolInput (bounded, one entry point), ffprobe and ffmpeg handed the file opened so, never its path (see Path spelling, links out of the root), and InputFormats/InputFormatArgs, the one demuxer list every tool run on a library file or an episode takes; dirnames.go: DirNames, the folder listings the spelling checks read, kept 3 s (see Path spelling); tagreader.go: ReadTags, the tag reads outside Extract (media.EmbeddedCoverBelow; Extract reads through the probe's block cache): dhowden reads an ID3v2 tag through a buffer up to the tag's end, not a byte per read system call; a narrator tag beats composer in both passes; mp4narrator.go reads the iTunes \xa9nrt item, which neither reads, with a bounded box walk; a series tag ending in a marked position, "Discworld, book #40", is the series and that position: seriestag.go SplitSeriesTag; a `series-part` tag "1-3" is a range: seriesrange.go, ParseSeriesRange, the one grammar of a range position, and ParseSeriesPosition, a number or a range; incl. ReleaseDate: a date tag as YYYY[-MM[-DD]], stored as books.released, never as published); DeriveFromPath (structural path parsing, the scan's baseline: the folder holding the book is the series and the one above it the author, but a lone folder is the author; a leaf named `Author; Series; Book NN[; Title]` states the series and position, a range or none, `@rev` 3); layout.go: ReadPathLayout (author/series/book LAYOUT, the match's path facts) and FromPathLayout (a path-first library's values); absfile.go: ParseABSFile/ReadABSFile (an Audiobookshelf metadata.json, see Metadata overrides); attachments.go: AttachmentsDir `.audiosilo`, Read/ParseCharacters, Recaps, Description and Provenance (the Bridge's generated files, checked against audiosilo-meta's formats; see Bridge attachments); chapterlist.go: Read/ParseChapterList (the Bridge's `chapters.json`, chapters found in the narration; see Generated chapters); foldercode.go: FolderCodePosition (a position or range from the code leading a folder name, "DH06 - ...", "LAM05-06", its letters the series' initials; read only by the Bridge's books listing); discfolder.go: IsDiscFolder ("CD 2", "Disc 3": the scan's join rule, and the Audible backup destination check); titlepos.go: PositionInTitle (a series position read from a title that is the series' name then a number, "He Who Fights with Monsters 4: ..."; narrow: set off by a space or comma, 1-3 digits, then the end or a separator, never a range); seriestitle.go: TitleNotSeries (an album tag naming only the book's series gives way to the title tag or the path's title; LeafSeries reads an `Author; Series; Book NN; Title` leaf (a `Leaf`: series, title part, position or range) and PathLeafSeries a book's own; MaybeSeriesTitle, the scan's re-read test for a snapshot before `@rev` 2; Metadata.PartsTitle: a book of several files takes the album over its first file's title tag, unless its folder or its last file's tag says the tag is the book's (PartNamed: when that file is worth reading), `@rev` 5; see Metadata overrides in CONVENTIONS.md) +internal/metadata/ dhowden/tag + ffprobe extraction (fastprobe*.go: the in-process probe, ffprobe's answer read in Go by the configured ffprobe's release's rules, but a header-less VBR MP3's frames counted where ffprobe estimates, ffprobe for a file it is unsure of, see In-process probe; probeview.go: ProbeView, the comparison cmd/probediff and the fixture tests make; bounded.go: Bounded, every other look at a library file a share that stopped answering would hold (a stat, a listing, an open and its reads) under a scan read's bounds and per-mount cap, given up on as GaveUp (see In-process probe), TransientFault (the share-fault rule's transient list, see Share faults), and NamesListed; openbelow.go: Below, a request's open through an os.Root at the library's root (OpenRegularBelow, ReadDirBelow); belowcache.go: BelowFolder, the scan's (OpenBelow, StatBelow, LstatBelow), through the file's folder kept open a moment, one openat a file; toolinput.go: ToolInput (bounded, one entry point), ffprobe and ffmpeg handed the file opened so, never its path (see Path spelling, links out of the root), and InputFormats/InputFormatArgs, the one demuxer list every tool run on a library file or an episode takes; dirnames.go: DirNames, the folder listings the spelling checks read, kept 3 s (see Path spelling); tagreader.go: ReadTags, the tag reads outside Extract (media.EmbeddedCoverBelow; Extract reads through the probe's block cache): dhowden reads an ID3v2 tag through a buffer up to the tag's end, not a byte per read system call; a narrator tag beats composer in both passes; mp4narrator.go reads the iTunes \xa9nrt item, which neither reads, with a bounded box walk; a series tag ending in a marked position, "Discworld, book #40", is the series and that position: seriestag.go SplitSeriesTag; a `series-part` tag "1-3" is a range: seriesrange.go, ParseSeriesRange, the one grammar of a range position, and ParseSeriesPosition, a number or a range; incl. ReleaseDate: a date tag as YYYY[-MM[-DD]], stored as books.released, never as published); DeriveFromPath (structural path parsing, the scan's baseline: the folder holding the book is the series and the one above it the author, but a lone folder is the author; a leaf named `Author; Series; Book NN[; Title]` states the series and position, a range or none, `@rev` 3); layout.go: ReadPathLayout (author/series/book LAYOUT, the match's path facts) and FromPathLayout (a path-first library's values); absfile.go: ParseABSFile/ReadABSFile (an Audiobookshelf metadata.json, see Metadata overrides); attachments.go: AttachmentsDir `.audiosilo`, Read/ParseCharacters, Recaps, Description and Provenance (the Bridge's generated files, checked against audiosilo-meta's formats; see Bridge attachments); chapterlist.go: Read/ParseChapterList (the Bridge's `chapters.json`, chapters found in the narration; see Generated chapters); foldercode.go: FolderCodePosition (a position or range from the code leading a folder name, "DH06 - ...", "LAM05-06", its letters the series' initials; read only by the Bridge's books listing); discfolder.go: IsDiscFolder ("CD 2", "Disc 3": the scan's join rule, and the Audible backup destination check); titlepos.go: PositionInTitle (a series position read from a title that is the series' name then a number, "He Who Fights with Monsters 4: ..."; narrow: set off by a space or comma, 1-3 digits, then the end or a separator, never a range); seriestitle.go: TitleNotSeries (an album tag naming only the book's series gives way to the title tag or the path's title; LeafSeries reads an `Author; Series; Book NN; Title` leaf (a `Leaf`: series, title part, position or range) and PathLeafSeries also recognizes a disc below a leaf; MaybeSeriesTitle, the scan's re-read test for a snapshot before `@rev` 2; Metadata.PartsTitle: a book of several files takes the album over its first file's title tag, unless its folder or its last file's tag says the tag is the book's (PartNamed: when that file is worth reading), `@rev` 5; `@rev` 6 takes the folder over unconfirmed multi-file titles and reads a structured leaf's title, its own series position, and its author at the root; see Metadata overrides in CONVENTIONS.md) internal/media/ Range streaming, download, embedded cover extraction, transcoding (the file opened through the library root and handed over as a descriptor: fd:, else as metadata.ToolInput hands it, /dev/fd/3 through a link on Unix, a re-checked, held path on Windows, for an ffmpeg older than 6.1, a cached copy's run too; pipe:0 for a podcast episode on an older ffmpeg; every input whose demuxer ffmpeg guesses an audio container only, metadata.InputFormatArgs); filecache.go: FileCache, a cache of copies ffmpeg makes from a cacheSpec (LRU by mtime, single-flight, .part + rename, disk guard, refusals remembered for an hour; Open/Status/Queue/WarmAll); remux.go: NewRemuxer, the MP3-in-MKA remux spec (/cache/remux, 8 GiB, warmed by /item and /chapters, a cold stream transcoded after 2 s (a download, or with every transcode slot busy, after up to 45 s), own ETag; see Recognized audio); rendition.go: NewRenditionCache, the watch rendition spec (/cache/renditions/watch, AAC-LC mono 48 kbps, 10 GiB; see Watch renditions); remoteart.go: ArtFetcher, the one remote art fetcher (community covers, podcast artwork) over a caller's netguard transport: no user info, <= 3 redirects without a downgrade, a 200 only, a byte cap internal/names/ reading people in an Author/Narrator credit: Split (the deliberately shy co-credit rule), Reversed ("Surname, Given"), SortKey (surname first; the catalog registers it as the SQL function name_sort for the admin list's surname sort) internal/meta/ Phase 1.5 community metadata lookup: HTTP client + Service (asin/isbn, or the book's recorded match in book_matches via EnrichMatch when it names another work or those find nothing -> composed enrichment envelope; a LibriVox recording's `librivox` id and links) with a bounded TTL cache and its persistent SQLite level (store.go); the /meta bundle's previous works and spoiler gating (bundle.go); the admin console's match (match.go: metaserve works/match over tag + path facts, metadata.ReadPathLayout; works/search fallback for an older metaserve); a bulk run's spacing of its requests (pacer.go: `Pacer`, `WithPacer`, the remote leg's `pacedTransport`); a call's time budget (budget.go: `withBudget`, which a bulk run's Retry-After waits don't count against, and `WithSharedBudget` for a request that composes twice); community cover fetches (cover.go: public addresses only); owned books' work ids for the Series cards (workids.go); placing the caller's books on rails and the next rail entry (local.go); which of a work's series a book is in (seriesrules.go: the series rules below); a work's positions on this book's chapters (positionscale.go: `OnRecording`); generated content laid beside the community work (generated.go: `Answer`, `Unmatched`, `MetaGenerated`, `MetaGeneratedDescription`); cache-only reads for the Bridge's estimate and book facts (cachedenrich.go: `cachedAnswerOf`, the newer of the cache and the upcoming job's resolution; `Coverages`, `CachedWork`, a `Coverage` per book whose `Description` is the community work's `community_description`); the console's Add from LibriVox reads (librivox.go: `LibrivoxSearch`, `LibrivoxWork`, `LibrivoxRecordingOf`) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 326c229ee..96fee8c91 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -2366,7 +2366,7 @@ every session. CLAUDE.md keeps a one-line index of these topics. layout over the tags (`bookLayers.scannedFields`: `metadata.FromPathLayout`, where the top folder is the AUTHOR and disc/track folders are parts, unlike `DeriveFromPath`'s two nearest folders; a layout value goes over a tag's wherever it says anything and replaces the baseline's own reading even with - nothing (a leaf named `Author; Series; Book NN[; Title]` says its series, position and title part, `LeafSeries`); the title always keeps one, and a tag title that IS the folder's name, number and all ("13 Reasons Why"), stays whole with no position read from it (never a `LeafSeries` leaf, whose parts the layout reads even when the title is the whole leaf, as an untagged book's is); the position goes with the series: the layout's own, else + nothing (a leaf named `Author; Series; Book NN[; Title]` says its series, position and title part, `LeafSeries`); the title always keeps one, and a tag title that IS the folder's name, number and all ("13 Reasons Why"), stays whole with no position read from it; the position goes with the series: the layout's own, else the scanned one only while the series it numbers stays). It is a resolve rule, not a scan one: the snapshot is unchanged, and `UpdateLibrary` marks the library's books due a re-resolve in the edit's own transaction (`markResolve`: the `library_resolve_due` row of `server_state`, the library's id and the change's @@ -2426,8 +2426,7 @@ every session. CLAUDE.md keeps a one-line index of these topics. (`ParseSeriesRange`, the start and `SeriesIndexEnd`), "Book XX" and "Book 00" the series with no position. As the path baseline it fills only a series the tags leave out (a series tag still wins, `readNames`), and it reads as the path's source; a path-first library's - `FromPathLayout` reads the leaf too (its series, position and title part). The leaf's title - stays the whole name in `DeriveFromPath` (`TitleNotSeries` reads the title part). The LibraForge + `FromPathLayout` reads the leaf too (its series, position and title part). Revision 3 kept the whole leaf as the path title. The LibraForge benchmark's library of these (about 600 books): +39 auto-right, auto-wrong 8 to 7. **The tag reading** (`@rev` 4, server#175): a snapshot written before 2.4.0 and 2.5.0 read tags as they do now (a series tag carrying its position, `metadata.SplitSeriesTag`; a title in any @@ -2449,13 +2448,27 @@ every session. CLAUDE.md keeps a one-line index of these topics. A book of one file keeps the title tag ("Portal to Nova Roma: Paris"). Corpus check: the LibriVox perf library (120 books) and the testbed libraries renamed four books, each to its album (Frankenstein, The Odyssey, The Diary of a Nobody, The Secret Agent's `secret_agent`), and nothing else. - **Backfill of revisions 2 to 5**: a snapshot older than today's that a newer revision may read + **Folder titles and leaf names** (`@rev` 6, server#272, server#325). For a book of several + files without an album, a title tag that differs between the first and last files gives way + to `PathTitle`. If the files carry different chapter titles and agree on any album they both name, + and the first has an album and no series tag, the scan uses a meaningful folder title when the album and folder + share no distinctive word. This preserves a fuller album title such as "Frankenstein; or, The + Modern Prometheus" in "Frankenstein". Filename tags such as "Part 01.mp3" leave the album in + place. Shared book names from revision 5 still apply. + A structured leaf now supplies its title part, or its series and position when it has no title + part ("Dark Road 1-5"). A tagged series can use the leaf's position only when both name the + same series (`match.SameSeries`). "Books 01-03" states the same range as "Book 01-03". + A disc folder indexed on its own takes the structured leaf above it as its book. At the + library root the author comes from the first part of a structured leaf. + **Backfill of revisions 2 to 6**: a snapshot older than today's that a newer revision may read otherwise (`Signature.NamesCheck`, `namesCheck` by `revNumber`: before revision 2 a title `metadata.MaybeSeriesTitle` flags, over the snapshot's title and series; before revision 3 a leaf `metadata.PathLeafSeries` reads; before revision 4 `tagReadingMayDiffer`: an MP4, a narrator, a series `SplitSeriesTag` splits, a non-ASCII letter in the title or path; before revision 5 a book of several files, which `Signatures` counts in `book_files` only for a folder book's older snapshot, - and whose last file is read too where its title turns on it, `partNamed`) + and whose last file is read too where its title turns on it, `partNamed`; before revision 6 a + structured leaf, a disc directly under one, or a multi-file book whose path title differs from + the snapshot title) is read once by the next scan with the PathRead read and rewritten by `SetPathReading` (which skips only a snapshot already at `scannedRev`), no re-index and no migration (a `PathFromSnapshot` one waits for that read too, so an unreadable file never records today's @@ -2468,9 +2481,9 @@ every session. CLAUDE.md keeps a one-line index of these topics. `indexed_at` then: `Signature.TagReadFailed`, `Catalog.SetTagReadFailed`), so those bytes are not read for them again on every scan (server#318); the next index of the book (its files changed, a Re-read) clears it, and a time-out, a run that failed or a count standing in for it cut short for now - (`uncountedForNow`) reads again. A current `@rev` 1 to 4 snapshot it doesn't flag + (`uncountedForNow`) reads again. A current `@rev` 1 to 5 snapshot it doesn't flag (`Signature.RevStamp`: its stamp the row's `indexed_at`) is stamped at today's revision by that - scan (`Catalog.StampScannedRev`, the revision alone, compare-and-set on a current revision 1 to 4, + scan (`Catalog.StampScannedRev`, the revision alone, compare-and-set on a current revision 1 to 5, `revOlderOwn`), so later scans don't test it again (`MaybeSeriesTitle` is about 2 µs a row); a snapshot of no revision stays until its next re-index or path reading. A stamped book is never tested again, so a later change that makes the reading change more books (`TitleNotSeries` more @@ -2847,7 +2860,9 @@ every session. CLAUDE.md keeps a one-line index of these topics. the community title is written; any other word or number keeps the file's ("part" names a split of the book, "abridged" another edition, "Book 2" of a work at position 1 another volume), and a title of the community's words and nothing more only when it is in one case. The review lists it - like any planned change. + like any planned change. An admin reverting a community title chooses the value underneath it. + The revert stores that title as an ordinary edited override, which later fills respect. Reverting + that edit releases the lock. **Tag identifiers are hints** (`0067`: `books.tag_asin` / `tag_isbn` / `tag_language`, read from `asin` / `audible_asin` / the iTunes freeform ASIN / an ID3 TXXX ASIN, `isbn`, `language` / TLAN in both tag passes, an ASIN or ISBN only in its proper form (`match.ValidASIN`/`ValidISBN`: `N/A` beside diff --git a/internal/catalog/books.go b/internal/catalog/books.go index 012d7025b..5d2663ddc 100644 --- a/internal/catalog/books.go +++ b/internal/catalog/books.go @@ -532,7 +532,8 @@ type Signature struct { // (metadata.PathLeafSeries); before revision 4, one the tag reading may read // otherwise (tagReadingMayDiffer); before revision 5 (a book of several // files no longer takes its first file's title tag: metadata.PartsTitle), - // one of several files. + // one of several files. Before revision 6, a structured leaf or a disc under + // one, or a multi-file book with a different path title. NamesCheck bool // DurationStale: a book holding an MP3 whose lengths were read before // today's revision (durationRev: books.duration_rev), or since by an @@ -547,7 +548,7 @@ type Signature struct { // not read it again for them (server#318). An index of the book (its files // changed, a Re-read) clears it. TagReadFailed bool - // RevStamp: a book whose snapshot is its own and of revision 1 to 4 (so + // RevStamp: a book whose snapshot is its own and of revision 1 to 5 (so // PathOK) that needs no read (not NamesCheck), which the next scan stamps // with today's revision (StampScannedRev), so it is never tested again. RevStamp bool diff --git a/internal/catalog/metadatasource_test.go b/internal/catalog/metadatasource_test.go index ea1be06c7..c6669b90b 100644 --- a/internal/catalog/metadatasource_test.go +++ b/internal/catalog/metadatasource_test.go @@ -450,9 +450,9 @@ func TestPreferPathKeepsWhatThePathDoesNotSay(t *testing.T) { // the series and position (metadata.DeriveFromPath, metadata.FromPathLayout), // so the scan's reading of them reads as the path's; a library that prefers its // folders keeps them (its layout reads the leaf too) and takes the title part -// over the tags' title, and a range is the leaf's in both. An untagged book's -// title is the whole leaf: the folders' library still takes its title part and -// position, beside a series tag spelled another way. +// over the tags' title, and a range is the leaf's in both. The untagged title is the leaf's title part. +// Only a library preferring the leaf's series takes its position beside a +// tag that names another series. func TestLeafSeriesSources(t *testing.T) { t.Parallel() c, ctx := newTestCatalog(t) @@ -467,8 +467,8 @@ func TestLeafSeriesSources(t *testing.T) { {RelPath: tufo, Title: "From The Ashes (Unabridged)", Author: "Mark Tufo", Series: "Indian Hill", SeriesIndex: 4}, {RelPath: rules, Title: "The Rules: The Complete Series", Author: "Aaron Oster", Series: "The Rules", SeriesIndex: 1, SeriesIndexEnd: 3}, - {RelPath: spell, Title: "Larry Correia; Grimnoir Chronicles; Book 02; Spellbound", Author: "Larry Correia", - Series: "Grimnoir", SeriesIndex: 2}, + {RelPath: spell, Title: "Spellbound", Author: "Larry Correia", + Series: "Grimnoir"}, } { b.LibraryID, b.IsFolder, b.AddedAt = lib.ID, true, "2020-01-01" if _, err := c.UpsertBook(ctx, b); err != nil { @@ -477,8 +477,8 @@ func TestLeafSeriesSources(t *testing.T) { } title := [2]string{"From The Ashes (Unabridged)", SourceTag} untagged := map[string][2]string{ - FieldTitle: {"Larry Correia; Grimnoir Chronicles; Book 02; Spellbound", SourcePath}, - FieldSeries: {"Grimnoir", SourceTag}, FieldSeriesIndex: {"2", SourcePath}, + FieldTitle: {"Spellbound", SourcePath}, + FieldSeries: {"Grimnoir", SourceTag}, FieldSeriesIndex: {"", ""}, } if src == MetadataFromPath { title = [2]string{"From The Ashes", SourcePath} diff --git a/internal/catalog/overrides.go b/internal/catalog/overrides.go index a74dc0387..1ec066356 100644 --- a/internal/catalog/overrides.go +++ b/internal/catalog/overrides.go @@ -285,22 +285,23 @@ const scannedStampKey = "@indexed_at" // a narrator tag over composer), which a snapshot stamped from an older // revision never had; one of revision 4 predates revision 5, when a book of // several files stopped taking its first file's title tag over the album that -// tag extends (metadata.PartsTitle, server#272). The next scan reads such a +// tag extends (metadata.PartsTitle, server#272). Revision 6 reads the folder +// title for unconfirmed multi-file titles and the names a leaf states, including +// the leaf above a disc folder (server#272, server#325). The next scan reads such a // book again where a newer revision may read it otherwise // (Signature.NamesCheck) and stamps the rest (StampScannedRev). A new revision // adds the one before it to revOlderOwn's list, so its snapshots are stamped // too. const ( scannedRevKey = "@rev" - scannedRev = "5" + scannedRev = "6" // The revisions that brought a reading in, so a snapshot of one needs no read - // for it (Signature.NamesCheck): TitleNotSeries (MaybeSeriesTitle), a leaf - // that states a series (PathLeafSeries), the tag reading (tagReadingMayDiffer), - // a book of several files' title. + // for it (Signature.NamesCheck): TitleNotSeries, the tag reading, multi-file + // titles, and the latest folder and leaf rules. revTitleNotSeries = 2 - revLeafSeries = 3 revTagReading = 4 revPartsTitle = 5 + revFolderNames = 6 ) // revNumber is a snapshot's revision as a number: 0 before revision 1 (none), @@ -592,8 +593,8 @@ func (l *bookLayers) resolve() map[string]FieldValue { // (overABS). // // The baseline also reads the title the way metadata.TitleNotSeries may take it -// in place of an album that only names the series (metadata.PathTitle: "Mark -// Tufo; Indian Hill; Book 05; Into the Fire"), which DeriveFromPath doesn't: a +// in place of an album that only names the series (metadata.PathTitle can read +// the parent of a disc as the title, where DeriveFromPath reads the disc): a // scanned title equal to that one is the baseline's. // // A series with no position takes the one its title gives @@ -646,12 +647,10 @@ func (l *bookLayers) readScanned() (scanned, baseline, layout bookFields) { } layout = pathFields(metadata.FromPathLayout(l.path, l.isFolder)) raw := metadata.ReadPathLayout(l.path, l.isFolder) - if _, leaf := metadata.LeafSeries(raw.Title); !leaf && raw.Title != "" && + if number, title := metadata.SplitSeriesIndex(raw.Title); (number != 0 || title != raw.Title) && strings.EqualFold(strings.TrimSpace(l.scanned[FieldTitle]), raw.Title) { // The tag title IS the folder's name, number and all ("13 Reasons Why"): // the number is part of the title, not a volume the layout can split off. - // A leaf named "Author; Series; Book NN[; Title]" is no such title (an - // untagged book's is the whole leaf): the layout reads its parts. layout[FieldTitle], layout[FieldSeriesIndex] = l.scanned[FieldTitle], raw.Position } scanned = maps.Clone(l.scanned) @@ -849,8 +848,10 @@ type BookEdit struct { // ASIN, while that ASIN is no admin's own edit (one typed in since, the // same value), else ErrMatchedSince. "" keeps the zero MatchIf's rule. MatchIfASIN string - Source string - UserID int64 + // KeepEditedTitle protects a fill against a title edit made after it read the book. + KeepEditedTitle bool + Source string + UserID int64 } // normalizeSource is where an edit or a custom cover came from, as stored: @@ -1081,6 +1082,21 @@ func (c *Catalog) editTx(ctx context.Context, tx *sql.Tx, ref Ref, edit BookEdit return err } } + if edit.Source == SourceEdited && slices.Contains(edit.Revert, FieldTitle) { + l, err := loadLayers(ctx, tx, bookID) + if err != nil { + return err + } + if l.overrides[FieldTitle].Source == SourceCommunity { + // Reverting the community title chooses the value underneath it. + // Store that choice like any admin edit so a later fill respects it. + set := make(map[string]string, len(edit.Set)+1) + maps.Copy(set, edit.Set) + set[FieldTitle] = l.unedited(FieldTitle)[FieldTitle].Value + edit.Set = set + edit.Revert = slices.DeleteFunc(slices.Clone(edit.Revert), func(field string) bool { return field == FieldTitle }) + } + } set, revert := edit.Set, edit.Revert swapSet, swapRevert, err := seriesSwap(ctx, tx, bookID, edit) if err != nil { @@ -1116,8 +1132,9 @@ func (c *Catalog) editTx(ctx context.Context, tx *sql.Tx, ref Ref, edit BookEdit VALUES(?,?,?,?,?,?,?) ON CONFLICT(library_id, path, field) DO UPDATE SET value = excluded.value, source = excluded.source, - updated_by = excluded.updated_by, updated_at = excluded.updated_at`, - ref.LibraryID, path, field, v, edit.Source, editor, now); err != nil { + updated_by = excluded.updated_by, updated_at = excluded.updated_at + WHERE NOT (? AND book_overrides.source = 'edited')`, + ref.LibraryID, path, field, v, edit.Source, editor, now, edit.KeepEditedTitle && field == FieldTitle); err != nil { return err } } diff --git a/internal/catalog/pathreading.go b/internal/catalog/pathreading.go index 9e49dfef3..65e99b177 100644 --- a/internal/catalog/pathreading.go +++ b/internal/catalog/pathreading.go @@ -60,7 +60,7 @@ const pathCheckExpr = `CASE // // The fifth column is revOlderOwn, so an older snapshot a scan finds needs no // read can be stamped with today's revision (StampScannedRev). The sixth is -// whether a folder book whose snapshot predates revision 5 has several files +// whether a folder book with an older snapshot has several files // (always false for today's, so the count is never taken for it). const snapshotNamesExpr = `CASE WHEN json_valid(scanned) THEN json_extract(scanned, '$."@rev"') END, CASE WHEN json_valid(scanned) THEN IFNULL(json_extract(scanned, '$.title'), '') ELSE title END, @@ -70,12 +70,12 @@ const snapshotNamesExpr = `CASE WHEN json_valid(scanned) THEN json_extract(scann CASE WHEN is_folder AND CASE WHEN json_valid(scanned) THEN json_extract(scanned, '$."` + scannedRevKey + `"') END IS NOT '` + scannedRev + `' THEN (SELECT COUNT(*) > 1 FROM (SELECT 1 FROM book_files f WHERE f.book_id = books.id LIMIT 2)) ELSE 0 END` -// revOlderOwn is whether a books row's snapshot is of revision 1 to 4 (older +// revOlderOwn is whether a books row's snapshot is of revision 1 to 5 (older // than today's, scannedRev, but read with a lone folder as the author) and its // own (its stamp the row's indexed_at, scannedStampKey): Signature.RevStamp, // and StampScannedRev's compare-and-set. const revOlderOwn = `CASE WHEN json_valid(scanned) - THEN IFNULL(json_extract(scanned, '$."` + scannedRevKey + `"'), '') IN ('1', '2', '3', '4') + THEN IFNULL(json_extract(scanned, '$."` + scannedRevKey + `"'), '') IN ('1', '2', '3', '4', '5') AND json_extract(scanned, '$."` + scannedStampKey + `"') IS indexed_at ELSE 0 END` @@ -87,11 +87,20 @@ const revOlderOwn = `CASE WHEN json_valid(scanned) // series (PathLeafSeries), before 4 a book the tag reading of 2.4.0 and 2.5.0 // may read otherwise (tagReadingMayDiffer), before 5 a book of several files // (severalFiles: its first file's title tag may have been taken over the -// album, metadata.PartsTitle). +// album, metadata.PartsTitle). Before revision 6 a structured leaf (including +// the parent of a disc) may supply different names, or a multi-file book +// may take its path title if that differs from its snapshot. func namesCheck(rev int, rel string, isFolder, severalFiles bool, format, title, series, narrator string) bool { - return (rev < revPartsTitle && severalFiles) || - (rev < revLeafSeries && metadata.PathLeafSeries(rel, isFolder)) || - (rev < revTitleNotSeries && metadata.MaybeSeriesTitle(rel, isFolder, title, series)) || + if rev < revFolderNames { + if metadata.PathLeafSeries(rel, isFolder) { + return true + } + if severalFiles { + pathTitle := metadata.PathTitle(rel, isFolder) + return rev < revPartsTitle || (pathTitle != "" && title != pathTitle) + } + } + return (rev < revTitleNotSeries && metadata.MaybeSeriesTitle(rel, isFolder, title, series)) || (rev < revTagReading && tagReadingMayDiffer(rel, format, title, series, narrator)) } @@ -118,7 +127,7 @@ func tagReadingMayDiffer(rel, format, title, series, narrator string) bool { // (Signature.RevStamp: no NamesCheck), so later scans don't test them again. // Their values are unchanged, so nothing is re-resolved or announced; a row // re-indexed or re-read since the scan read its signature (no longer a current -// revision 1 to 4 snapshot) is left as it is. It commits every +// revision 1 to 5 snapshot) is left as it is. It commits every // pathReadingBatch books. func (c *Catalog) StampScannedRev(ctx context.Context, libraryID int64, paths []string) error { return c.eachPathBatch(ctx, "StampScannedRev", libraryID, paths, func(tx *sql.Tx, relPath string) (bool, error) { diff --git a/internal/catalog/pathreading_test.go b/internal/catalog/pathreading_test.go index c5b1fc661..aaec2a398 100644 --- a/internal/catalog/pathreading_test.go +++ b/internal/catalog/pathreading_test.go @@ -177,8 +177,8 @@ func TestStampScannedRev(t *testing.T) { t.Fatal(err) } wantRevs := map[string]string{ - plain: "5|A Parade of Horribles", stale: "1|The Final Empire", series: "1|Without Law", - series2: "5|Without Law", leaf: "2|From The Ashes", plain2: "5|The Butcher's Masquerade", + plain: "6|A Parade of Horribles", stale: "1|The Final Empire", series: "1|Without Law", + series2: "6|Without Law", leaf: "2|From The Ashes", plain2: "6|The Butcher's Masquerade", } for rel, w := range wantRevs { var got string @@ -220,7 +220,9 @@ func TestNamesCheckByRevision(t *testing.T) { {"Latin accent at 3", 3, "A/Les Misérables", "mp3", "Les Misérables", "", "", true}, {"punctuation only at 3", 3, "A/B – C", "mp3", "B – C", "", "", false}, {"leaf series at 2", 2, leaf, "mp3", "From The Ashes", "", "", true}, - {"leaf series at 3", 3, leaf, "mp3", "From The Ashes", "", "", false}, + {"leaf series at 5", 5, leaf, "mp3", "From The Ashes", "", "", true}, + {"leaf series at 6", 6, leaf, "mp3", "From The Ashes", "", "", false}, + {"disc under leaf at 5", 5, leaf + "/CD1", "mp3", "CD1", leaf, "", true}, {"no revision", 0, "Charles Dickens/Great Expectations", "mp3", "Great Expectations", "", "", false}, } for _, c := range cases { diff --git a/internal/library/pathreading_test.go b/internal/library/pathreading_test.go index c07fe9cf0..c6519ab18 100644 --- a/internal/library/pathreading_test.go +++ b/internal/library/pathreading_test.go @@ -194,7 +194,7 @@ func TestScanTitleNotSeries(t *testing.T) { // for its series (read, unchanged) by their readings, and the one whose title // isn't a series, never read, stamped (StampScannedRev), so no later scan // tests it again. - wantRevs := []string{edited + "=5", vall + "=5", first + "=5", tufo + "=5", carl + "=5"} + wantRevs := []string{edited + "=6", vall + "=6", first + "=6", tufo + "=6", carl + "=6"} slices.Sort(wantRevs) if !slices.Equal(revs, wantRevs) { t.Errorf("revisions = %v, want %v", revs, wantRevs) @@ -275,8 +275,12 @@ func TestScanPartsTitle(t *testing.T) { silence(t, root, fmt.Sprintf("%s/%02d.mp3", nova, i+1), 1, "album=Portal to Nova Roma", "title=Portal to Nova Roma: Paris (Part "+part+")", "artist=Pat Writer") silence(t, root, fmt.Sprintf("%s/%02d.mp3", athens, i+1), 1, "album=Portal to Nova Roma", "title=Portal to Nova Roma: Athens - Part "+part, "artist=Pat Writer") } - // Each file's title only its chapter past the album: the album, which a - // series tag naming it then gives way to the folder (TitleNotSeries). + // Different chapter titles, with and without the series as a prefix or tag. + const dragon, essays = "Robert Jordan/The Dragon Reborn", "Francis Bacon/Essays" + for i, ch := range []string{"A Beginning", "An Ending"} { + silence(t, root, fmt.Sprintf("%s/%02d.mp3", dragon, i+1), 1, "album="+wot, "title="+ch) + silence(t, root, fmt.Sprintf("%s/%02d.mp3", essays, i+1), 1, "title="+ch) + } const eye, eyeSeries = "Robert Jordan/The Eye of the World", "Robert Jordan 2/The Eye of the World" for i, ch := range []string{"Ravens", "An Empty Road", "The Peddler"} { silence(t, root, fmt.Sprintf("%s/%02d.mp3", eye, i+1), 1, "album="+wot, "title="+wot+" - "+ch, "artist=Robert Jordan") @@ -289,7 +293,7 @@ func TestScanPartsTitle(t *testing.T) { } want := map[string]string{ parts: album, single: "Portal to Nova Roma: Paris", boxed: boxTitle, shared: sharedTitle, - hunt: "The Great Hunt", nova: "Paris", athens: "Athens", eye: wot, eyeSeries: "The Eye of the World", + hunt: "The Great Hunt", nova: "Paris", athens: "Athens", eye: "The Eye of the World", eyeSeries: "The Eye of the World", dragon: "The Dragon Reborn", essays: "Essays", } check := func(when string) { t.Helper() @@ -312,10 +316,22 @@ func TestScanPartsTitle(t *testing.T) { if _, err := db.ExecContext(ctx, `UPDATE books SET scanned = json_set(scanned, '$."@rev"', '4') WHERE rel_path IN (?, ?)`, single, shared); err != nil { t.Fatal(err) } + // Revision 5 kept the series album or the first file's tag. A revision 5 + // book already titled exactly like its folder can just take the stamp. + for rel, old := range map[string]string{eye: wot, dragon: wot, essays: "A Beginning", eyeSeries: "The Eye of the World"} { + if _, err := db.ExecContext(ctx, `UPDATE books SET scanned = json_set(scanned, '$.title', ?, '$."@rev"', '5'), title = ? WHERE rel_path = ?`, old, old, rel); err != nil { + t.Fatal(err) + } + } + sigs, err := cat.Signatures(ctx, lib.ID) if err != nil { t.Fatal(err) } + if !sigs[eye].NamesCheck || !sigs[dragon].NamesCheck || !sigs[essays].NamesCheck || !sigs[eyeSeries].RevStamp { + t.Fatalf("revision 5 backfill: wanted three title reads and a stamp for the matching folder") + } + if !sigs[parts].NamesCheck || !sigs[shared].NamesCheck || sigs[single].NamesCheck || !sigs[single].RevStamp { t.Fatalf("signatures: several files %+v and %+v, one file %+v; want the first two read, the other stamped", sigs[parts], sigs[shared], sigs[single]) @@ -333,7 +349,7 @@ func TestScanPartsTitle(t *testing.T) { check("after the backfill") var stale int if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM books - WHERE json_extract(scanned, '$."@rev"') IS NOT '5'`).Scan(&stale); err != nil || stale != 0 { + WHERE json_extract(scanned, '$."@rev"') IS NOT '6'`).Scan(&stale); err != nil || stale != 0 { t.Fatalf("snapshots before today's revision after the backfill = %d (err %v), want 0", stale, err) } @@ -369,8 +385,8 @@ func TestScanPartsTitle(t *testing.T) { t.Fatal(err) } check("last file readable again") - if got := rev(); got != "5" { - t.Fatalf("revision once the last file is read = %q, want 5", got) + if got := rev(); got != "6" { + t.Fatalf("revision once the last file is read = %q, want 6", got) } } @@ -429,7 +445,7 @@ func TestScanNamesCheckWaitsForRead(t *testing.T) { if _, err := s.Scan(ctx, *lib); err != nil { t.Fatal(err) } - reading("readable again", "From The Ashes", "5") + reading("readable again", "From The Ashes", "6") } // A leaf named "Author; Series; Book NN[; Title]" states the book's series and @@ -524,7 +540,7 @@ func TestScanLeafStatesSeries(t *testing.T) { check("after the backfill") var stale int if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM books - WHERE json_extract(scanned, '$."@rev"') IS NOT '5'`).Scan(&stale); err != nil || stale != 0 { + WHERE json_extract(scanned, '$."@rev"') IS NOT '6'`).Scan(&stale); err != nil || stale != 0 { t.Fatalf("snapshots before today's revision after the backfill = %d (err %v), want 0", stale, err) } sigs, err := cat.Signatures(ctx, lib.ID) @@ -613,7 +629,7 @@ func TestScanTagReadingRevision(t *testing.T) { } var stale int if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM books - WHERE json_extract(scanned, '$."@rev"') IS NOT '5'`).Scan(&stale); err != nil || stale != 0 { + WHERE json_extract(scanned, '$."@rev"') IS NOT '6'`).Scan(&stale); err != nil || stale != 0 { t.Fatalf("snapshots before today's revision after the backfill = %d (err %v), want 0", stale, err) } if sigs, err = cat.Signatures(ctx, lib.ID); err != nil { @@ -625,3 +641,81 @@ func TestScanTagReadingRevision(t *testing.T) { } } } + +func TestScanLeafNamesRevisionSix(t *testing.T) { + t.Parallel() + ctx := t.Context() + db := storetest.Open(t) + cat := catalog.New(db, time.Now) + root := t.TempDir() + const ( + leaf = "Bea Writer; The Crossing; Books 01-03; Homecoming" + same = "Shelf/Bea Writer; The Crossing; Book 01-03; The Ferryman" + other = "Shelf/Bea Writer; The Crossing; Book 01-03; Far Bank" + disc = "Bea Writer/Bea Writer; The Crossing; Book 04; Low Water/CD1" + plain = "Plain Name.mp3" + ) + silence(t, root, leaf+"/01.mp3", 1) + silence(t, root, same+"/01.mp3", 1, "series=THE CROSSING") + silence(t, root, other+"/01.mp3", 1, "series=River Stories") + silence(t, root, disc+"/01.mp3", 1) + silence(t, root, plain, 1) + lib, err := cat.CreateLibrary(ctx, catalog.Library{Name: "L", Root: root}) + if err != nil { + t.Fatal(err) + } + s := NewScanner(cat, lookFFprobe(t), slog.Default()) + type names struct { + title, author, series string + start, end float64 + } + want := map[string]names{ + leaf: {"Homecoming", "Bea Writer", "The Crossing", 1, 3}, + same: {"The Ferryman", "Shelf", "THE CROSSING", 1, 3}, + other: {"Far Bank", "Shelf", "River Stories", 0, 0}, + disc: {"Low Water", "Bea Writer", "The Crossing", 4, 0}, + plain: {"Plain Name", "", "", 0, 0}, + } + scan := func() { + t.Helper() + if _, err := s.Scan(ctx, *lib); err != nil { + t.Fatal(err) + } + for path, w := range want { + b, err := cat.GetBookByPath(ctx, lib.ID, path) + if err != nil { + t.Fatal(err) + } + if got := (names{b.Title, b.Author, b.Series, b.SeriesIndex, b.SeriesIndexEnd}); got != w { + t.Errorf("%s: got %+v, want %+v", path, got, w) + } + } + } + scan() + // Seed the revision 5 readings. The disc had just one file, so only + // recognizing its parent as a leaf can schedule its reread. + for path, old := range map[string]names{ + leaf: {leaf, "", "", 0, 0}, + same: {filepath.Base(same), "Shelf", "THE CROSSING", 1, 3}, + other: {filepath.Base(other), "Shelf", "River Stories", 1, 3}, + disc: {"CD1", "Bea Writer", "Bea Writer; The Crossing; Book 04; Low Water", 0, 0}, + } { + if _, err := db.ExecContext(ctx, `UPDATE books SET scanned = json_set(scanned, '$."@rev"', '5', + '$.title', ?, '$.series', ?, '$.series_index', ?, '$.author', ?), + title = ?, series = ?, series_index = ?, series_index_end = ?, author = ? WHERE rel_path = ?`, + old.title, old.series, catalog.FormatSeriesRange(old.start, old.end), old.author, + old.title, old.series, old.start, old.end, old.author, path); err != nil { + t.Fatal(err) + } + } + scan() + sigs, err := cat.Signatures(ctx, lib.ID) + if err != nil { + t.Fatal(err) + } + for path, sig := range sigs { + if sig.NamesCheck || sig.RevStamp { + t.Errorf("%s still needs a backfill", path) + } + } +} diff --git a/internal/library/scanner.go b/internal/library/scanner.go index d2114d460..187acd691 100644 --- a/internal/library/scanner.go +++ b/internal/library/scanner.go @@ -27,6 +27,7 @@ import ( "github.com/kodestar/audiosilo-server/internal/metadata" "github.com/kodestar/audiosilo-server/internal/mounts" "github.com/kodestar/audiosilo-server/internal/pool" + "github.com/kodestar/audiosilo-server/pkg/match" ) // Scanner walks library roots and keeps the catalog index up to date. The @@ -1051,17 +1052,10 @@ func (l *runLog) finish() []catalog.RunEvent { // pathFlushEvery is how many path readings a scan gathers before writing them. const pathFlushEvery = 500 -// readNames is book b's title, author and series: the path's reading -// (metadata.DeriveFromPath, the series and position a leaf named "Author; -// Series; Book NN[; Title]" states included) as the baseline, then md's tags, -// which are authoritative when present (an unreadable file's md carries none; -// nil reads the same), except a book of several files' first title tag that -// names that file (metadata.PartsTitle: the album instead, unless the book's -// folder or last, its last file's tags, nil for unread, says the tag is the -// book's, or the two tags share a name past the album), and an album tag that -// only names the book's series, which gives way to the book's own title -// (metadata.TitleNotSeries), and md's narrator. So the leaf's series fills -// only a series the tags leave out. +// readNames takes the path as its baseline and overlays the primary file's +// tags. A leaf's position belongs to its series. PartsTitle uses the last +// file's tags to tell chapter titles from book titles, and TitleNotSeries +// resolves albums that name a known series. func readNames(b *catalog.Book, md, last *metadata.Metadata) *metadata.Metadata { n := metadata.DeriveFromPath(b.RelPath, b.IsFolder) if md == nil { @@ -1076,6 +1070,9 @@ func readNames(b *catalog.Book, md, last *metadata.Metadata) *metadata.Metadata n.Author = md.Author } if strings.TrimSpace(md.Series) != "" { + if md.SeriesIndex == 0 && n.SeriesIndex != 0 && !match.SameSeries(n.Series, md.Series) && metadata.PathLeafSeries(b.RelPath, b.IsFolder) { + n.SeriesIndex, n.SeriesIndexEnd = 0, 0 + } n.Series = md.Series } if md.SeriesIndex != 0 { diff --git a/internal/matchrun/offered_test.go b/internal/matchrun/offered_test.go index 730486ebc..e713e6ab4 100644 --- a/internal/matchrun/offered_test.go +++ b/internal/matchrun/offered_test.go @@ -234,3 +234,65 @@ func TestRefreshApplyLeavesOutNoOps(t *testing.T) { } } } + +// An admin who reverts a community title keeps the restored value on the next +// fill. A fresh proposal can still fill other fields on the book. +func TestFillRespectsRevertedTitle(t *testing.T) { + t.Parallel() + e := newEnv(t) + ctx := t.Context() + const path, title = "A/Martian", "The Martian (Unabridged)" + e.book(t, path, title, "B0UK000001", nil) + hit := cand("the-martian", 100, "") + hit.Description = "" + e.matcher.byASIN["B0UK000001"] = []meta.MatchCandidate{hit} + fill := func() { + t.Helper() + run := e.start(t, catalog.MatchModeRefresh, "uk") + if _, err := e.runner.Apply(ctx, ctx, run.ID, ApplyOptions{Scope: ScopeFill, UserID: e.admin}); err != nil { + t.Fatal(err) + } + e.runner.Wait() + } + fill() + if f := e.field(t, path, catalog.FieldTitle); f.Value != "The Martian" || f.Source != catalog.SourceCommunity { + t.Fatalf("first fill title = %+v", f) + } + revert := func() error { + return e.cat.EditBook(ctx, e.lib, path, catalog.BookEdit{Revert: []string{catalog.FieldTitle}, UserID: e.admin}) + } + if err := revert(); err != nil { + t.Fatal(err) + } + hit.Description = "New description" + e.matcher.byASIN["B0UK000001"] = []meta.MatchCandidate{hit} + fill() + if f := e.field(t, path, catalog.FieldTitle); f.Value != title || f.Source != catalog.SourceEdited || !f.Locked { + t.Errorf("title after revert and fill = %+v", f) + } + if f := e.field(t, path, catalog.FieldDescription); f.Value != hit.Description { + t.Errorf("description after second fill = %+v", f) + } + + // A fill that already planned the tidy must respect a revert committed + // between its last read and the write transaction too. + if err := e.cat.EditBook(ctx, e.lib, path, catalog.BookEdit{Set: map[string]string{ + catalog.FieldTitle: title + " Audiobook", + }, Source: catalog.SourceCommunity}); err != nil { + t.Fatal(err) + } + reverted := make(chan error, 1) + e.runner.beforeEdit = func(*catalog.MatchRunItem) { reverted <- revert() } + fill() + select { + case err := <-reverted: + if err != nil { + t.Fatal(err) + } + default: + t.Fatal("expected a fill that planned a title write") + } + if f := e.field(t, path, catalog.FieldTitle); f.Value != title || f.Source != catalog.SourceEdited { + t.Errorf("fill racing the revert wrote %+v", f) + } +} diff --git a/internal/matchrun/runner.go b/internal/matchrun/runner.go index 8d6046f05..727afd865 100644 --- a/internal/matchrun/runner.go +++ b/internal/matchrun/runner.go @@ -836,7 +836,8 @@ func (r *Runner) applyItem(ctx context.Context, run *catalog.MatchRun, it *catal } edits := len(w.Set) > 0 || len(w.Revert) > 0 || w.Anchor != nil if edits { - edit := catalog.BookEdit{Set: w.Set, Revert: w.Revert, Source: catalog.SourceCommunity, UserID: o.UserID} + edit := catalog.BookEdit{Set: w.Set, Revert: w.Revert, Source: catalog.SourceCommunity, UserID: o.UserID, + KeepEditedTitle: o.Scope == ScopeFill} if w.Anchor != nil { how := catalog.MatchHowAccepted if it.Outcome == catalog.OutcomeAuto { diff --git a/internal/meta/prefill.go b/internal/meta/prefill.go index 251bfc2b2..dc2a82050 100644 --- a/internal/meta/prefill.go +++ b/internal/meta/prefill.go @@ -1,7 +1,6 @@ package meta import ( - "strconv" "strings" "github.com/kodestar/audiosilo-server/internal/metadata" @@ -25,12 +24,7 @@ import ( // the author, cleaned of series and numbering (match.CleanTitle), is the // path's title ("Bernard Cornwell" by "Sharpe's Eagle (Sharpe 08)"); // - a junk title ("Track 01", "03": metadata.IsGenericTitle; "Unknown", -// "Untitled") or a junk author ("Unknown", "Various Artists"), each alone; -// - a title that is the book's own leaf named "Author; Series; Book NN[; -// Title]" (metadata.LeafSeries: an untagged book's, which the scan titles -// by its leaf), which the path reads as its title part, else its series -// and position ("Dark Road 1-5"); a tag that only looks like one, beside -// a leaf named otherwise, names its book and stays. +// "Untitled") or a junk author ("Unknown", "Various Artists"), each alone. // // A fact the path doesn't give keeps the tag's value (for swapped tags, the // other tag's). @@ -38,17 +32,8 @@ func SearchPrefill(title, author, series, relPath string, isFolder bool) string title, author = strings.TrimSpace(title), strings.TrimSpace(author) p := metadata.FromPathLayout(relPath, isFolder) pathTitle := strings.TrimSpace(p.Title) - if pathTitle == "" && p.Series != "" { - // "Brandon Sanderson/Stormlight Archive/03": the series and its volume; a - // leaf named "Author; Series; Book NN" with no title part, the series and - // its position, a range ("Dark Road 1-5") or none ("Book XX"). - pathTitle = p.Series - if p.SeriesIndex > 0 { - pathTitle += " " + strconv.FormatFloat(p.SeriesIndex, 'f', -1, 64) - if metadata.ValidSeriesRange(p.SeriesIndex, p.SeriesIndexEnd) { - pathTitle += "-" + strconv.FormatFloat(p.SeriesIndexEnd, 'f', -1, 64) - } - } + if pathTitle == "" { + pathTitle = p.SeriesTitle() } // A tag that matches its own path fact is never swapped: "Dune/Dune" by Frank // Herbert has the title of its author folder because the folder is the book's. @@ -62,7 +47,7 @@ func SearchPrefill(title, author, series, relPath string, isFolder bool) string // Eagle" folder is Sharpe's Eagle by Bernard Cornwell. title, author = author, title } - if pathTitle != "" && (swapped || junkTitle(title) || leafTitle(title, relPath, isFolder)) { + if pathTitle != "" && (swapped || junkTitle(title)) { title = pathTitle } if p.Author != "" && (swapped || junkAuthor(author)) { @@ -80,18 +65,6 @@ func junkTitle(t string) bool { return metadata.IsGenericTitle(t) } -// leafTitle reports whether a title is the book's own leaf, named "Author; -// Series; Book NN[; Title]" (metadata.LeafSeries), as the scan titles an -// untagged book in one: the rule the layout's title follows (catalog's -// readScanned), so a tag that is only shaped like one is never replaced. -func leafTitle(title, relPath string, isFolder bool) bool { - leaf := metadata.ReadPathLayout(relPath, isFolder).Title - if _, ok := metadata.LeafSeries(leaf); !ok { - return false - } - return match.Fold(title) == match.Fold(leaf) -} - // junkAuthor reports whether an author tag names nobody. func junkAuthor(a string) bool { switch strings.ToLower(a) { diff --git a/internal/meta/prefill_test.go b/internal/meta/prefill_test.go index aac33118f..4fb7b7d56 100644 --- a/internal/meta/prefill_test.go +++ b/internal/meta/prefill_test.go @@ -44,16 +44,6 @@ func TestSearchPrefill(t *testing.T) { "Bruno Miller/Bruno Miller; Dark Road; Book 01-05", true, "Dark Road 1-5 Bruno Miller"}, {"a leaf with no position", "Track 01", "Isaac Asimov", "", "Isaac Asimov/Isaac Asimov; Robot Dreams; Book XX", true, "Robot Dreams Isaac Asimov"}, - // An untagged book in such a leaf: the scan titles it by the whole leaf, - // which the path reads as its title part, else its series and position. - {"an untagged leaf's range", "Bruno Miller; Dark Road; Book 01-05", "Bruno Miller", "", - "Bruno Miller/Bruno Miller; Dark Road; Book 01-05", true, "Dark Road 1-5 Bruno Miller"}, - {"an untagged leaf's position", "Bruno Miller; Dark Road; Book 03", "Bruno Miller", "", - "Bruno Miller/Bruno Miller; Dark Road; Book 03", true, "Dark Road 3 Bruno Miller"}, - {"an untagged leaf's title part", "Mark Tufo; Indian Hill; Book 04; From The Ashes", "Mark Tufo", "", - "Mark Tufo/Mark Tufo; Indian Hill; Book 04; From The Ashes", true, "From The Ashes Mark Tufo"}, - {"an untagged leaf file's title part", "Mark Tufo; Indian Hill; Book 04; From The Ashes", "", "", - "Mark Tufo/Mark Tufo; Indian Hill; Book 04; From The Ashes.mp3", false, "From The Ashes Mark Tufo"}, {"a tagged title in a leaf stays", "From The Ashes (Unabridged)", "Mark Tufo", "", "Mark Tufo/Mark Tufo; Indian Hill; Book 04; From The Ashes", true, "From The Ashes (Unabridged) Mark Tufo"}, {"a tagged title shaped like a leaf beside another leaf stays", "Mark Tufo; Indian Hill; Book 04; From The Ashes", diff --git a/internal/metadata/layout.go b/internal/metadata/layout.go index 6089f4626..c8c048628 100644 --- a/internal/metadata/layout.go +++ b/internal/metadata/layout.go @@ -1,6 +1,7 @@ package metadata import ( + "cmp" "strconv" "strings" ) @@ -80,6 +81,7 @@ func FromPathLayout(relPath string, isFolder bool) *Metadata { l := ReadPathLayout(relPath, isFolder) m := &Metadata{Author: strings.TrimSpace(l.Author)} if leaf, ok := LeafSeries(l.Title); ok { + m.Author = cmp.Or(m.Author, leaf.Author) m.Title, m.Series, m.SeriesIndex, m.SeriesIndexEnd = leaf.Title, leaf.Series, leaf.Position, leaf.PositionEnd return m } @@ -95,6 +97,19 @@ func FromPathLayout(relPath string, isFolder bool) *Metadata { return m } +// SeriesTitle names a book by its series and position when the path supplies +// no title of its own ("Dark Road 1-5"). +func (m *Metadata) SeriesTitle() string { + if m.Series == "" || m.SeriesIndex <= 0 { + return m.Series + } + title := m.Series + " " + strconv.FormatFloat(m.SeriesIndex, 'f', -1, 64) + if ValidSeriesRange(m.SeriesIndex, m.SeriesIndexEnd) { + title += "-" + strconv.FormatFloat(m.SeriesIndexEnd, 'f', -1, 64) + } + return title +} + // plainVolume reads a part label that is a plain number ("03") as the volume // it names ("3"); a label with a disc word ("CD1", "Part 3"), or a zero, is // not one and gives "". diff --git a/internal/metadata/layout_test.go b/internal/metadata/layout_test.go index ef99d8c7e..d6256711b 100644 --- a/internal/metadata/layout_test.go +++ b/internal/metadata/layout_test.go @@ -138,6 +138,10 @@ func TestFromPathLayout(t *testing.T) { {path: "Track 01.mp3", want: Metadata{}}, // A leaf named "Author; Series; Book NN[; Title]" (LeafSeries) states its // series, position (a range, or none) and title part, file or folder. + { + path: "Bea Writer; The Crossing; Books 01-03; Homecoming/Disc 2", isFolder: true, + want: Metadata{Author: "Bea Writer", Series: "The Crossing", SeriesIndex: 1, SeriesIndexEnd: 3, Title: "Homecoming"}, + }, { path: "Mark Tufo/Mark Tufo; Indian Hill; Book 04; From The Ashes", isFolder: true, want: Metadata{Author: "Mark Tufo", Series: "Indian Hill", SeriesIndex: 4, Title: "From The Ashes"}, diff --git a/internal/metadata/metadata.go b/internal/metadata/metadata.go index d5f09cf96..160995bd5 100644 --- a/internal/metadata/metadata.go +++ b/internal/metadata/metadata.go @@ -775,34 +775,50 @@ func bookTitle(album, title string) string { return a } -// PartsTitle is the title of a book of several files whose tags gave m (its -// first file's) and maybe its last file's, other (nil for unread; the scan -// reads it only when PartNamed says the title turns on it). A title tag that -// extends the album may name its file, a chapter rather than the book -// (server#272), so where PartNamed holds the title is, in order: the tag, when -// other carries the same one; the name the two share past the album -// (partsName), unless the folder (pathTitle) names the album; the tag without -// its bracketed part markers, when that is all they differ by; else the album. -// With other unread the folder alone says, so the album. An album that names -// only the book's series then gives way as TitleNotSeries says. +// PartsTitle chooses the book title from the first and last files. Matching +// title tags, or a book name shared past the album, can name the book. When +// the tags name different chapters, an album corroborated by the folder still +// names the book. Without that evidence an unrelated album can name a series. func (m *Metadata) PartsTitle(pathTitle string, other *Metadata) string { + if m.AlbumTag == "" && m.TitleTag != "" && IsGenericTitle(m.TitleTag) && pathTitle != "" { + return pathTitle + } if !m.PartNamed(pathTitle) || (other != nil && strings.EqualFold(m.TitleTag, other.TitleTag)) { return m.Title } + if m.AlbumTag == "" { + return pathTitle + } if other == nil { return m.AlbumTag } - if !sameName(m.AlbumTag, pathTitle) { - if name := partsName(m.AlbumTag, m.TitleTag, other.TitleTag); name != "" { - return name + if m.Title != m.AlbumTag { + if !sameName(m.AlbumTag, pathTitle) { + if name := partsName(m.AlbumTag, m.TitleTag, other.TitleTag); name != "" { + return name + } + } + if canonTag(m.TitleTag) == canonTag(other.TitleTag) { + return cleanTag(m.TitleTag) } } - if canonTag(m.TitleTag) == canonTag(other.TitleTag) { - return cleanTag(m.TitleTag) + if other.TitleTag != "" && !IsAudio(other.TitleTag) && (other.AlbumTag == "" || sameName(m.AlbumTag, other.AlbumTag)) && m.folderOverAlbum(pathTitle) { + return pathTitle } return m.AlbumTag } +// folderOverAlbum reports whether an unconfirmed album and the folder appear +// to name different works. A longer album such as "Frankenstein; or, The +// Modern Prometheus" still names the book in "Frankenstein". A known series +// is handled separately by TitleNotSeries. A filename tag like "Part 01.mp3" +// supplies no chapter name to weigh against the album. +func (m *Metadata) folderOverAlbum(pathTitle string) bool { + return m.Series == "" && !IsAudio(m.TitleTag) && !IsGenericTitle(cleanTag(pathTitle)) && !volumeMarker(pathTitle) && + !strings.EqualFold(pathTitle, "Folder") && + !sameName(pathTitle, m.AlbumTag) && !match.TitlesShareWord(pathTitle, m.AlbumTag) +} + // partsName is the name two title tags of one book's files (first, last) share // past its album: what each adds after the album and a separator (": ", " - "), // brackets left out, up to the separator where they part ("The Great Hunt" of @@ -853,14 +869,19 @@ func cutAlbum(title, album string) (string, bool) { // colon, or a spaced dash or bar ("Series: Book - Chapter"). var nameSep = regexp.MustCompile(`(?:\s*:|\s+[-–—|])\s+`) -// PartNamed reports whether m's title may name its file, not the book of -// several files it is the first of: a title tag bookTitle took over the album -// it extends, which doesn't name the book's folder (pathTitle) as PartsTitle -// reads it. Only then does the book's title turn on another file's tags, so -// only then is one worth reading. Nil reads as no tags. +// PartNamed reports whether another file's tags could change the choice of +// title. A tag confirmed by the book folder needs no second read. func (m *Metadata) PartNamed(pathTitle string) bool { - return m != nil && m.AlbumTag != "" && m.Title == m.TitleTag && m.TitleTag != m.AlbumTag && - !sameName(m.TitleTag, pathTitle) && !sameName(albumTail(m.AlbumTag, m.TitleTag), pathTitle) + if m == nil || m.TitleTag == "" { + return false + } + if m.AlbumTag == "" { + return pathTitle != m.TitleTag && !IsGenericTitle(m.TitleTag) + } + if m.Title == m.TitleTag && m.TitleTag != m.AlbumTag { + return !sameName(m.TitleTag, pathTitle) && !sameName(albumTail(m.AlbumTag, m.TitleTag), pathTitle) + } + return !sameName(m.TitleTag, m.AlbumTag) && m.folderOverAlbum(pathTitle) } // albumTail is what a title tag adds to the album when it extends it at a word @@ -1018,7 +1039,7 @@ func firstNonEmpty(vals ...string) string { // // Mark Tufo/Mark Tufo; Indian Hill; Book 04; From The Ashes (series Indian Hill, #4) // -// Its title stays the whole leaf; TitleNotSeries reads the title part. +// The title part names the book. Without one, the series and position identify it. func DeriveFromPath(relPath string, isFolder bool) *Metadata { m := &Metadata{} segments := pathSegments(relPath, isFolder) @@ -1033,6 +1054,13 @@ func DeriveFromPath(relPath string, isFolder bool) *Metadata { } if l, ok := LeafSeries(name); ok { m.Series, m.SeriesIndex, m.SeriesIndexEnd = l.Series, l.Position, l.PositionEnd + if m.Author == "" { + m.Author = l.Author + } + m.Title = l.Title + if m.Title == "" { + m.Title = m.SeriesTitle() + } } return m } @@ -1045,6 +1073,13 @@ func pathSegments(relPath string, isFolder bool) []string { last := segs[len(segs)-1] segs[len(segs)-1] = strings.TrimSuffix(last, filepath.Ext(last)) } + // An individually indexed disc in a structured book folder belongs to + // that leaf. Use the same book segment for all path and backfill rules. + if isFolder && len(segs) > 1 && strings.Contains(segs[len(segs)-2], ";") && IsDiscFolder(segs[len(segs)-1]) { + if _, ok := LeafSeries(segs[len(segs)-2]); ok { + segs = segs[:len(segs)-1] + } + } return segs } diff --git a/internal/metadata/metadata_test.go b/internal/metadata/metadata_test.go index 618edf348..b1589b45d 100644 --- a/internal/metadata/metadata_test.go +++ b/internal/metadata/metadata_test.go @@ -78,52 +78,52 @@ func TestDeriveFromPath(t *testing.T) { want: Metadata{Title: "Unsouled", SeriesIndex: 1}, }, // A leaf named "Author; Series; Book NN[; Title]" states its series and - // position (LeafSeries), the shapes of the LibraForge benchmark; its - // title stays the whole leaf (TitleNotSeries reads the title part). + // position (LeafSeries), the shapes of the LibraForge benchmark; its title + // part or the numbered series identifies it. { name: "leaf series and position", rel: "Mark Tufo/Mark Tufo; Indian Hill; Book 04; From The Ashes", isFolder: true, - want: Metadata{Title: "Mark Tufo; Indian Hill; Book 04; From The Ashes", Author: "Mark Tufo", + want: Metadata{Title: "From The Ashes", Author: "Mark Tufo", Series: "Indian Hill", SeriesIndex: 4}, }, { name: "leaf file without a title part", rel: "A.R. Wise/A.R. Wise; Deadlocked; Book 01.m4b", - want: Metadata{Title: "A.R. Wise; Deadlocked; Book 01", Author: "A.R. Wise", Series: "Deadlocked", SeriesIndex: 1}, + want: Metadata{Title: "Deadlocked 1", Author: "A.R. Wise", Series: "Deadlocked", SeriesIndex: 1}, }, { name: "leaf range", rel: "Bruno Miller/Bruno Miller; Dark Road; Book 01-05", isFolder: true, - want: Metadata{Title: "Bruno Miller; Dark Road; Book 01-05", Author: "Bruno Miller", Series: "Dark Road", + want: Metadata{Title: "Dark Road 1-5", Author: "Bruno Miller", Series: "Dark Road", SeriesIndex: 1, SeriesIndexEnd: 5}, }, { name: "leaf range with a title part", rel: "Tao Wong/Tao Wong; System Apocalypse; Book 10-12; Omnibus Volume 4", isFolder: true, - want: Metadata{Title: "Tao Wong; System Apocalypse; Book 10-12; Omnibus Volume 4", Author: "Tao Wong", + want: Metadata{Title: "Omnibus Volume 4", Author: "Tao Wong", Series: "System Apocalypse", SeriesIndex: 10, SeriesIndexEnd: 12}, }, { name: "leaf Book XX states no position", rel: "B.V. Larson/B.V. Larson; Star Force; Book XX; Army of One", isFolder: true, - want: Metadata{Title: "B.V. Larson; Star Force; Book XX; Army of One", Author: "B.V. Larson", Series: "Star Force"}, + want: Metadata{Title: "Army of One", Author: "B.V. Larson", Series: "Star Force"}, }, { name: "leaf Book 00 states no position", rel: "Larry Correia/Larry Correia; Grimnoir Chronicles; Book 00; Tokyo Raider", isFolder: true, - want: Metadata{Title: "Larry Correia; Grimnoir Chronicles; Book 00; Tokyo Raider", Author: "Larry Correia", + want: Metadata{Title: "Tokyo Raider", Author: "Larry Correia", Series: "Grimnoir Chronicles"}, }, { name: "a leaf's series over the folder's", rel: "Mark Tufo/Zombies/Mark Tufo; Zombie Fallout; Book 02", isFolder: true, - want: Metadata{Title: "Mark Tufo; Zombie Fallout; Book 02", Author: "Mark Tufo", Series: "Zombie Fallout", + want: Metadata{Title: "Zombie Fallout 2", Author: "Mark Tufo", Series: "Zombie Fallout", SeriesIndex: 2}, }, } @@ -364,7 +364,13 @@ func TestPartsTitle(t *testing.T) { {"underscore tail gives way", "The Diary of a Nobody", "The Diary of a Nobody_Ch00", "The Diary of a Nobody", unread, "The Diary of a Nobody"}, {"another file without a title tag", "The Odyssey", "The Odyssey: Book 01", "The Odyssey", "", "The Odyssey"}, {"album already chosen", "Pride and Prejudice", "Chapters 21-22", "Pride and Prejudice", "Chapters 21-22", "Pride and Prejudice"}, - {"no album", "", "The Essays of Francis Bacon 01", "Essays", unread, "The Essays of Francis Bacon 01"}, + {"no album", "", "The Essays of Francis Bacon 01", "Essays", unread, "Essays"}, + {"no album, generic first tag", "", "Track 1", "The Eye of the World", unread, "The Eye of the World"}, + {"no album, named chapters", "", "Ravens", "The Eye of the World", "The Peddler", "The Eye of the World"}, + {"no album, shared title", "", "The Quiet Harbour", "Files", "The Quiet Harbour", "The Quiet Harbour"}, + {"unrelated album, chapter names", "The Wheel of Time", "Ravens Rising", "The Dragon Reborn", "The Peddler", "The Dragon Reborn"}, + {"filename tags keep the album", "Real Title", "Part 01.mp3", "Odd Name", "Part 02.mp3", "Real Title"}, + {"album corroborated by folder", "The Odyssey", "The Voyage", "Odyssey", "Homecoming", "The Odyssey"}, {"no title tag", "Main Street", "", "Main Street", unread, "Main Street"}, // A box set's album beside each book's own title: the tail names the folder. {"tail names the folder", "The Expanse Box Set", "The Expanse Box Set: Leviathan Wakes", "Leviathan Wakes", unread, "The Expanse Box Set: Leviathan Wakes"}, @@ -387,10 +393,8 @@ func TestPartsTitle(t *testing.T) { {"shared name of two parts", "Cosmere", "Cosmere: Mistborn - The Final Empire - Chapter 1", "Book 1", "Cosmere: Mistborn - The Final Empire - Chapter 38", "Mistborn - The Final Empire"}, {"shared subtitle, generic folder", "Sapiens", "Sapiens: A Brief History (Part 1)", "Book 2", "Sapiens: A Brief History (Part 2)", "A Brief History"}, // Tags that share nothing past the album but a marker: each file's own - // chapter, so the album. With the series as the album and no series tag - // that is the series' name ("The Eye of the World"): the files name no - // book, and TitleNotSeries takes the folder only once a tag says series. - {"only chapters past the album", "The Wheel of Time", "The Wheel of Time - Ravens", "The Eye of the World", "The Wheel of Time - The Peddler", "The Wheel of Time"}, + // chapter. An unrelated album yields to the book folder. + {"only chapters past the album", "The Wheel of Time", "The Wheel of Time - Ravens", "The Eye of the World", "The Wheel of Time - The Peddler", "The Eye of the World"}, {"only a part marker shared", "Dune", "Dune: Part 1 - Chapter 1", "Book 1", "Dune: Part 1 - Chapter 9", "Dune"}, {"only a volume marker shared", "The Expanse", "The Expanse: Book 1 - Chapter 01", "Folder", "The Expanse: Book 1 - Chapter 30", "The Expanse"}, {"underscore chapters", "The Diary of a Nobody", "The Diary of a Nobody_Ch00", "Diary of a Nobody", "The Diary of a Nobody_Ch24", "The Diary of a Nobody"}, @@ -407,9 +411,21 @@ func TestPartsTitle(t *testing.T) { if got := m.PartsTitle(tc.path, other); got != tc.want { t.Errorf("%s: PartsTitle(%q, %q, %q, %q) = %q, want %q", tc.name, tc.album, tc.title, tc.path, tc.other, got, tc.want) } - // PartNamed: only a title that turns on the other file asks for it. - if turns := m.PartsTitle(tc.path, nil) != m.PartsTitle(tc.path, &Metadata{TitleTag: m.TitleTag}); turns != m.PartNamed(tc.path) { - t.Errorf("%s: PartNamed = %v, want %v", tc.name, m.PartNamed(tc.path), turns) + } + for _, tc := range []struct { + album, title, path string + want bool + }{ + {"", "Prologue", "The Dragon Reborn", true}, + {"The Wheel of Time", "Chapter 1", "The Dragon Reborn", true}, + {"The Odyssey", "Chapter 1", "Odyssey", false}, + {"The Expanse", "The Expanse: Leviathan Wakes", "Leviathan Wakes", false}, + {"", "The Dragon Reborn", "The Dragon Reborn", false}, + } { + var m Metadata + m.setTitle(tc.album, tc.title) + if got := m.PartNamed(tc.path); got != tc.want { + t.Errorf("PartNamed(%q, %q in %q) = %v, want %v", tc.album, tc.title, tc.path, got, tc.want) } } if (*Metadata)(nil).PartNamed("Any") { diff --git a/internal/metadata/seriestitle.go b/internal/metadata/seriestitle.go index b854b173a..ad585984d 100644 --- a/internal/metadata/seriestitle.go +++ b/internal/metadata/seriestitle.go @@ -170,6 +170,8 @@ func (p seriesPath) leafNames(title string) bool { // Leaf is what a book's leaf named "Author; Series; Book NN[; Title]" states // (LeafSeries). type Leaf struct { + // Author is the first part, used when there is no author folder. + Author string // Series is the series part ("Indian Hill"). Series string // Title is the title part, "" with none. @@ -202,7 +204,7 @@ func LeafSeries(leaf string) (Leaf, bool) { if parts[0] == "" || parts[1] == "" || m == nil { return Leaf{}, false } - l := Leaf{Series: parts[1], Title: strings.Join(parts[3:], "; ")} + l := Leaf{Author: parts[0], Series: parts[1], Title: strings.Join(parts[3:], "; ")} if start, end, ok := ParseSeriesRange(m[1]); ok { l.Position, l.PositionEnd = start, end } else { @@ -212,8 +214,11 @@ func LeafSeries(leaf string) (Leaf, bool) { } // PathLeafSeries reports whether a book's own leaf (its file's name without the -// extension, or its folder's) is one LeafSeries reads, as DeriveFromPath reads it. +// extension, its folder, or the parent of a disc folder) is one LeafSeries reads. func PathLeafSeries(relPath string, isFolder bool) bool { + if !strings.Contains(relPath, ";") { + return false + } segs := pathSegments(relPath, isFolder) _, ok := LeafSeries(segs[len(segs)-1]) return ok @@ -223,7 +228,7 @@ func PathLeafSeries(relPath string, isFolder bool) bool { // in submatch 1 and the number it leads with, if any, in submatch 2. A marker // is a number ("04", "01-05", "2.5") or the placeholder "XX" ("??"), never a // word, so "Oprah; Picks; Book Club" states no series. -var leafVolume = regexp.MustCompile(`^(?i:book)\s+((\d+(?:\.\d+)?)\S*|(?i:x+)|\?+)$`) +var leafVolume = regexp.MustCompile(`^(?i:books?)\s+((\d+(?:\.\d+)?)\S*|(?i:x+)|\?+)$`) // volumeMarker reports whether a name is only a volume marker, "Book 10", // "Vol. 2", "C02", "#3" (splitSeriesIndex's prefixes and a number): no title. diff --git a/internal/metadata/seriestitle_test.go b/internal/metadata/seriestitle_test.go index 553c9bb51..8d235fac6 100644 --- a/internal/metadata/seriestitle_test.go +++ b/internal/metadata/seriestitle_test.go @@ -140,23 +140,23 @@ func TestLeafSeries(t *testing.T) { want Leaf ok bool }{ - {"Mark Tufo; Indian Hill; Book 04; From The Ashes", Leaf{"Indian Hill", "From The Ashes", 4, 0}, true}, - {"Alex Raizman; Dinosaur Dungeon; Book 01; Wrath", Leaf{"Dinosaur Dungeon", "Wrath", 1, 0}, true}, - {"A.R. Wise; Deadlocked; Book 01", Leaf{"Deadlocked", "", 1, 0}, true}, - {"Bruno Miller; Dark Road; Book 01-05", Leaf{"Dark Road", "", 1, 5}, true}, - {"Aaron Oster; The Rules; Book 01-03", Leaf{"The Rules", "", 1, 3}, true}, - {"Craig Robertson; Time Wars Last Forever; Book 03-04", Leaf{"Time Wars Last Forever", "", 3, 4}, true}, - {"Tao Wong; System Apocalypse; Book 10-12; Omnibus Volume 4", Leaf{"System Apocalypse", "Omnibus Volume 4", 10, 12}, true}, - {"Adrian J. Smith; The Extinction; Book 01-03; New Zealand", Leaf{"The Extinction", "New Zealand", 1, 3}, true}, - {"B.V. Larson; Star Force; Book XX; Army of One", Leaf{"Star Force", "Army of One", 0, 0}, true}, - {"Isaac Asimov; Robot Dreams; Book XX", Leaf{"Robot Dreams", "", 0, 0}, true}, - {"Christopher Ruocchio; Sun Eater; Book XX; The Lesser Devil 1.5", Leaf{"Sun Eater", "The Lesser Devil 1.5", 0, 0}, true}, - {"Larry Correia; Grimnoir Chronicles; Book 00; Tokyo Raider", Leaf{"Grimnoir Chronicles", "Tokyo Raider", 0, 0}, true}, - {"A. Writer; Series; Book 00", Leaf{"Series", "", 0, 0}, true}, - {"A. Writer; Series; Book 2.5; Title; With a Semicolon", Leaf{"Series", "Title; With a Semicolon", 2.5, 0}, true}, + {"Mark Tufo; Indian Hill; Book 04; From The Ashes", Leaf{"Mark Tufo", "Indian Hill", "From The Ashes", 4, 0}, true}, + {"Alex Raizman; Dinosaur Dungeon; Book 01; Wrath", Leaf{"Alex Raizman", "Dinosaur Dungeon", "Wrath", 1, 0}, true}, + {"A.R. Wise; Deadlocked; Book 01", Leaf{"A.R. Wise", "Deadlocked", "", 1, 0}, true}, + {"Bruno Miller; Dark Road; Book 01-05", Leaf{"Bruno Miller", "Dark Road", "", 1, 5}, true}, + {"Aaron Oster; The Rules; Book 01-03", Leaf{"Aaron Oster", "The Rules", "", 1, 3}, true}, + {"Craig Robertson; Time Wars Last Forever; Book 03-04", Leaf{"Craig Robertson", "Time Wars Last Forever", "", 3, 4}, true}, + {"Tao Wong; System Apocalypse; Book 10-12; Omnibus Volume 4", Leaf{"Tao Wong", "System Apocalypse", "Omnibus Volume 4", 10, 12}, true}, + {"Adrian J. Smith; The Extinction; Book 01-03; New Zealand", Leaf{"Adrian J. Smith", "The Extinction", "New Zealand", 1, 3}, true}, + {"B.V. Larson; Star Force; Book XX; Army of One", Leaf{"B.V. Larson", "Star Force", "Army of One", 0, 0}, true}, + {"Isaac Asimov; Robot Dreams; Book XX", Leaf{"Isaac Asimov", "Robot Dreams", "", 0, 0}, true}, + {"Christopher Ruocchio; Sun Eater; Book XX; The Lesser Devil 1.5", Leaf{"Christopher Ruocchio", "Sun Eater", "The Lesser Devil 1.5", 0, 0}, true}, + {"Larry Correia; Grimnoir Chronicles; Book 00; Tokyo Raider", Leaf{"Larry Correia", "Grimnoir Chronicles", "Tokyo Raider", 0, 0}, true}, + {"A. Writer; Series; Book 00", Leaf{"A. Writer", "Series", "", 0, 0}, true}, + {"A. Writer; Series; Book 2.5; Title; With a Semicolon", Leaf{"A. Writer", "Series", "Title; With a Semicolon", 2.5, 0}, true}, // Not a range a position may hold: the number it leads with, or none. - {"A. Writer; Series; Book 05-03", Leaf{"Series", "", 5, 0}, true}, - {"A. Writer; Series; Book 00-03", Leaf{"Series", "", 0, 0}, true}, + {"A. Writer; Series; Book 05-03", Leaf{"A. Writer", "Series", "", 5, 0}, true}, + {"A. Writer; Series; Book 00-03", Leaf{"A. Writer", "Series", "", 0, 0}, true}, {"Albert Camus; The Stranger", Leaf{}, false}, {"Amir Levine; Attached; The New Science of Adult Attachment", Leaf{}, false}, {"Codename; Freedom - Book 001 - Survive Week One", Leaf{}, false}, @@ -165,7 +165,7 @@ func TestLeafSeries(t *testing.T) { // A word after "Book" is no marker. {"Oprah; Picks; Book Club", Leaf{}, false}, {"A. Writer; Series; Book One; Title", Leaf{}, false}, - {"A. Writer; Series; Book ??", Leaf{"Series", "", 0, 0}, true}, + {"A. Writer; Series; Book ??", Leaf{"A. Writer", "Series", "", 0, 0}, true}, {"Plain Title", Leaf{}, false}, } for _, c := range cases { diff --git a/pkg/match/match.go b/pkg/match/match.go index e846ac391..6ae7ecc92 100644 --- a/pkg/match/match.go +++ b/pkg/match/match.go @@ -979,6 +979,24 @@ var titleStopwords = map[string]bool{ "or": true, "nor": true, "from": true, } +// TitlesShareWord reports whether two titles have a word in common beyond +// articles and joining words. The scanner uses this to preserve an album +// whose title is a fuller spelling of the book folder's. +func TitlesShareWord(a, b string) bool { + words := func(s string) []string { + return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { + return !unicode.IsLetter(r) && !unicode.IsNumber(r) && !unicode.IsMark(r) + }) + } + bw := words(b) + for _, w := range words(a) { + if !titleStopwords[w] && slices.Contains(bw, w) { + return true + } + } + return false +} + // titleTokens reduces a title to its set of significant lowercase word tokens after // CleanTitle has removed the series name and fluff. func titleTokens(title, series string, o Options) []string { From b737d4d2ae59dbb492d15d7c1b1d399c8e65c734 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 19:03:37 +0000 Subject: [PATCH 02/16] Tidy the revision-6 title rules Drop the "Folder" special case from folderOverAlbum (only a test fixture used it), the duplicate ";" test before LeafSeries in pathSegments, and the whitespace-only clause in readScanned's numbered-title check. namesCheck answers a pre-revision-5 multi-file book before reading its path title, so a snapshot that is never stamped does not parse its path on every scan. Restore readNames' account of nil tags and the narrator, and say why TitlesShareWord keeps its own word split. Part of #272, #325. --- internal/catalog/overrides.go | 2 +- internal/catalog/pathreading.go | 5 ++++- internal/library/scanner.go | 11 +++++++---- internal/metadata/metadata.go | 13 ++++--------- internal/metadata/metadata_test.go | 2 +- internal/metadata/seriestitle.go | 3 ++- pkg/match/match.go | 4 +++- 7 files changed, 22 insertions(+), 18 deletions(-) diff --git a/internal/catalog/overrides.go b/internal/catalog/overrides.go index 1ec066356..37051abc7 100644 --- a/internal/catalog/overrides.go +++ b/internal/catalog/overrides.go @@ -647,7 +647,7 @@ func (l *bookLayers) readScanned() (scanned, baseline, layout bookFields) { } layout = pathFields(metadata.FromPathLayout(l.path, l.isFolder)) raw := metadata.ReadPathLayout(l.path, l.isFolder) - if number, title := metadata.SplitSeriesIndex(raw.Title); (number != 0 || title != raw.Title) && + if number, _ := metadata.SplitSeriesIndex(raw.Title); number != 0 && strings.EqualFold(strings.TrimSpace(l.scanned[FieldTitle]), raw.Title) { // The tag title IS the folder's name, number and all ("13 Reasons Why"): // the number is part of the title, not a volume the layout can split off. diff --git a/internal/catalog/pathreading.go b/internal/catalog/pathreading.go index 65e99b177..95a328e52 100644 --- a/internal/catalog/pathreading.go +++ b/internal/catalog/pathreading.go @@ -96,8 +96,11 @@ func namesCheck(rev int, rel string, isFolder, severalFiles bool, format, title, return true } if severalFiles { + if rev < revPartsTitle { + return true + } pathTitle := metadata.PathTitle(rel, isFolder) - return rev < revPartsTitle || (pathTitle != "" && title != pathTitle) + return pathTitle != "" && title != pathTitle } } return (rev < revTitleNotSeries && metadata.MaybeSeriesTitle(rel, isFolder, title, series)) || diff --git a/internal/library/scanner.go b/internal/library/scanner.go index 187acd691..0d29044bb 100644 --- a/internal/library/scanner.go +++ b/internal/library/scanner.go @@ -1052,10 +1052,13 @@ func (l *runLog) finish() []catalog.RunEvent { // pathFlushEvery is how many path readings a scan gathers before writing them. const pathFlushEvery = 500 -// readNames takes the path as its baseline and overlays the primary file's -// tags. A leaf's position belongs to its series. PartsTitle uses the last -// file's tags to tell chapter titles from book titles, and TitleNotSeries -// resolves albums that name a known series. +// readNames is book b's title, author and series: the path's reading +// (metadata.DeriveFromPath) as the baseline, then md's tags (nil, an unread +// file, keeps the path's), and md's narrator. A leaf's position goes only with +// its own series: a tag naming another series and no position clears it. +// PartsTitle uses the last file's tags (last, nil for unread) to tell chapter +// titles from book titles, and TitleNotSeries resolves albums that name a +// known series. func readNames(b *catalog.Book, md, last *metadata.Metadata) *metadata.Metadata { n := metadata.DeriveFromPath(b.RelPath, b.IsFolder) if md == nil { diff --git a/internal/metadata/metadata.go b/internal/metadata/metadata.go index 160995bd5..2e9ff5aa7 100644 --- a/internal/metadata/metadata.go +++ b/internal/metadata/metadata.go @@ -6,6 +6,7 @@ package metadata import ( + "cmp" "context" "errors" "log/slog" @@ -815,7 +816,6 @@ func (m *Metadata) PartsTitle(pathTitle string, other *Metadata) string { // supplies no chapter name to weigh against the album. func (m *Metadata) folderOverAlbum(pathTitle string) bool { return m.Series == "" && !IsAudio(m.TitleTag) && !IsGenericTitle(cleanTag(pathTitle)) && !volumeMarker(pathTitle) && - !strings.EqualFold(pathTitle, "Folder") && !sameName(pathTitle, m.AlbumTag) && !match.TitlesShareWord(pathTitle, m.AlbumTag) } @@ -1054,13 +1054,8 @@ func DeriveFromPath(relPath string, isFolder bool) *Metadata { } if l, ok := LeafSeries(name); ok { m.Series, m.SeriesIndex, m.SeriesIndexEnd = l.Series, l.Position, l.PositionEnd - if m.Author == "" { - m.Author = l.Author - } - m.Title = l.Title - if m.Title == "" { - m.Title = m.SeriesTitle() - } + m.Author = cmp.Or(m.Author, l.Author) + m.Title = cmp.Or(l.Title, m.SeriesTitle()) } return m } @@ -1075,7 +1070,7 @@ func pathSegments(relPath string, isFolder bool) []string { } // An individually indexed disc in a structured book folder belongs to // that leaf. Use the same book segment for all path and backfill rules. - if isFolder && len(segs) > 1 && strings.Contains(segs[len(segs)-2], ";") && IsDiscFolder(segs[len(segs)-1]) { + if isFolder && len(segs) > 1 && IsDiscFolder(segs[len(segs)-1]) { if _, ok := LeafSeries(segs[len(segs)-2]); ok { segs = segs[:len(segs)-1] } diff --git a/internal/metadata/metadata_test.go b/internal/metadata/metadata_test.go index b1589b45d..eb967cb43 100644 --- a/internal/metadata/metadata_test.go +++ b/internal/metadata/metadata_test.go @@ -396,7 +396,7 @@ func TestPartsTitle(t *testing.T) { // chapter. An unrelated album yields to the book folder. {"only chapters past the album", "The Wheel of Time", "The Wheel of Time - Ravens", "The Eye of the World", "The Wheel of Time - The Peddler", "The Eye of the World"}, {"only a part marker shared", "Dune", "Dune: Part 1 - Chapter 1", "Book 1", "Dune: Part 1 - Chapter 9", "Dune"}, - {"only a volume marker shared", "The Expanse", "The Expanse: Book 1 - Chapter 01", "Folder", "The Expanse: Book 1 - Chapter 30", "The Expanse"}, + {"only a volume marker shared", "The Expanse", "The Expanse: Book 1 - Chapter 01", "Book 1", "The Expanse: Book 1 - Chapter 30", "The Expanse"}, {"underscore chapters", "The Diary of a Nobody", "The Diary of a Nobody_Ch00", "Diary of a Nobody", "The Diary of a Nobody_Ch24", "The Diary of a Nobody"}, {"underscore chapters as written", "secret_agent", "secret_agent_ch01", "Secret Agent", "secret_agent_ch13", "secret_agent"}, } diff --git a/internal/metadata/seriestitle.go b/internal/metadata/seriestitle.go index ad585984d..f6276ac2b 100644 --- a/internal/metadata/seriestitle.go +++ b/internal/metadata/seriestitle.go @@ -120,7 +120,8 @@ func readSeriesPath(relPath string, isFolder bool, tagSeries, tagAuthor string) if l, ok := LeafSeries(leaf); ok { // DeriveFromPath took the leaf's series and position over the folder // holding the book, which still names a series the book is in; the - // title is the leaf's title part. + // title is the leaf's title part alone, "" with none (not DeriveFromPath's + // series and position). p.title = l.Title if len(segs) > 2 { p.series = append(p.series, segs[len(segs)-2]) diff --git a/pkg/match/match.go b/pkg/match/match.go index 6ae7ecc92..677ee06f4 100644 --- a/pkg/match/match.go +++ b/pkg/match/match.go @@ -981,7 +981,9 @@ var titleStopwords = map[string]bool{ // TitlesShareWord reports whether two titles have a word in common beyond // articles and joining words. The scanner uses this to preserve an album -// whose title is a fuller spelling of the book folder's. +// whose title is a fuller spelling of the book folder's. Unlike tokenize it +// keeps letters in any script, numbers and one-letter words, since a folder +// name is weighed here, not scored against a candidate. func TitlesShareWord(a, b string) bool { words := func(s string) []string { return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { From 50ae4067d640490505e25b2ad4f81f551db0277e Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 19:03:37 +0000 Subject: [PATCH 03/16] Keep every admin edit through a match run's write, not only the title A run plans no write over an admin's edit in any field or scope, so an edited override present when it writes was made after it read the book. The guard covered only the title under fill: an admin's edit to another field, or to the title during an overwrite run, made between the plan and the write was replaced. KeepEdited now holds for every field the run sets, in every scope. Part of #307. --- internal/catalog/bookmatches_test.go | 41 ++++++++++++++++++++++++++++ internal/catalog/overrides.go | 15 ++++++---- internal/matchrun/runner.go | 2 +- 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/internal/catalog/bookmatches_test.go b/internal/catalog/bookmatches_test.go index 1a99d3ff0..f71729c8c 100644 --- a/internal/catalog/bookmatches_test.go +++ b/internal/catalog/bookmatches_test.go @@ -1358,3 +1358,44 @@ func TestFieldShowsTheEnrichmentUnderAnOverride(t *testing.T) { t.Errorf("no enrichment = %+v, want none", f) } } + +// TestKeepEditedLeavesAdminEdits: a match run's write (KeepEdited) leaves any +// field an admin edited since it read the book, not only the title, and still +// writes the others; without the flag a community edit replaces it. +func TestKeepEditedLeavesAdminEdits(t *testing.T) { + t.Parallel() + c, ctx := newTestCatalog(t) + lib, _ := c.CreateLibrary(ctx, Library{Name: "L", Root: "/tmp/l"}) + const p = "A/Book" + if _, err := c.UpsertBook(ctx, scannedBook(lib.ID, p)); err != nil { + t.Fatal(err) + } + if err := c.EditBook(ctx, lib.ID, p, BookEdit{Set: map[string]string{FieldDescription: "Mine"}}); err != nil { + t.Fatal(err) + } + override := func(field string) string { + t.Helper() + var v, src string + if err := c.db.QueryRowContext(ctx, `SELECT value, source FROM book_overrides + WHERE library_id = ? AND path = ? AND field = ?`, lib.ID, p, field).Scan(&v, &src); err != nil { + t.Fatal(err) + } + return v + "|" + src + } + theirs := map[string]string{FieldDescription: "Theirs", FieldTitle: "Their Title"} + if err := c.EditBook(ctx, lib.ID, p, BookEdit{Set: theirs, Source: SourceCommunity, KeepEdited: true}); err != nil { + t.Fatal(err) + } + if got := override(FieldDescription); got != "Mine|"+SourceEdited { + t.Errorf("description after a run's write = %q, want the admin's", got) + } + if got := override(FieldTitle); got != "Their Title|"+SourceCommunity { + t.Errorf("title after a run's write = %q", got) + } + if err := c.EditBook(ctx, lib.ID, p, BookEdit{Set: theirs, Source: SourceCommunity}); err != nil { + t.Fatal(err) + } + if got := override(FieldDescription); got != "Theirs|"+SourceCommunity { + t.Errorf("description after an accepted community edit = %q", got) + } +} diff --git a/internal/catalog/overrides.go b/internal/catalog/overrides.go index 37051abc7..7b958b028 100644 --- a/internal/catalog/overrides.go +++ b/internal/catalog/overrides.go @@ -848,10 +848,13 @@ type BookEdit struct { // ASIN, while that ASIN is no admin's own edit (one typed in since, the // same value), else ErrMatchedSince. "" keeps the zero MatchIf's rule. MatchIfASIN string - // KeepEditedTitle protects a fill against a title edit made after it read the book. - KeepEditedTitle bool - Source string - UserID int64 + // KeepEdited leaves a field an admin edited after the match run read the + // book as it is: a run never plans over an admin's edit (matchrun's plan + // and tidyTitle), so one there now was made since (a revert of a + // community title included). + KeepEdited bool + Source string + UserID int64 } // normalizeSource is where an edit or a custom cover came from, as stored: @@ -1133,8 +1136,8 @@ func (c *Catalog) editTx(ctx context.Context, tx *sql.Tx, ref Ref, edit BookEdit ON CONFLICT(library_id, path, field) DO UPDATE SET value = excluded.value, source = excluded.source, updated_by = excluded.updated_by, updated_at = excluded.updated_at - WHERE NOT (? AND book_overrides.source = 'edited')`, - ref.LibraryID, path, field, v, edit.Source, editor, now, edit.KeepEditedTitle && field == FieldTitle); err != nil { + WHERE NOT (? AND book_overrides.source = '`+SourceEdited+`')`, + ref.LibraryID, path, field, v, edit.Source, editor, now, edit.KeepEdited); err != nil { return err } } diff --git a/internal/matchrun/runner.go b/internal/matchrun/runner.go index 727afd865..503e8fb7b 100644 --- a/internal/matchrun/runner.go +++ b/internal/matchrun/runner.go @@ -837,7 +837,7 @@ func (r *Runner) applyItem(ctx context.Context, run *catalog.MatchRun, it *catal edits := len(w.Set) > 0 || len(w.Revert) > 0 || w.Anchor != nil if edits { edit := catalog.BookEdit{Set: w.Set, Revert: w.Revert, Source: catalog.SourceCommunity, UserID: o.UserID, - KeepEditedTitle: o.Scope == ScopeFill} + KeepEdited: true} if w.Anchor != nil { how := catalog.MatchHowAccepted if it.Outcome == catalog.OutcomeAuto { From 46445ba3473bbd2df218f3a517246f10b3b968a9 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 19:36:27 +0000 Subject: [PATCH 04/16] Skip the revision-6 read for a book already titled like its folder The backfill re-read every revision 5 multi-file book whose snapshot title was not byte-for-byte its folder's, so a folder spelled in another case or carrying "(Unabridged)" cost two tag reads per book on the first scan after the upgrade. A title the folder already gives (metadata.SameName: case, brackets and series spelling aside) reads the same under every revision 6 rule, so it is only stamped. Part of #272. --- internal/catalog/pathreading.go | 4 +++- internal/catalog/pathreading_test.go | 6 ++++++ internal/metadata/seriestitle.go | 4 ++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/internal/catalog/pathreading.go b/internal/catalog/pathreading.go index 95a328e52..6fd29ec22 100644 --- a/internal/catalog/pathreading.go +++ b/internal/catalog/pathreading.go @@ -100,7 +100,9 @@ func namesCheck(rev int, rel string, isFolder, severalFiles bool, format, title, return true } pathTitle := metadata.PathTitle(rel, isFolder) - return pathTitle != "" && title != pathTitle + // A title the folder already gives (case and brackets aside) is + // one revision 6 reads the same. + return pathTitle != "" && !metadata.SameName(title, pathTitle) } } return (rev < revTitleNotSeries && metadata.MaybeSeriesTitle(rel, isFolder, title, series)) || diff --git a/internal/catalog/pathreading_test.go b/internal/catalog/pathreading_test.go index aaec2a398..e63cb9ee3 100644 --- a/internal/catalog/pathreading_test.go +++ b/internal/catalog/pathreading_test.go @@ -236,6 +236,12 @@ func TestNamesCheckByRevision(t *testing.T) { t.Errorf("several files at %d: namesCheck = %v, want %v", rev, got, want) } } + // Revision 6: one of revision 5 only when its title isn't the folder's. + for title, want := range map[string]bool{"The Wheel of Time": true, "frankenstein (Unabridged)": false} { + if got := namesCheck(5, "Mary Shelley/Frankenstein", true, true, "mp3", title, "", ""); got != want { + t.Errorf("several files titled %q at 5: namesCheck = %v, want %v", title, got, want) + } + } if revNumber("3") != 3 || revNumber("") != 0 || revNumber("x") != 0 || revNumber("-1") != 0 { t.Error("revNumber misreads a revision") } diff --git a/internal/metadata/seriestitle.go b/internal/metadata/seriestitle.go index f6276ac2b..44975a826 100644 --- a/internal/metadata/seriestitle.go +++ b/internal/metadata/seriestitle.go @@ -297,3 +297,7 @@ func namesAny(name string, names []string) bool { func sameName(a, b string) bool { return match.SameSeries(canonTag(a), canonTag(b)) } + +// SameName is sameName for the backfill's test of a stored title against the +// folder's (catalog's namesCheck). +func SameName(a, b string) bool { return sameName(a, b) } From 029dd407cdb4f67a07528e9addf4918ba0d92a46 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 19:36:27 +0000 Subject: [PATCH 05/16] Keep a leaf's position when the tag spells its series another way A tag naming the leaf's series without its article ("Expanse" beside "James Corey; The Expanse; Book 03") failed match.SameSeries, so the scan cleared the position the leaf states. leafTagSeries also accepts equal match.NormalizeSeries forms; another series still clears it. Part of #325. --- internal/library/pathreading_test.go | 18 +++++++++++------- internal/library/scanner.go | 15 ++++++++++++++- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/internal/library/pathreading_test.go b/internal/library/pathreading_test.go index c6519ab18..b427896fd 100644 --- a/internal/library/pathreading_test.go +++ b/internal/library/pathreading_test.go @@ -652,12 +652,15 @@ func TestScanLeafNamesRevisionSix(t *testing.T) { leaf = "Bea Writer; The Crossing; Books 01-03; Homecoming" same = "Shelf/Bea Writer; The Crossing; Book 01-03; The Ferryman" other = "Shelf/Bea Writer; The Crossing; Book 01-03; Far Bank" - disc = "Bea Writer/Bea Writer; The Crossing; Book 04; Low Water/CD1" - plain = "Plain Name.mp3" + // The tag spells the leaf's series without its article: the same series. + spelled = "Shelf/Bea Writer; The Crossing; Book 05; Second Light" + disc = "Bea Writer/Bea Writer; The Crossing; Book 04; Low Water/CD1" + plain = "Plain Name.mp3" ) silence(t, root, leaf+"/01.mp3", 1) silence(t, root, same+"/01.mp3", 1, "series=THE CROSSING") silence(t, root, other+"/01.mp3", 1, "series=River Stories") + silence(t, root, spelled+"/01.mp3", 1, "series=Crossing") silence(t, root, disc+"/01.mp3", 1) silence(t, root, plain, 1) lib, err := cat.CreateLibrary(ctx, catalog.Library{Name: "L", Root: root}) @@ -670,11 +673,12 @@ func TestScanLeafNamesRevisionSix(t *testing.T) { start, end float64 } want := map[string]names{ - leaf: {"Homecoming", "Bea Writer", "The Crossing", 1, 3}, - same: {"The Ferryman", "Shelf", "THE CROSSING", 1, 3}, - other: {"Far Bank", "Shelf", "River Stories", 0, 0}, - disc: {"Low Water", "Bea Writer", "The Crossing", 4, 0}, - plain: {"Plain Name", "", "", 0, 0}, + leaf: {"Homecoming", "Bea Writer", "The Crossing", 1, 3}, + same: {"The Ferryman", "Shelf", "THE CROSSING", 1, 3}, + other: {"Far Bank", "Shelf", "River Stories", 0, 0}, + spelled: {"Second Light", "Shelf", "Crossing", 5, 0}, + disc: {"Low Water", "Bea Writer", "The Crossing", 4, 0}, + plain: {"Plain Name", "", "", 0, 0}, } scan := func() { t.Helper() diff --git a/internal/library/scanner.go b/internal/library/scanner.go index 0d29044bb..f893496f8 100644 --- a/internal/library/scanner.go +++ b/internal/library/scanner.go @@ -1073,7 +1073,7 @@ func readNames(b *catalog.Book, md, last *metadata.Metadata) *metadata.Metadata n.Author = md.Author } if strings.TrimSpace(md.Series) != "" { - if md.SeriesIndex == 0 && n.SeriesIndex != 0 && !match.SameSeries(n.Series, md.Series) && metadata.PathLeafSeries(b.RelPath, b.IsFolder) { + if md.SeriesIndex == 0 && n.SeriesIndex != 0 && !leafTagSeries(n.Series, md.Series) && metadata.PathLeafSeries(b.RelPath, b.IsFolder) { n.SeriesIndex, n.SeriesIndexEnd = 0, 0 } n.Series = md.Series @@ -1086,6 +1086,19 @@ func readNames(b *catalog.Book, md, last *metadata.Metadata) *metadata.Metadata return n } +// leafTagSeries reports whether a leaf's series and a series tag name one +// series, the way the matcher reads a series name: by match.SameSeries, or with +// a leading article or a trailing " Series" aside (match.NormalizeSeries: "The +// Expanse" and "Expanse"), so a tag spelling the leaf's series its own way +// keeps the leaf's position. +func leafTagSeries(leaf, tag string) bool { + if match.SameSeries(leaf, tag) { + return true + } + n := match.NormalizeSeries(leaf) + return n != "" && n == match.NormalizeSeries(tag) +} + // partNamed reports whether book b's title turns on the tags of another of its // files (metadata.PartNamed): a book of several files whose first file's tags, // md, title it with a tag that may name that file. A scan then reads its last From c8362bb24737b16b4a78ffb69ebe3fdb0ca09f69 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 19:36:27 +0000 Subject: [PATCH 06/16] Keep the album when neither files nor folder name another book The folder replaced a correct album whenever the album and folder shared no word, including when the title tags were track labels or the album with a number ("The Gunslinger" in "The Dark Tower 1"), when the folder was a series slot ("Discworld 05", "Books 1-3"), a container ("Files", "MP3", "Unabridged"), or when the files numbered one book under a series album ("Harry Potter: Philosopher's Stone 01" to "17" in "Files"). Each now keeps the album, as before revision 6. Without an album, tags that differ only by bracketed part markers name the book ("Dune"), a container folder leaves the first tag, and a tag equal to the folder but for case needs no second read. Bracketed notes no longer count as a shared word. Part of #272. --- CONVENTIONS.md | 20 ++++++---- internal/metadata/metadata.go | 60 +++++++++++++++++++++++++++--- internal/metadata/metadata_test.go | 21 ++++++++++- 3 files changed, 86 insertions(+), 15 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 96fee8c91..fa60e73e9 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -2450,14 +2450,20 @@ every session. CLAUDE.md keeps a one-line index of these topics. Agent's `secret_agent`), and nothing else. **Folder titles and leaf names** (`@rev` 6, server#272, server#325). For a book of several files without an album, a title tag that differs between the first and last files gives way - to `PathTitle`. If the files carry different chapter titles and agree on any album they both name, + to `PathTitle`, unless the two differ only by bracketed part markers ("Dune (Part 1)": "Dune"). + If the files carry different chapter titles and agree on any album they both name, and the first has an album and no series tag, the scan uses a meaningful folder title when the album and folder - share no distinctive word. This preserves a fuller album title such as "Frankenstein; or, The - Modern Prometheus" in "Frankenstein". Filename tags such as "Part 01.mp3" leave the album in - place. Shared book names from revision 5 still apply. + share no distinctive word (brackets left out). This preserves a fuller album title such as "Frankenstein; or, The + Modern Prometheus" in "Frankenstein". Tags that name no chapter (`chapterNamed`: filename tags such as + "Part 01.mp3", track labels, the album and a number, "The Gunslinger 01") and a folder named as a + volume or a numbered slot (`folderSlot`: "Book One", "Books 1-3", "The Dark Tower 1") or for + what it holds (`containerFolder`: "Files", "MP3", "Unabridged"), and tags numbering one name in + turn (`numberedAlike`: "Harry Potter: Philosopher's Stone 01" to "... 17"), leave the album in + place; without an album such a folder leaves the first tag. Shared book names from revision 5 still apply. A structured leaf now supplies its title part, or its series and position when it has no title part ("Dark Road 1-5"). A tagged series can use the leaf's position only when both name the - same series (`match.SameSeries`). "Books 01-03" states the same range as "Book 01-03". + same series (`leafTagSeries`: `match.SameSeries`, or `match.NormalizeSeries` with a leading article + or a trailing " Series" aside, "The Expanse" and "Expanse"). "Books 01-03" states the same range as "Book 01-03". A disc folder indexed on its own takes the structured leaf above it as its book. At the library root the author comes from the first part of a structured leaf. **Backfill of revisions 2 to 6**: a snapshot older than today's that a newer revision may read @@ -2467,8 +2473,8 @@ every session. CLAUDE.md keeps a one-line index of these topics. series `SplitSeriesTag` splits, a non-ASCII letter in the title or path; before revision 5 a book of several files, which `Signatures` counts in `book_files` only for a folder book's older snapshot, and whose last file is read too where its title turns on it, `partNamed`; before revision 6 a - structured leaf, a disc directly under one, or a multi-file book whose path title differs from - the snapshot title) + structured leaf, a disc directly under one, or a multi-file book whose path title is not the + snapshot title, `metadata.SameName`: case and brackets aside) is read once by the next scan with the PathRead read and rewritten by `SetPathReading` (which skips only a snapshot already at `scannedRev`), no re-index and no migration (a `PathFromSnapshot` one waits for that read too, so an unreadable file never records today's diff --git a/internal/metadata/metadata.go b/internal/metadata/metadata.go index 2e9ff5aa7..8b69c7192 100644 --- a/internal/metadata/metadata.go +++ b/internal/metadata/metadata.go @@ -788,6 +788,14 @@ func (m *Metadata) PartsTitle(pathTitle string, other *Metadata) string { return m.Title } if m.AlbumTag == "" { + // Tags that differ only by their bracketed part markers name the book, + // as they do beside an album below. + if other != nil && canonTag(m.TitleTag) == canonTag(other.TitleTag) && !IsGenericTitle(cleanTag(m.TitleTag)) { + return cleanTag(m.TitleTag) + } + if containerFolder.MatchString(strings.TrimSpace(cleanTag(pathTitle))) { + return m.Title // "Files", "MP3": the folder names no book either + } return pathTitle } if other == nil { @@ -803,7 +811,8 @@ func (m *Metadata) PartsTitle(pathTitle string, other *Metadata) string { return cleanTag(m.TitleTag) } } - if other.TitleTag != "" && !IsAudio(other.TitleTag) && (other.AlbumTag == "" || sameName(m.AlbumTag, other.AlbumTag)) && m.folderOverAlbum(pathTitle) { + if chapterNamed(m.AlbumTag, other.TitleTag) && !numberedAlike(m.TitleTag, other.TitleTag) && + (other.AlbumTag == "" || sameName(m.AlbumTag, other.AlbumTag)) && m.folderOverAlbum(pathTitle) { return pathTitle } return m.AlbumTag @@ -812,11 +821,50 @@ func (m *Metadata) PartsTitle(pathTitle string, other *Metadata) string { // folderOverAlbum reports whether an unconfirmed album and the folder appear // to name different works. A longer album such as "Frankenstein; or, The // Modern Prometheus" still names the book in "Frankenstein". A known series -// is handled separately by TitleNotSeries. A filename tag like "Part 01.mp3" -// supplies no chapter name to weigh against the album. +// is handled separately by TitleNotSeries. A title tag that names no chapter +// (chapterNamed) has nothing to weigh against the album, and a folder named +// as a volume or a numbered slot ("Book One", "Books 1-3", "The Dark Tower 1": +// folderSlot) or for what it holds ("Files", "MP3", "Unabridged": +// containerFolder) names no title of its own. func (m *Metadata) folderOverAlbum(pathTitle string) bool { - return m.Series == "" && !IsAudio(m.TitleTag) && !IsGenericTitle(cleanTag(pathTitle)) && !volumeMarker(pathTitle) && - !sameName(pathTitle, m.AlbumTag) && !match.TitlesShareWord(pathTitle, m.AlbumTag) + folder := strings.TrimSpace(cleanTag(pathTitle)) + return m.Series == "" && chapterNamed(m.AlbumTag, m.TitleTag) && !IsGenericTitle(folder) && + !volumeMarker(pathTitle) && !folderSlot.MatchString(folder) && !containerFolder.MatchString(folder) && + !sameName(pathTitle, m.AlbumTag) && !match.TitlesShareWord(cleanTag(pathTitle), cleanTag(m.AlbumTag)) +} + +// chapterNamed reports whether a title tag of one of a book's files names a +// chapter of its own: not a file's name ("Part 01.mp3"), a track label +// ("Track 01", "Chapter 3") or the album with a track marker before or after +// it ("The Gunslinger 01", "01 - The Gunslinger"), each of which supplies no +// name to weigh against the album. +func chapterNamed(album, tag string) bool { + if tag == "" || IsAudio(tag) || IsGenericTitle(tag) || trackTail(album, tag) { + return false + } + _, rest := splitSeriesIndex(tag) + return !sameName(rest, album) +} + +// folderSlot matches a folder name that is a volume label ("Book One", "Books +// 1-3", "Volume II") or a name and a volume number ("The Dark Tower 1", +// "Discworld 05"): a slot in a series, not a title to put over the album. +var folderSlot = regexp.MustCompile(`^(?i:books?|vol\.?|volume|part)\s+(?i:\d[\d.\-–]*|[ivxlc]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)$|\s#?\d{1,3}$`) + +// containerFolder matches a folder named for what it holds rather than which +// book ("Files", "MP3", "Audiobook", "Unabridged", "New Folder"). +var containerFolder = regexp.MustCompile(`^(?i:files?|mp3s?|m4[ab]s?|audio|audio ?books?|unabridged|abridged|complete|full|media|tracks?|chapters?|parts?|discs?|cds?|(?:new )?folder|untitled|unknown)$`) + +// trailingTrack is a track number ending a title tag ("Philosopher's Stone 01"). +var trailingTrack = regexp.MustCompile(`[\s._-]+\d{1,3}$`) + +// numberedAlike reports whether two files' title tags are one name numbered in +// turn ("Harry Potter: Philosopher's Stone 01" and "... 17"): the files name +// the same thing, the book or its album, not chapters of their own. +func numberedAlike(first, last string) bool { + f, l := cleanTag(first), cleanTag(last) + tf, tl := trailingTrack.ReplaceAllString(f, ""), trailingTrack.ReplaceAllString(l, "") + return tf != f && tl != l && tf != "" && sameName(tf, tl) } // partsName is the name two title tags of one book's files (first, last) share @@ -876,7 +924,7 @@ func (m *Metadata) PartNamed(pathTitle string) bool { return false } if m.AlbumTag == "" { - return pathTitle != m.TitleTag && !IsGenericTitle(m.TitleTag) + return !sameName(m.TitleTag, pathTitle) && !IsGenericTitle(m.TitleTag) } if m.Title == m.TitleTag && m.TitleTag != m.AlbumTag { return !sameName(m.TitleTag, pathTitle) && !sameName(albumTail(m.AlbumTag, m.TitleTag), pathTitle) diff --git a/internal/metadata/metadata_test.go b/internal/metadata/metadata_test.go index eb967cb43..8ffb04219 100644 --- a/internal/metadata/metadata_test.go +++ b/internal/metadata/metadata_test.go @@ -371,6 +371,21 @@ func TestPartsTitle(t *testing.T) { {"unrelated album, chapter names", "The Wheel of Time", "Ravens Rising", "The Dragon Reborn", "The Peddler", "The Dragon Reborn"}, {"filename tags keep the album", "Real Title", "Part 01.mp3", "Odd Name", "Part 02.mp3", "Real Title"}, {"album corroborated by folder", "The Odyssey", "The Voyage", "Odyssey", "Homecoming", "The Odyssey"}, + // Tags naming no chapter (a track label, the album and a number), or a + // folder named as a volume or a numbered slot, keep the album. + {"track tags keep the album", "The Gunslinger", "Track 01", "The Dark Tower 1", "Track 12", "The Gunslinger"}, + {"album and number tags keep the album", "The Gunslinger", "The Gunslinger 01", "Dark Tower", "The Gunslinger 05", "The Gunslinger"}, + {"number and album tags keep the album", "The Gunslinger", "01 - The Gunslinger", "Dark Tower", "05 - The Gunslinger", "The Gunslinger"}, + {"numbered folder keeps the album", "Sourcery", "Rincewind Runs", "Discworld 05", "The Sourcerer", "Sourcery"}, + {"volume folder keeps the album", "The Fellowship of the Ring", "A Long-expected Party", "Book One", "The Breaking of the Fellowship", "The Fellowship of the Ring"}, + {"box set range folder keeps the album", "The Expanse Box Set", "The Expanse Box Set: Leviathan Wakes", "Books 1-3", "The Expanse Box Set: Caliban's War", "The Expanse Box Set"}, + {"no album, bracketed parts", "", "Dune (Part 1)", "Frank Herbert - Dune [2007]", "Dune (Part 2)", "Dune"}, + // A folder named for what it holds, or files numbering one name in turn + // (the book under a series album), keep the album as before. + {"container folder keeps the album", "Pride and Prejudice", "Netherfield", "Unabridged", "Pemberley", "Pride and Prejudice"}, + {"series album, numbered book tags, container folder", "Harry Potter", "Harry Potter: Philosopher's Stone 01", "Files", "Harry Potter: Philosopher's Stone 17", "Harry Potter"}, + {"numbered book tags keep the album", "Harry Potter", "Philosopher's Stone 01", "Sorcerer Rip", "Philosopher's Stone 17", "Harry Potter"}, + {"no album, container folder keeps the tag", "", "Ravens", "MP3", "The Peddler", "Ravens"}, {"no title tag", "Main Street", "", "Main Street", unread, "Main Street"}, // A box set's album beside each book's own title: the tail names the folder. {"tail names the folder", "The Expanse Box Set", "The Expanse Box Set: Leviathan Wakes", "Leviathan Wakes", unread, "The Expanse Box Set: Leviathan Wakes"}, @@ -417,10 +432,12 @@ func TestPartsTitle(t *testing.T) { want bool }{ {"", "Prologue", "The Dragon Reborn", true}, - {"The Wheel of Time", "Chapter 1", "The Dragon Reborn", true}, - {"The Odyssey", "Chapter 1", "Odyssey", false}, + {"The Wheel of Time", "Ravens", "The Dragon Reborn", true}, + {"The Wheel of Time", "Chapter 1", "The Dragon Reborn", false}, + {"The Odyssey", "The Voyage", "Odyssey", false}, {"The Expanse", "The Expanse: Leviathan Wakes", "Leviathan Wakes", false}, {"", "The Dragon Reborn", "The Dragon Reborn", false}, + {"", "The Dragon Reborn", "the dragon reborn", false}, } { var m Metadata m.setTitle(tc.album, tc.title) From 7530fbcde6391eadc292cd823f1025d93baad616 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 19:36:27 +0000 Subject: [PATCH 07/16] Keep the tag's spelling of a title equal to its folder in path-first libraries The numbered-title check was rewritten to need a number in the folder name, so in a library that prefers its folders a tag equal to the folder except for case ("The Martian" in "the martian") took the folder's spelling. Restore the check: any folder name but a structured leaf. Part of #325. --- internal/catalog/metadatasource_test.go | 7 +++++++ internal/catalog/overrides.go | 6 ++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/internal/catalog/metadatasource_test.go b/internal/catalog/metadatasource_test.go index c6669b90b..a6ba0e3c5 100644 --- a/internal/catalog/metadatasource_test.go +++ b/internal/catalog/metadatasource_test.go @@ -422,6 +422,13 @@ func TestPreferPathKeepsWhatThePathDoesNotSay(t *testing.T) { FieldSeriesIndex: {"", ""}, }, }, + { + // A tag title that is the folder's name in another case keeps the + // tag's spelling. + name: "folder name in lower case", path: "Andy Weir/the martian", isFolder: true, + title: "The Martian", author: "Andy Weir", + want: map[string][2]string{FieldTitle: {"The Martian", SourcePath}}, + }, { // The same series unnumbered by the path keeps the tag's position. name: "same series", path: "James S. A. Corey/The Expanse/Abaddon's Gate", isFolder: true, diff --git a/internal/catalog/overrides.go b/internal/catalog/overrides.go index 7b958b028..318c3bf32 100644 --- a/internal/catalog/overrides.go +++ b/internal/catalog/overrides.go @@ -647,10 +647,12 @@ func (l *bookLayers) readScanned() (scanned, baseline, layout bookFields) { } layout = pathFields(metadata.FromPathLayout(l.path, l.isFolder)) raw := metadata.ReadPathLayout(l.path, l.isFolder) - if number, _ := metadata.SplitSeriesIndex(raw.Title); number != 0 && + if _, leaf := metadata.LeafSeries(raw.Title); !leaf && raw.Title != "" && strings.EqualFold(strings.TrimSpace(l.scanned[FieldTitle]), raw.Title) { // The tag title IS the folder's name, number and all ("13 Reasons Why"): - // the number is part of the title, not a volume the layout can split off. + // the number is part of the title, not a volume the layout can split off, + // and its spelling is the tag's. A leaf named "Author; Series; Book NN[; + // Title]" is no such title: the layout reads its parts. layout[FieldTitle], layout[FieldSeriesIndex] = l.scanned[FieldTitle], raw.Position } scanned = maps.Clone(l.scanned) From 007ad13876142e4e755aa27b846e44a5129cfb95 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 19:36:27 +0000 Subject: [PATCH 08/16] Revert a community title plainly when the files' title is invalid Reverting a community title stores the title underneath as an edited override, but it skipped the checks an admin's own edit gets, so an empty or over-long tag title became an override no admin could type. It now goes through normalizeOverride and falls back to a plain revert. Part of #307. --- internal/catalog/bookmatches_test.go | 40 ++++++++++++++++++++++++++++ internal/catalog/overrides.go | 17 +++++++----- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/internal/catalog/bookmatches_test.go b/internal/catalog/bookmatches_test.go index f71729c8c..c4b5d3a52 100644 --- a/internal/catalog/bookmatches_test.go +++ b/internal/catalog/bookmatches_test.go @@ -1399,3 +1399,43 @@ func TestKeepEditedLeavesAdminEdits(t *testing.T) { t.Errorf("description after an accepted community edit = %q", got) } } + +// TestRevertCommunityTitleLocksTheFiles: an admin's revert of a community +// title stores the title underneath as an edited override (a later fill keeps +// it), unless that title is one an admin couldn't type in (too long), which is +// reverted as before. +func TestRevertCommunityTitleLocksTheFiles(t *testing.T) { + t.Parallel() + c, ctx := newTestCatalog(t) + lib, _ := c.CreateLibrary(ctx, Library{Name: "L", Root: "/tmp/l"}) + long := strings.Repeat("Long Title ", 60) + for path, title := range map[string]string{"A/Short": "Original Name", "A/Long": long} { + b := scannedBook(lib.ID, path) + b.Title = title + if _, err := c.UpsertBook(ctx, b); err != nil { + t.Fatal(err) + } + if err := c.EditBook(ctx, lib.ID, path, BookEdit{Set: map[string]string{FieldTitle: "Their Title"}, Source: SourceCommunity}); err != nil { + t.Fatal(err) + } + if err := c.EditBook(ctx, lib.ID, path, BookEdit{Revert: []string{FieldTitle}}); err != nil { + t.Fatal(err) + } + } + var v, src string + if err := c.db.QueryRowContext(ctx, `SELECT value, source FROM book_overrides + WHERE library_id = ? AND path = 'A/Short' AND field = ?`, lib.ID, FieldTitle).Scan(&v, &src); err != nil { + t.Fatal(err) + } + if v != "Original Name" || src != SourceEdited { + t.Errorf("reverted title override = %q (%s), want the files' title, edited", v, src) + } + var n int + if err := c.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM book_overrides + WHERE library_id = ? AND path = 'A/Long' AND field = ?`, lib.ID, FieldTitle).Scan(&n); err != nil { + t.Fatal(err) + } + if n != 0 { + t.Errorf("a revert onto an over-long title left %d overrides, want a plain revert", n) + } +} diff --git a/internal/catalog/overrides.go b/internal/catalog/overrides.go index 318c3bf32..94d7a4db5 100644 --- a/internal/catalog/overrides.go +++ b/internal/catalog/overrides.go @@ -1092,14 +1092,17 @@ func (c *Catalog) editTx(ctx context.Context, tx *sql.Tx, ref Ref, edit BookEdit if err != nil { return err } + // Reverting the community title chooses the value underneath it. + // Store that choice like any admin edit so a later fill respects it; + // one an admin couldn't type in (none, too long) is a plain revert. if l.overrides[FieldTitle].Source == SourceCommunity { - // Reverting the community title chooses the value underneath it. - // Store that choice like any admin edit so a later fill respects it. - set := make(map[string]string, len(edit.Set)+1) - maps.Copy(set, edit.Set) - set[FieldTitle] = l.unedited(FieldTitle)[FieldTitle].Value - edit.Set = set - edit.Revert = slices.DeleteFunc(slices.Clone(edit.Revert), func(field string) bool { return field == FieldTitle }) + if under, err := normalizeOverride(FieldTitle, l.unedited(FieldTitle)[FieldTitle].Value); err == nil { + set := make(map[string]string, len(edit.Set)+1) + maps.Copy(set, edit.Set) + set[FieldTitle] = under + edit.Set = set + edit.Revert = slices.DeleteFunc(slices.Clone(edit.Revert), func(field string) bool { return field == FieldTitle }) + } } } set, revert := edit.Set, edit.Revert From 6917dc1f17d9ef034d82bde660082b6d0337e657 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 19:36:27 +0000 Subject: [PATCH 09/16] Leave a match run's series fields beside an admin's series edit With an admin's series edit made after a run read the book kept, the run still wrote its position and other series for the community's series beside it. leaveEdited drops the edited fields from the run's write and, when one is a series field, all three series fields, so the book keeps the admin's series as a whole. Part of #307. --- internal/catalog/bookmatches_test.go | 18 ++++++++--- internal/catalog/overrides.go | 45 ++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 7 deletions(-) diff --git a/internal/catalog/bookmatches_test.go b/internal/catalog/bookmatches_test.go index c4b5d3a52..59ac78dfd 100644 --- a/internal/catalog/bookmatches_test.go +++ b/internal/catalog/bookmatches_test.go @@ -1360,8 +1360,9 @@ func TestFieldShowsTheEnrichmentUnderAnOverride(t *testing.T) { } // TestKeepEditedLeavesAdminEdits: a match run's write (KeepEdited) leaves any -// field an admin edited since it read the book, not only the title, and still -// writes the others; without the flag a community edit replaces it. +// field an admin edited since it read the book, not only the title, and the +// run's other series fields beside an edited series, and still writes the +// rest; without the flag a community edit replaces it. func TestKeepEditedLeavesAdminEdits(t *testing.T) { t.Parallel() c, ctx := newTestCatalog(t) @@ -1370,7 +1371,7 @@ func TestKeepEditedLeavesAdminEdits(t *testing.T) { if _, err := c.UpsertBook(ctx, scannedBook(lib.ID, p)); err != nil { t.Fatal(err) } - if err := c.EditBook(ctx, lib.ID, p, BookEdit{Set: map[string]string{FieldDescription: "Mine"}}); err != nil { + if err := c.EditBook(ctx, lib.ID, p, BookEdit{Set: map[string]string{FieldDescription: "Mine", FieldSeries: "My Series"}}); err != nil { t.Fatal(err) } override := func(field string) string { @@ -1382,10 +1383,19 @@ func TestKeepEditedLeavesAdminEdits(t *testing.T) { } return v + "|" + src } - theirs := map[string]string{FieldDescription: "Theirs", FieldTitle: "Their Title"} + theirs := map[string]string{FieldDescription: "Theirs", FieldTitle: "Their Title", FieldSeries: "Their Series", FieldSeriesIndex: "3"} if err := c.EditBook(ctx, lib.ID, p, BookEdit{Set: theirs, Source: SourceCommunity, KeepEdited: true}); err != nil { t.Fatal(err) } + // The run's position for its series doesn't go beside the admin's series. + var positions int + if err := c.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM book_overrides WHERE library_id = ? AND path = ? AND field = ?`, + lib.ID, p, FieldSeriesIndex).Scan(&positions); err != nil || positions != 0 { + t.Errorf("series_index overrides after a run's write = %d (%v), want none", positions, err) + } + if got := override(FieldSeries); got != "My Series|"+SourceEdited { + t.Errorf("series after a run's write = %q, want the admin's", got) + } if got := override(FieldDescription); got != "Mine|"+SourceEdited { t.Errorf("description after a run's write = %q, want the admin's", got) } diff --git a/internal/catalog/overrides.go b/internal/catalog/overrides.go index 94d7a4db5..4728cde14 100644 --- a/internal/catalog/overrides.go +++ b/internal/catalog/overrides.go @@ -1125,6 +1125,11 @@ func (c *Catalog) editTx(ctx context.Context, tx *sql.Tx, ref Ref, edit BookEdit if len(swapRevert) > 0 || len(labelRevert) > 0 { revert = slices.Concat(edit.Revert, swapRevert, labelRevert) } + if edit.KeepEdited { + if set, err = leaveEdited(ctx, tx, ref.LibraryID, path, set); err != nil { + return err + } + } if len(set) == 0 && len(revert) == 0 && !edit.editsChapters() { if edit.Match != nil && edit.Match.WorkID != "" { // An anchor alone: the match is part of the book's community @@ -1140,9 +1145,8 @@ func (c *Catalog) editTx(ctx context.Context, tx *sql.Tx, ref Ref, edit BookEdit VALUES(?,?,?,?,?,?,?) ON CONFLICT(library_id, path, field) DO UPDATE SET value = excluded.value, source = excluded.source, - updated_by = excluded.updated_by, updated_at = excluded.updated_at - WHERE NOT (? AND book_overrides.source = '`+SourceEdited+`')`, - ref.LibraryID, path, field, v, edit.Source, editor, now, edit.KeepEdited); err != nil { + updated_by = excluded.updated_by, updated_at = excluded.updated_at`, + ref.LibraryID, path, field, v, edit.Source, editor, now); err != nil { return err } } @@ -1207,6 +1211,41 @@ func (c *Catalog) editTx(ctx context.Context, tx *sql.Tx, ref Ref, edit BookEdit return refreshEffective(ctx, tx, bookID) } +// seriesFields are the fields a match run lays out together (matchrun's +// planSeries): the main series, its position and the other series. +var seriesFields = []string{FieldSeries, FieldSeriesIndex, FieldMoreSeries} + +// leaveEdited is a match run's set (BookEdit.KeepEdited) less the fields an +// admin edited since the run read the book: a run never plans over an edit, so +// an edited field in set is one made since. One of the series fields takes the +// others out too, so the run's position or other series never go beside the +// admin's series. +func leaveEdited(ctx context.Context, tx *sql.Tx, libraryID int64, path string, set map[string]string) (map[string]string, error) { + rows, err := tx.QueryContext(ctx, `SELECT field FROM book_overrides WHERE library_id = ? AND path = ? AND source = ?`, + libraryID, path, SourceEdited) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + edited := map[string]bool{} + for rows.Next() { + var field string + if err := rows.Scan(&field); err != nil { + return nil, err + } + if _, ok := set[field]; ok { + edited[field] = true + } + } + if err := rows.Err(); err != nil || len(edited) == 0 { + return set, err + } + series := slices.ContainsFunc(seriesFields, func(f string) bool { return edited[f] }) + set = maps.Clone(set) + maps.DeleteFunc(set, func(field, _ string) bool { return edited[field] || (series && slices.Contains(seriesFields, field)) }) + return set, nil +} + // seriesSwap is what an admin edit making one of a book's other series its main // one (by its exact name) writes besides, so the old main series isn't lost and // the new one isn't listed twice: the old main series takes the entry's place in From e95cbc14420cafaa8b13dc25e676b2b0bb556401 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 20:07:32 +0000 Subject: [PATCH 10/16] Keep the album or tag beside folders that name no title of their own A no-album book in a folder such as "03" or "Book 3" took the folder over its first title tag; a book straight in its author's folder took the author's name over a correct album; "Mistborn Book One" was not seen as a series slot; and a title tag equal to the folder lost to an unrelated series album. Main titled each of these right. Part of #272. --- CONVENTIONS.md | 16 +++++---- internal/metadata/metadata.go | 58 ++++++++++++++++++++++-------- internal/metadata/metadata_test.go | 20 +++++++++++ 3 files changed, 74 insertions(+), 20 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index fa60e73e9..19812a11f 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -2366,7 +2366,7 @@ every session. CLAUDE.md keeps a one-line index of these topics. layout over the tags (`bookLayers.scannedFields`: `metadata.FromPathLayout`, where the top folder is the AUTHOR and disc/track folders are parts, unlike `DeriveFromPath`'s two nearest folders; a layout value goes over a tag's wherever it says anything and replaces the baseline's own reading even with - nothing (a leaf named `Author; Series; Book NN[; Title]` says its series, position and title part, `LeafSeries`); the title always keeps one, and a tag title that IS the folder's name, number and all ("13 Reasons Why"), stays whole with no position read from it; the position goes with the series: the layout's own, else + nothing (a leaf named `Author; Series; Book NN[; Title]` says its series, position and title part, `LeafSeries`); the title always keeps one, and a tag title that IS the folder's name, number and all ("13 Reasons Why"), stays whole with no position read from it (never a `LeafSeries` leaf, whose parts the layout reads); the position goes with the series: the layout's own, else the scanned one only while the series it numbers stays). It is a resolve rule, not a scan one: the snapshot is unchanged, and `UpdateLibrary` marks the library's books due a re-resolve in the edit's own transaction (`markResolve`: the `library_resolve_due` row of `server_state`, the library's id and the change's @@ -2455,11 +2455,15 @@ every session. CLAUDE.md keeps a one-line index of these topics. and the first has an album and no series tag, the scan uses a meaningful folder title when the album and folder share no distinctive word (brackets left out). This preserves a fuller album title such as "Frankenstein; or, The Modern Prometheus" in "Frankenstein". Tags that name no chapter (`chapterNamed`: filename tags such as - "Part 01.mp3", track labels, the album and a number, "The Gunslinger 01") and a folder named as a - volume or a numbered slot (`folderSlot`: "Book One", "Books 1-3", "The Dark Tower 1") or for - what it holds (`containerFolder`: "Files", "MP3", "Unabridged"), and tags numbering one name in - turn (`numberedAlike`: "Harry Potter: Philosopher's Stone 01" to "... 17"), leave the album in - place; without an album such a folder leaves the first tag. Shared book names from revision 5 still apply. + "Part 01.mp3", track labels, the album and a number, "The Gunslinger 01"), a folder that names no + title (`untitledFolder`: a bare number "03", a volume label "Book One", "Books 1-3", or what it + holds, `containerFolder`: "Files", "MP3", "Unabridged"), a numbered slot (`folderSlot`: "The Dark + Tower 1", "Mistborn Book One") or the author tag ("Andy Weir", a book straight in its author's + folder), and tags numbering one name in turn (`numberedAlike`: "Harry Potter: Philosopher's + Stone 01" to "... 17"), leave the album in place; without an album a folder that names no title + leaves the first tag (a numbered name, "Fahrenheit 451", may be the title there). A title tag the + folder names too beside such an album is the book's, with no second read (`folderNamesTag`: "The + Eye of the World" under "The Wheel of Time"). Shared book names from revision 5 still apply. A structured leaf now supplies its title part, or its series and position when it has no title part ("Dark Road 1-5"). A tagged series can use the leaf's position only when both name the same series (`leafTagSeries`: `match.SameSeries`, or `match.NormalizeSeries` with a leading article diff --git a/internal/metadata/metadata.go b/internal/metadata/metadata.go index 8b69c7192..875be77bf 100644 --- a/internal/metadata/metadata.go +++ b/internal/metadata/metadata.go @@ -780,10 +780,15 @@ func bookTitle(album, title string) string { // title tags, or a book name shared past the album, can name the book. When // the tags name different chapters, an album corroborated by the folder still // names the book. Without that evidence an unrelated album can name a series. +// A title tag the folder names too beside such an album is the book's ("The +// Eye of the World" under "The Wheel of Time"). func (m *Metadata) PartsTitle(pathTitle string, other *Metadata) string { if m.AlbumTag == "" && m.TitleTag != "" && IsGenericTitle(m.TitleTag) && pathTitle != "" { return pathTitle } + if m.folderNamesTag(pathTitle) { + return m.TitleTag + } if !m.PartNamed(pathTitle) || (other != nil && strings.EqualFold(m.TitleTag, other.TitleTag)) { return m.Title } @@ -793,8 +798,8 @@ func (m *Metadata) PartsTitle(pathTitle string, other *Metadata) string { if other != nil && canonTag(m.TitleTag) == canonTag(other.TitleTag) && !IsGenericTitle(cleanTag(m.TitleTag)) { return cleanTag(m.TitleTag) } - if containerFolder.MatchString(strings.TrimSpace(cleanTag(pathTitle))) { - return m.Title // "Files", "MP3": the folder names no book either + if pathTitle != "" && untitledFolder(pathTitle) { + return m.Title // "Files", "MP3", "03", "Book 3": the folder names no book either } return pathTitle } @@ -822,15 +827,32 @@ func (m *Metadata) PartsTitle(pathTitle string, other *Metadata) string { // to name different works. A longer album such as "Frankenstein; or, The // Modern Prometheus" still names the book in "Frankenstein". A known series // is handled separately by TitleNotSeries. A title tag that names no chapter -// (chapterNamed) has nothing to weigh against the album, and a folder named -// as a volume or a numbered slot ("Book One", "Books 1-3", "The Dark Tower 1": -// folderSlot) or for what it holds ("Files", "MP3", "Unabridged": -// containerFolder) names no title of its own. +// (chapterNamed) has nothing to weigh against the album, and a folder that +// names no title of its own (untitledFolder), a numbered slot ("The Dark +// Tower 1", "Mistborn Book One": folderSlot) or the author tag ("Andy Weir", +// a book straight in its author's folder) keeps it. func (m *Metadata) folderOverAlbum(pathTitle string) bool { folder := strings.TrimSpace(cleanTag(pathTitle)) - return m.Series == "" && chapterNamed(m.AlbumTag, m.TitleTag) && !IsGenericTitle(folder) && - !volumeMarker(pathTitle) && !folderSlot.MatchString(folder) && !containerFolder.MatchString(folder) && - !sameName(pathTitle, m.AlbumTag) && !match.TitlesShareWord(cleanTag(pathTitle), cleanTag(m.AlbumTag)) + return m.Series == "" && chapterNamed(m.AlbumTag, m.TitleTag) && !untitledFolder(pathTitle) && + !folderSlot.MatchString(folder) && !sameName(pathTitle, m.AlbumTag) && !sameName(pathTitle, m.Author) && + !match.TitlesShareWord(folder, cleanTag(m.AlbumTag)) +} + +// folderNamesTag reports whether the album bookTitle chose sits beside a title +// tag the book's folder names too, the album naming another work +// (folderOverAlbum): a series album over the book's own title. +func (m *Metadata) folderNamesTag(pathTitle string) bool { + return m.AlbumTag != "" && m.Title == m.AlbumTag && sameName(m.TitleTag, pathTitle) && m.folderOverAlbum(pathTitle) +} + +// untitledFolder reports whether a book's folder name (pathTitle) names no +// title of its own: a track label or a bare number ("03"), a volume marker +// or label ("Book 3", "Book One", "Books 1-3": volumeFolder) or what it holds +// ("Files", "MP3", "Unabridged": containerFolder). +func untitledFolder(pathTitle string) bool { + folder := strings.TrimSpace(cleanTag(pathTitle)) + return IsGenericTitle(folder) || volumeMarker(pathTitle) || volumeFolder.MatchString(folder) || + containerFolder.MatchString(folder) } // chapterNamed reports whether a title tag of one of a book's files names a @@ -846,10 +868,18 @@ func chapterNamed(album, tag string) bool { return !sameName(rest, album) } -// folderSlot matches a folder name that is a volume label ("Book One", "Books -// 1-3", "Volume II") or a name and a volume number ("The Dark Tower 1", -// "Discworld 05"): a slot in a series, not a title to put over the album. -var folderSlot = regexp.MustCompile(`^(?i:books?|vol\.?|volume|part)\s+(?i:\d[\d.\-–]*|[ivxlc]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)$|\s#?\d{1,3}$`) +// volumeLabel is a volume word and its number ("Book One", "Books 1-3", +// "Volume II"). +const volumeLabel = `(?i:books?|vol\.?|volume|part)\s+(?i:\d[\d.\-–]*|[ivxlc]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)` + +// volumeFolder matches a folder name that is only a volume label: no title. +var volumeFolder = regexp.MustCompile(`^` + volumeLabel + `$`) + +// folderSlot matches a folder name that is a name and a volume number or label +// ("The Dark Tower 1", "Discworld 05", "Mistborn Book One"): a slot in a +// series, not a title to put over the album. Without an album to keep, such a +// name ("Fahrenheit 451") may be the title, so only folderOverAlbum asks. +var folderSlot = regexp.MustCompile(`\s(?:` + volumeLabel + `|#?\d{1,3})$`) // containerFolder matches a folder named for what it holds rather than which // book ("Files", "MP3", "Audiobook", "Unabridged", "New Folder"). @@ -929,7 +959,7 @@ func (m *Metadata) PartNamed(pathTitle string) bool { if m.Title == m.TitleTag && m.TitleTag != m.AlbumTag { return !sameName(m.TitleTag, pathTitle) && !sameName(albumTail(m.AlbumTag, m.TitleTag), pathTitle) } - return !sameName(m.TitleTag, m.AlbumTag) && m.folderOverAlbum(pathTitle) + return !sameName(m.TitleTag, m.AlbumTag) && !sameName(m.TitleTag, pathTitle) && m.folderOverAlbum(pathTitle) } // albumTail is what a title tag adds to the album when it extends it at a word diff --git a/internal/metadata/metadata_test.go b/internal/metadata/metadata_test.go index 8ffb04219..a5193b551 100644 --- a/internal/metadata/metadata_test.go +++ b/internal/metadata/metadata_test.go @@ -379,6 +379,15 @@ func TestPartsTitle(t *testing.T) { {"numbered folder keeps the album", "Sourcery", "Rincewind Runs", "Discworld 05", "The Sourcerer", "Sourcery"}, {"volume folder keeps the album", "The Fellowship of the Ring", "A Long-expected Party", "Book One", "The Breaking of the Fellowship", "The Fellowship of the Ring"}, {"box set range folder keeps the album", "The Expanse Box Set", "The Expanse Box Set: Leviathan Wakes", "Books 1-3", "The Expanse Box Set: Caliban's War", "The Expanse Box Set"}, + {"series and volume word folder keeps the album", "The Final Empire", "Prologue", "Mistborn Book One", "Epilogue", "The Final Empire"}, + // A title tag the folder names too beside an unrelated album is the + // book's, read alike by every file or not. + {"tags name the folder over a series album", "The Wheel of Time", "The Eye of the World", "The Eye of the World", "The Eye of the World", "The Eye of the World"}, + {"tag names the folder over a series album", "The Wheel of Time", "The Eye of the World", "the eye of the world", unread, "The Eye of the World"}, + // Without an album, a folder that names no title keeps the first tag. + {"no album, number folder keeps the tag", "", "Oathbringer - 01", "03", "Oathbringer - 45", "Oathbringer - 01"}, + {"no album, volume folder keeps the tag", "", "Prologue", "Book 3", "Epilogue", "Prologue"}, + {"no album, numbered title folder", "", "The Hearth and the Salamander", "Fahrenheit 451", "Burning Bright", "Fahrenheit 451"}, {"no album, bracketed parts", "", "Dune (Part 1)", "Frank Herbert - Dune [2007]", "Dune (Part 2)", "Dune"}, // A folder named for what it holds, or files numbering one name in turn // (the book under a series album), keep the album as before. @@ -438,6 +447,8 @@ func TestPartsTitle(t *testing.T) { {"The Expanse", "The Expanse: Leviathan Wakes", "Leviathan Wakes", false}, {"", "The Dragon Reborn", "The Dragon Reborn", false}, {"", "The Dragon Reborn", "the dragon reborn", false}, + // The folder confirms the tag beside the album: no second read. + {"The Wheel of Time", "The Eye of the World", "The Eye of the World", false}, } { var m Metadata m.setTitle(tc.album, tc.title) @@ -448,6 +459,15 @@ func TestPartsTitle(t *testing.T) { if (*Metadata)(nil).PartNamed("Any") { t.Error("no tags: PartNamed = true") } + // A book straight in its author's folder: the folder names the author, + // not another work, so the album stays. + m := Metadata{Author: "Andy Weir"} + m.setTitle("The Martian", "Sol Six") + other := Metadata{} + other.setTitle("The Martian", "Homecoming") + if got := m.PartsTitle("Andy Weir", &other); got != "The Martian" { + t.Errorf("author folder: PartsTitle = %q, want the album", got) + } } func TestIsGenericTitle(t *testing.T) { From d1a244b6e2cc84aafcb7e1011771269ef105137e Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 20:07:32 +0000 Subject: [PATCH 11/16] Prefill a structured leaf's title part when the stored title is the leaf A title tag written from a folder named "Author; Series; Book NN; Title", or a row not read again since revision 6, still stores the whole leaf. The match dialog then searched for the whole leaf instead of its title part. Part of #325. --- internal/meta/prefill.go | 21 +++++++++++++++++++-- internal/meta/prefill_test.go | 9 +++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/internal/meta/prefill.go b/internal/meta/prefill.go index dc2a82050..7ff2d7840 100644 --- a/internal/meta/prefill.go +++ b/internal/meta/prefill.go @@ -24,7 +24,13 @@ import ( // the author, cleaned of series and numbering (match.CleanTitle), is the // path's title ("Bernard Cornwell" by "Sharpe's Eagle (Sharpe 08)"); // - a junk title ("Track 01", "03": metadata.IsGenericTitle; "Unknown", -// "Untitled") or a junk author ("Unknown", "Various Artists"), each alone. +// "Untitled") or a junk author ("Unknown", "Various Artists"), each alone; +// - a title that is the book's own leaf named "Author; Series; Book NN[; +// Title]" (metadata.LeafSeries: a title tag written from the leaf, or a +// row a scan before revision 6 titled by it and none has read again since), +// which the path reads as its title part, else its series and position +// ("Dark Road 1-5"); a tag that only looks like one, beside a leaf named +// otherwise, names its book and stays. // // A fact the path doesn't give keeps the tag's value (for swapped tags, the // other tag's). @@ -47,7 +53,7 @@ func SearchPrefill(title, author, series, relPath string, isFolder bool) string // Eagle" folder is Sharpe's Eagle by Bernard Cornwell. title, author = author, title } - if pathTitle != "" && (swapped || junkTitle(title)) { + if pathTitle != "" && (swapped || junkTitle(title) || leafTitle(title, relPath, isFolder)) { title = pathTitle } if p.Author != "" && (swapped || junkAuthor(author)) { @@ -65,6 +71,17 @@ func junkTitle(t string) bool { return metadata.IsGenericTitle(t) } +// leafTitle reports whether a title is the book's own leaf, named "Author; +// Series; Book NN[; Title]" (metadata.LeafSeries), so a tag that is only +// shaped like one is never replaced. +func leafTitle(title, relPath string, isFolder bool) bool { + leaf := metadata.ReadPathLayout(relPath, isFolder).Title + if _, ok := metadata.LeafSeries(leaf); !ok { + return false + } + return match.Fold(title) == match.Fold(leaf) +} + // junkAuthor reports whether an author tag names nobody. func junkAuthor(a string) bool { switch strings.ToLower(a) { diff --git a/internal/meta/prefill_test.go b/internal/meta/prefill_test.go index 4fb7b7d56..f6907bf76 100644 --- a/internal/meta/prefill_test.go +++ b/internal/meta/prefill_test.go @@ -44,6 +44,15 @@ func TestSearchPrefill(t *testing.T) { "Bruno Miller/Bruno Miller; Dark Road; Book 01-05", true, "Dark Road 1-5 Bruno Miller"}, {"a leaf with no position", "Track 01", "Isaac Asimov", "", "Isaac Asimov/Isaac Asimov; Robot Dreams; Book XX", true, "Robot Dreams Isaac Asimov"}, + // A title that is the whole leaf (a tag written from it, or a row read + // before revision 6): the path reads its title part, else its series + // and position. + {"a leaf title's range", "Bruno Miller; Dark Road; Book 01-05", "Bruno Miller", "", + "Bruno Miller/Bruno Miller; Dark Road; Book 01-05", true, "Dark Road 1-5 Bruno Miller"}, + {"a leaf title's title part", "Mark Tufo; Indian Hill; Book 04; From The Ashes", "Mark Tufo", "", + "Mark Tufo/Mark Tufo; Indian Hill; Book 04; From The Ashes", true, "From The Ashes Mark Tufo"}, + {"a leaf file title's title part", "Mark Tufo; Indian Hill; Book 04; From The Ashes", "", "", + "Mark Tufo/Mark Tufo; Indian Hill; Book 04; From The Ashes.mp3", false, "From The Ashes Mark Tufo"}, {"a tagged title in a leaf stays", "From The Ashes (Unabridged)", "Mark Tufo", "", "Mark Tufo/Mark Tufo; Indian Hill; Book 04; From The Ashes", true, "From The Ashes (Unabridged) Mark Tufo"}, {"a tagged title shaped like a leaf beside another leaf stays", "Mark Tufo; Indian Hill; Book 04; From The Ashes", From 2644465b650169978a478f50fdf1ad7461194d93 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 20:07:32 +0000 Subject: [PATCH 12/16] Test TitlesShareWord Its word splitting and stopwords decide whether a folder can replace an album, so a change to them should fail a test. Part of #272. --- pkg/match/match_test.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/pkg/match/match_test.go b/pkg/match/match_test.go index 086f66ce7..bced11a39 100644 --- a/pkg/match/match_test.go +++ b/pkg/match/match_test.go @@ -550,3 +550,25 @@ func TestRecordings(t *testing.T) { }) } } + +// TestTitlesShareWord: a word beyond articles and joining words, in any +// script, a number or one letter included, is shared; case and punctuation +// aside. +func TestTitlesShareWord(t *testing.T) { + for _, c := range []struct { + a, b string + want bool + }{ + {"Frankenstein", "Frankenstein; or, The Modern Prometheus", true}, + {"The Eye of the World", "The Wheel of Time", false}, + {"HARRY potter 1", "Harry Potter and the Philosopher's Stone", true}, + {"Война и мир", "Мир", true}, + {"Catch 22", "Fahrenheit 451", false}, + {"Book 1", "Volume 1", true}, + {"", "Anything", false}, + } { + if got := TitlesShareWord(c.a, c.b); got != c.want { + t.Errorf("TitlesShareWord(%q, %q) = %v, want %v", c.a, c.b, got, c.want) + } + } +} From 397f10cbdf7c7cee63d88f841d8c98860245d248 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 20:07:32 +0000 Subject: [PATCH 13/16] Name a tagged structured leaf without a title part by series and position "Bruno Miller; Dark Road; Books 01-05" tagged with the series as the album was titled "Dark Road", while the untagged copy was "Dark Road 1-5". A tagged range or later book now reads as the untagged copy does; a single first book keeps the album, and a title tag that names the book still wins. Part of #325. --- internal/metadata/seriestitle.go | 29 +++++++++++++++++++++------ internal/metadata/seriestitle_test.go | 12 +++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/internal/metadata/seriestitle.go b/internal/metadata/seriestitle.go index 44975a826..e7f7c7c2a 100644 --- a/internal/metadata/seriestitle.go +++ b/internal/metadata/seriestitle.go @@ -38,7 +38,12 @@ import ( // then be a chapter's ("End Credits"); any other book takes the title tag, // except a book of several files, whose lone first-file tag ("Prologue", in // "Indian Hill/Book 3") counts only when it carries the series' name. With -// neither, title stays. A book whose own leaf names it as the album does +// neither, title stays, except under a LeafSeries leaf without a title part +// that states the album's series: the book is then named by its series and +// position as an untagged copy is ("Dark Road 1-5", DeriveFromPath). A range +// goes before the first-book rule (an omnibus is not the book the series is +// named for: a title tag that counts, else the range); a single first book +// keeps the album. A book whose own leaf names it as the album does // ("Frank Herbert/Dune/Dune": a series named for its first book), alone or // beside only its author, a year, a volume marker or the series and the number // 1 ("Frank Herbert/Frank Herbert - Dune.m4b", "Dune/1965 - Dune"), keeps the @@ -47,7 +52,7 @@ func TitleNotSeries(title string, md *Metadata, relPath string, isFolder, severa if md == nil || title == "" || title != md.AlbumTag { return title } - p := readSeriesPath(relPath, isFolder, md.Series, md.Author) + p := readSeriesPath(relPath, isFolder, md.Series, md.Author, title) if !p.namedForSeries(title) { return title } @@ -66,12 +71,16 @@ func TitleNotSeries(title string, md *Metadata, relPath string, isFolder, severa return tag case okPath && (severalFiles || !okTag || carriesName(tag, series)): return path + case okTag && p.isRange && (!severalFiles || carriesName(tag, series)): + return tag // an omnibus is never the first book named for its series + case p.isRange: + return p.untitled case cmp.Or(md.SeriesIndex, p.position) == 1: return title case okTag && (!severalFiles || carriesName(tag, series)): return tag } - return title + return cmp.Or(p.untitled, title) } // MaybeSeriesTitle reports whether a stored title and series could be a book's @@ -83,7 +92,7 @@ func MaybeSeriesTitle(relPath string, isFolder bool, title, series string) bool if strings.TrimSpace(title) == "" { return false } - return readSeriesPath(relPath, isFolder, series, "").namedForSeries(title) + return readSeriesPath(relPath, isFolder, series, "", "").namedForSeries(title) } // PathTitle is the title TitleNotSeries reads off a book's path (the title @@ -91,7 +100,7 @@ func MaybeSeriesTitle(relPath string, isFolder bool, title, series string) bool // else DeriveFromPath's; "" for a LeafSeries leaf without one), so the book // page can label a title the scan took from there as the path's. func PathTitle(relPath string, isFolder bool) string { - return readSeriesPath(relPath, isFolder, "", "").title + return readSeriesPath(relPath, isFolder, "", "", "").title } // seriesPath is what a book's tags and path say of its series and title for @@ -107,9 +116,14 @@ type seriesPath struct { // position is the leaf's volume number (DeriveFromPath's: a LeafSeries // leaf's included), 0 for none. position float64 + // untitled is the series and position a LeafSeries leaf without a title + // part names its book by, as DeriveFromPath does ("Dark Road 1-5"), when + // title names that series; isRange says the leaf states a range. "" else. + untitled string + isRange bool } -func readSeriesPath(relPath string, isFolder bool, tagSeries, tagAuthor string) seriesPath { +func readSeriesPath(relPath string, isFolder bool, tagSeries, tagAuthor, title string) seriesPath { n := DeriveFromPath(relPath, isFolder) p := seriesPath{ series: []string{tagSeries, n.Series}, title: n.Title, position: n.SeriesIndex, @@ -123,6 +137,9 @@ func readSeriesPath(relPath string, isFolder bool, tagSeries, tagAuthor string) // title is the leaf's title part alone, "" with none (not DeriveFromPath's // series and position). p.title = l.Title + if l.Title == "" && n.Title != "" && namesAny(title, []string{l.Series}) { + p.untitled, p.isRange = n.Title, ValidSeriesRange(l.Position, l.PositionEnd) + } if len(segs) > 2 { p.series = append(p.series, segs[len(segs)-2]) } diff --git a/internal/metadata/seriestitle_test.go b/internal/metadata/seriestitle_test.go index 8d235fac6..231d4365d 100644 --- a/internal/metadata/seriestitle_test.go +++ b/internal/metadata/seriestitle_test.go @@ -35,6 +35,18 @@ func TestTitleNotSeries(t *testing.T) { {"leaf layout: book 1 named for its series keeps it", "Mark Tufo/Mark Tufo; Indian Hill; Book 01", false, map[string]string{"genre": "Audiobook", "album": "Indian Hill", "album_artist": "Mark Tufo", "artist": "Mark Tufo", "title": "Indian Hill", "date": "2012"}, "Indian Hill"}, + {"leaf layout: an omnibus without a title part reads as the untagged copy", "Bruno Miller/Bruno Miller; Dark Road; Books 01-05", true, + map[string]string{"album": "Dark Road", "artist": "Bruno Miller", "title": "Dark Road 01"}, + "Dark Road 1-5"}, + {"leaf layout: a later book without a title part takes its position", "Mark Tufo/Mark Tufo; Indian Hill; Book 05", false, + map[string]string{"album": "Indian Hill", "artist": "Mark Tufo", "title": "Indian Hill"}, + "Indian Hill 5"}, + {"leaf layout: an omnibus keeps a title tag naming it", "Bruno Miller/Bruno Miller; Dark Road; Books 01-05", false, + map[string]string{"album": "Dark Road", "artist": "Bruno Miller", "title": "The Complete Collection"}, + "The Complete Collection"}, + {"leaf layout: an album naming another series is left alone", "Bruno Miller/Bruno Miller; Dark Road; Books 01-05", true, + map[string]string{"album": "River Stories", "series": "River Stories", "artist": "Bruno Miller", "title": "Chapter 1"}, + "River Stories"}, // "Author/Series/Book N": the folder holding the book is the series. {"series folder: series and number", "Eric Vall/Without Law/Book 17", false, map[string]string{"title": "Without Law 17", "artist": "Eric Vall", "album": "Without Law", "track": "17"}, From a349051fd46e7d7aef1d6d38669fb44c09281687 Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 20:07:32 +0000 Subject: [PATCH 14/16] Stop re-reading a book whose last file will not open on every scan A book whose title turns on its last file's tags waited for that file on every scan, so an unopenable last file cost two tag reads per scan forever. The failed read is now remembered like an ffprobe rejection, until the book is indexed again; the stored title stays. Part of #272. --- internal/catalog/books.go | 3 ++- internal/library/pathreading_test.go | 25 ++++++++++++++++++++++--- internal/library/scanner.go | 19 ++++++++++++++++--- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/internal/catalog/books.go b/internal/catalog/books.go index 5d2663ddc..5873574d7 100644 --- a/internal/catalog/books.go +++ b/internal/catalog/books.go @@ -543,7 +543,8 @@ type Signature struct { DurationStale bool // TagReadFailed: a scan's backfill read of the book's primary file for its // names or tag hints found ffprobe rejecting the file, where the index had - // not, and the book has not been indexed since (books.tag_read_failed_at, + // not, or found the last file of a book whose title turns on it + // (metadata.PartNamed) unopenable, and the book has not been indexed since (books.tag_read_failed_at, // 0091), so its files are the bytes that read failed on: the next scan does // not read it again for them (server#318). An index of the book (its files // changed, a Re-read) clears it. diff --git a/internal/library/pathreading_test.go b/internal/library/pathreading_test.go index b427896fd..ab4cbf3cb 100644 --- a/internal/library/pathreading_test.go +++ b/internal/library/pathreading_test.go @@ -354,8 +354,9 @@ func TestScanPartsTitle(t *testing.T) { } // A title that turns on the last file's tags waits for them: with that file - // unreadable the snapshot keeps its revision for the next scan, never the - // album recorded on a guess. + // unreadable the snapshot keeps its revision and title, never the album + // recorded on a guess, and later scans don't read it again until the book is + // indexed again. rev := func() (r string) { t.Helper() if err := db.QueryRowContext(ctx, `SELECT json_extract(scanned, '$."@rev"') FROM books WHERE rel_path = ?`, shared).Scan(&r); err != nil { @@ -376,7 +377,14 @@ func TestScanPartsTitle(t *testing.T) { } check("last file unreadable") if got := rev(); got != "4" { - t.Fatalf("revision with the last file unreadable = %q, want 4 (left for the next scan)", got) + t.Fatalf("revision with the last file unreadable = %q, want 4 (left as it is)", got) + } + sigs, err = cat.Signatures(ctx, lib.ID) + if err != nil { + t.Fatal(err) + } + if !sigs[shared].TagReadFailed { + t.Fatalf("an unopenable last file = %+v, want the read remembered as failed (not made on every scan)", sigs[shared]) } if err := os.Chmod(last, 0o644); err != nil { t.Fatal(err) @@ -384,6 +392,17 @@ func TestScanPartsTitle(t *testing.T) { if _, err := s.Scan(ctx, *lib); err != nil { t.Fatal(err) } + if got := rev(); got != "4" { + t.Fatalf("revision on the next scan = %q, want 4 (not read again before the book is indexed)", got) + } + // Its files changed (as a Re-read would), the book is indexed again. + later := time.Now().Add(time.Minute) + if err := os.Chtimes(last, later, later); err != nil { + t.Fatal(err) + } + if _, err := s.Scan(ctx, *lib); err != nil { + t.Fatal(err) + } check("last file readable again") if got := rev(); got != "6" { t.Fatalf("revision once the last file is read = %q, want 6", got) diff --git a/internal/library/scanner.go b/internal/library/scanner.go index f893496f8..a4b1e5c1f 100644 --- a/internal/library/scanner.go +++ b/internal/library/scanner.go @@ -439,7 +439,7 @@ func (s *Scanner) Scan(ctx context.Context, lib catalog.Library) (_ *ScanResult, // Books found unchanged whose ebook is new, changed or gone (or never looked // for: indexed before 0056): recorded without a re-index (SetEbooks). ebookBackfill := map[string]catalog.EbookReading{} - // Books found unchanged whose revision 1 to 4 snapshot needs no read + // Books found unchanged whose revision 1 to 5 snapshot needs no read // (Signature.RevStamp): stamped with today's revision (StampScannedRev), so // later scans don't test them again. var revBackfill []string @@ -500,6 +500,13 @@ func (s *Scanner) Scan(ctx context.Context, lib catalog.Library) (_ *ScanResult, if r.names && (md.ProbeErr == nil || old.ScanError == problemProbe) && (!partNamed(b, md) || tagsRead(r.last)) { pathBackfill[b.RelPath] = readNames(b, md, r.last) } + // A last file that won't open waits the same way as a primary file + // ffprobe rejects, below: until the book is indexed again (its files + // changed, a Re-read), not with two reads on every scan. Its title + // stays the one stored, never one guessed without those tags. + if r.names && partNamed(b, md) && unopened(r.last) { + failedBackfill[b.RelPath] = old.IndexedAt + } // Names or hints left waiting on ffprobe, which rejects the file's // data where the index read it: the same bytes are rejected again, // so the read is remembered until the book is indexed again @@ -816,8 +823,8 @@ func (s *Scanner) Scan(ctx context.Context, lib catalog.Library) (_ *ScanResult, // Rows indexed before 0067 haven't had their ASIN, ISBN and language // tags read: the same read, and they wait with the names, as the // hints only ffprobe reads (an M4B's mdta items) would be recorded as none. - // A title that may be the album naming the series (before revision 2) - // or a leaf that states a series (before revision 3: + // A book a newer revision may read otherwise (an album naming the + // series, a structured leaf, a book of several files: // catalog.Signature.NamesCheck) is the same read. readPath, readHints := old.PathCheck == catalog.PathRead || old.NamesCheck, old.HintsUnchecked if old.TagReadFailed { @@ -1117,6 +1124,12 @@ func tagsRead(md *metadata.Metadata) bool { return md != nil && md.OpenErr == nil && !md.TagsUnread() } +// unopened reports whether md is a file's reading whose open failed +// (OpenErr), not one a Stop or a time limit cut short. +func unopened(md *metadata.Metadata) bool { + return md != nil && md.OpenErr != nil +} + // setNames sets b's title, author, series and position (readNames), its // narrator and its tag hints (the ASIN, ISBN and language the tags give, never // its identifiers) from md, its primary file's tags (nil for none), and last, From b0a9f5623ede34f117096d6b4a292ec809a4691d Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 20:10:19 +0000 Subject: [PATCH 15/16] Keep the album beside a folder named by a code A folder such as "HP1", an ASIN or an ISBN shares no word with the album, so a book with chapter-name tags in one took the code as its title. Main kept the album. Part of #272. --- CONVENTIONS.md | 2 +- internal/metadata/metadata.go | 12 +++++++++--- internal/metadata/metadata_test.go | 5 +++++ 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 19812a11f..4606633ae 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -2457,7 +2457,7 @@ every session. CLAUDE.md keeps a one-line index of these topics. Modern Prometheus" in "Frankenstein". Tags that name no chapter (`chapterNamed`: filename tags such as "Part 01.mp3", track labels, the album and a number, "The Gunslinger 01"), a folder that names no title (`untitledFolder`: a bare number "03", a volume label "Book One", "Books 1-3", or what it - holds, `containerFolder`: "Files", "MP3", "Unabridged"), a numbered slot (`folderSlot`: "The Dark + holds, `containerFolder`: "Files", "MP3", "Unabridged", or a code, `codeFolder`: "HP1", an ASIN, an ISBN), a numbered slot (`folderSlot`: "The Dark Tower 1", "Mistborn Book One") or the author tag ("Andy Weir", a book straight in its author's folder), and tags numbering one name in turn (`numberedAlike`: "Harry Potter: Philosopher's Stone 01" to "... 17"), leave the album in place; without an album a folder that names no title diff --git a/internal/metadata/metadata.go b/internal/metadata/metadata.go index 875be77bf..5b30487e6 100644 --- a/internal/metadata/metadata.go +++ b/internal/metadata/metadata.go @@ -847,12 +847,13 @@ func (m *Metadata) folderNamesTag(pathTitle string) bool { // untitledFolder reports whether a book's folder name (pathTitle) names no // title of its own: a track label or a bare number ("03"), a volume marker -// or label ("Book 3", "Book One", "Books 1-3": volumeFolder) or what it holds -// ("Files", "MP3", "Unabridged": containerFolder). +// or label ("Book 3", "Book One", "Books 1-3": volumeFolder), what it holds +// ("Files", "MP3", "Unabridged": containerFolder) or a code for the book +// ("HP1", an ASIN or an ISBN: codeFolder). func untitledFolder(pathTitle string) bool { folder := strings.TrimSpace(cleanTag(pathTitle)) return IsGenericTitle(folder) || volumeMarker(pathTitle) || volumeFolder.MatchString(folder) || - containerFolder.MatchString(folder) + containerFolder.MatchString(folder) || codeFolder.MatchString(folder) } // chapterNamed reports whether a title tag of one of a book's files names a @@ -885,6 +886,11 @@ var folderSlot = regexp.MustCompile(`\s(?:` + volumeLabel + `|#?\d{1,3})$`) // book ("Files", "MP3", "Audiobook", "Unabridged", "New Folder"). var containerFolder = regexp.MustCompile(`^(?i:files?|mp3s?|m4[ab]s?|audio|audio ?books?|unabridged|abridged|complete|full|media|tracks?|chapters?|parts?|discs?|cds?|(?:new )?folder|untitled|unknown)$`) +// codeFolder matches a folder named by a code rather than a title: a short +// abbreviation and a number ("HP1", "LOTR2"), an ASIN ("B00ABCDEFG") or an +// ISBN ("9780441013593"). +var codeFolder = regexp.MustCompile(`^(?:[A-Za-z]{1,5}\d{1,3}|B0[0-9A-Z]{8}|(?:97[89])?\d{9}[\dXx])$`) + // trailingTrack is a track number ending a title tag ("Philosopher's Stone 01"). var trailingTrack = regexp.MustCompile(`[\s._-]+\d{1,3}$`) diff --git a/internal/metadata/metadata_test.go b/internal/metadata/metadata_test.go index a5193b551..e9f28ba69 100644 --- a/internal/metadata/metadata_test.go +++ b/internal/metadata/metadata_test.go @@ -395,6 +395,11 @@ func TestPartsTitle(t *testing.T) { {"series album, numbered book tags, container folder", "Harry Potter", "Harry Potter: Philosopher's Stone 01", "Files", "Harry Potter: Philosopher's Stone 17", "Harry Potter"}, {"numbered book tags keep the album", "Harry Potter", "Philosopher's Stone 01", "Sorcerer Rip", "Philosopher's Stone 17", "Harry Potter"}, {"no album, container folder keeps the tag", "", "Ravens", "MP3", "The Peddler", "Ravens"}, + // A folder named by a code (an abbreviation and a number, an ASIN, an + // ISBN) names no title either. + {"abbreviated folder keeps the album", "Harry Potter and the Philosopher's Stone", "The Boy Who Lived", "HP1", "The Vanishing Glass", "Harry Potter and the Philosopher's Stone"}, + {"ASIN folder keeps the album", "Project Hail Mary", "Chapter One: Ryland", "B08GB58KD5", "Chapter Thirty", "Project Hail Mary"}, + {"ISBN folder keeps the album", "Dune", "Prophecy", "9780441013593", "Arrakis", "Dune"}, {"no title tag", "Main Street", "", "Main Street", unread, "Main Street"}, // A box set's album beside each book's own title: the tail names the folder. {"tail names the folder", "The Expanse Box Set", "The Expanse Box Set: Leviathan Wakes", "Leviathan Wakes", unread, "The Expanse Box Set: Leviathan Wakes"}, From f9e66b7f9d02c5499a14a605326a98bad90929ac Mon Sep 17 00:00:00 2001 From: KodeStar Date: Sun, 22 Nov 2026 20:11:04 +0000 Subject: [PATCH 16/16] Leave accents out when TitlesShareWord compares an album and a folder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Shogun" and "Shōgun", or a decomposed folder name beside a composed tag, shared no word, so the folder's spelling replaced a correct album on a book with chapter-name tags. Part of #272. --- pkg/match/match.go | 14 ++++++++++++-- pkg/match/match_test.go | 2 ++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/pkg/match/match.go b/pkg/match/match.go index 677ee06f4..413b2b3d4 100644 --- a/pkg/match/match.go +++ b/pkg/match/match.go @@ -33,6 +33,8 @@ import ( "strings" "unicode" "unicode/utf8" + + "golang.org/x/text/unicode/norm" ) // Book is a candidate to match against (a server book, or any catalog entry). @@ -983,10 +985,18 @@ var titleStopwords = map[string]bool{ // articles and joining words. The scanner uses this to preserve an album // whose title is a fuller spelling of the book folder's. Unlike tokenize it // keeps letters in any script, numbers and one-letter words, since a folder -// name is weighed here, not scored against a candidate. +// name is weighed here, not scored against a candidate. Accents are left out +// (NFKD, as SeriesKey), so "Shogun" shares its word with "Shōgun" and a +// decomposed spelling with a composed one. func TitlesShareWord(a, b string) bool { words := func(s string) []string { - return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { + bare := strings.Map(func(r rune) rune { + if unicode.Is(unicode.Mn, r) { + return -1 + } + return r + }, norm.NFKD.String(strings.ToLower(s))) + return strings.FieldsFunc(bare, func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsNumber(r) && !unicode.IsMark(r) }) } diff --git a/pkg/match/match_test.go b/pkg/match/match_test.go index bced11a39..4dbaf7e51 100644 --- a/pkg/match/match_test.go +++ b/pkg/match/match_test.go @@ -566,6 +566,8 @@ func TestTitlesShareWord(t *testing.T) { {"Catch 22", "Fahrenheit 451", false}, {"Book 1", "Volume 1", true}, {"", "Anything", false}, + {"Shogun", "Shōgun", true}, + {"Les Mise\u0301rables", "Les Misérables, Volume 1", true}, } { if got := TitlesShareWord(c.a, c.b); got != c.want { t.Errorf("TitlesShareWord(%q, %q) = %v, want %v", c.a, c.b, got, c.want)