* fix(ebooks): fold author hint into metadata search query
The ebook enricher loaded each item's author but buildEbookSearchQuery
dropped it, and metadata.SearchQuery had no field to carry it — so the
plugin only ever received the title. Title-only searches collide or miss,
leaving items without metadata or a cover.
Add SearchQuery.Author and fold it into the plugin search query text
(the SearchMetadataRequest contract carries a single free-text Query, so
no proto change is needed). Gated to callers that set Author (ebooks);
movie/TV search is unchanged.
Verified live against OpenLibrary/GoogleBooks: improves disambiguation on
clean titles. Note: messy filename-derived titles (series prefixes,
trailing "(… Book N)") still need title normalization, and a large tail
of niche/self-published ebooks is simply absent from the free sources —
neither is addressed here.
AI-use disclosure: authored with Claude Code.
(cherry picked from commit ba1265909c4fb87e1a8eab64b0b0c183aa95acc1)
* feat(scanner): extract MOBI/AZW/AZW3 metadata from EXTH headers
These formats previously had no parser — parseEbookFile returned only the
format string, so title fell back to the filename with no author and no
ISBN, leaving ~21k books unmatchable by the metadata enricher.
Parse the Palm Database container (PDB header → record 0 → PalmDOC +
MOBI header → EXTH block) and extract title, authors, ISBN, publisher,
and language. EXTH is located by its magic rather than the header flag,
and field offsets (encoding @12, full-name @0x44/0x48) were verified
against real .mobi/.azw3 files.
Verified live against real library files:
azw3 → title "The Sea", author "A H Lee"
mobi → title "Brotherband 3: The Hunters", author "John Flanagan",
ISBN 9781742750637
AI-use disclosure: authored with Claude Code.
(cherry picked from commit 7af194b711de97bc79855f08a9a4f9732c49db74)
* fix(ebooks): recover author from path and clean provider search title
- ebookAuthorFromPath: recover an author for ".../<Author>/<Title>/<Title> -
<Author>.ext" layouts when the file embeds none, gated on two agreeing
path signals (grandparent dir == filename suffix) so magazines/courses
never get a junk author; strip the suffix from a path-derived title.
- cleanEbookSearchTitle: normalize filesystem-mangled titles before search
(underscore->space, drop trailing " - <author>") to lift hit rate.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit 36a16cb58c3e5276aa4c0bdf8577008070f6abea)
* fix(scanner): gate path-author on person-name shape
ebookAuthorFromPath's grandparent==suffix corroboration also matched
inverted layouts ("<Title>/<Author>/<Author> - <Title>"), assigning the
title as the author. Require the candidate directory to look like a person
name (comma form, or all-capitalized tokens plus name particles) so series
and title folders ("De legenden van de Alfen") are rejected, and return the
canonical directory form for proper casing.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit ff720bd268a23bff0e94c70f15cb7ecfb8efcb1f)
* fix(ebooks): strip series/book-number parentheticals from search title
cleanEbookSearchTitle now peels trailing "(... Book N)", "[#3]", "(2019)"
groups that don't belong in a provider title query, while leaving
meaningful parentheticals ("(Illustrated)") intact. Enrichment-side only.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit 2273636c04fd9ef483003a9558972a2104fdd3a6)
* fix(ebooks): keep volume number in search title and dedup provider IDs
Two distinct ebooks (e.g. series volumes named only by series + book
number) were collapsing onto a single provider work, then fighting over
the same media_item_provider_ids row:
- cleanEbookSearchTitle stripped trailing "(... Book N)" / "[#3]" groups
entirely, so every volume of a series searched as the bare series name
and matched the same provider work. The plugin search contract carries
only a single free-text Query, so the volume number is now UNWRAPPED
into the query (brackets dropped, words kept) instead of discarded,
giving distinct volumes distinct searches. Bare-year groups are still
dropped (SearchQuery.Year carries them); meaningful parentheticals
("(Illustrated)") still survive.
- collectEbookMetadata now consults FindContentIDByProviderIDs before
accumulating a search-result provider ID. An ID already owned by a
different content item is skipped, so the loser is not mis-tagged with
the winner's metadata and ReplaceByContentID no longer violates the
(provider, provider_id, item_type) unique constraint. The previous
behavior logged duplicate-key errors every sweep and re-enriched the
failing item forever (CPU/RAM churn). A failed ownership check is
surfaced as a provider error so the item retries rather than terminally
stamping as "no match".
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 942fdef6cb0e167b2d9223e9a968b3010b7b3ec8)
* fix(ebooks): address CodeRabbit review on PR #185
- cleanEbookSearchTitle: anchor author-suffix strip to a trailing match
(optionally followed by a series/volume parenthetical) so a mid-title
" - <token>" no longer truncates valid title text
- ebook scan: strip the recovered author suffix using normalized comparison
so case/spacing variants (e.g. "a. f. carter") don't leave a duplicate
- parseMOBIEXTH: bound parsing to the declared EXTH length so a corrupt
record count can't read full-text bytes as junk metadata
- add regression test for a non-trailing " - <token>" in the title
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 0f45af8143e04dfd5b4a5ee3e949dcd943eedbd1)
* fix(audiobooks): pass author in search query and retry on provider errors
Set SearchQuery.Author so the host adapter folds author into the
plugin free-text query (parity with ebooks). Track provider errors
during enrichment; when nothing matched and a provider errored, return
an error without stamping last_refreshed so the sweep retries instead
of terminally burning the item on a transient failure.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit f45dd2104c5d6415324e80f91f6684bc39858459)
* fix(scanner): consolidate fragmented multi-file audiobook content_ids on rescan
audiobookFolderShouldSkip used ListByObservedRootPath which returns all
files for a root path regardless of content_id. When a multi-file audiobook
had files fragmented across multiple content_ids (e.g. from concurrent
refreshes), the file count matched disk so the skip check returned true
and the reconcile never ran to merge them.
Now verifies all DB files share the same content_id before skipping; any
fragmentation forces a full reconcile which consolidates to one content_id
via FindContentIDByRootPath → upsertAudiobookMediaFiles.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
(cherry picked from commit e91c33e88a7d09e802e6afd8af246c6c954d0498)
* fix(ingest): skip concurrent match drainer for audiobook/podcast/ebook/manga libraries
The concurrent scoped match drainer ran during scan for all library types.
For audiobook libraries, the scanner assigns content_ids by folder root
(one item per multi-file folder). Running the drainer concurrently caused
it to process files with content_id=NULL (cleared by complete refresh)
as individual items, creating one media_item per file instead of one per
folder. This manifested as 41-file audiobooks fragmenting into dozens of
orphaned single-file content_ids on every refresh.
These library types use scanner-driven grouping; the post-scan drain step
handles them correctly. Returning nil matchScopes skips the concurrent
drainer entirely for these types.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
(cherry picked from commit 93ae9d22ce315874fa22a958b88ca1766075695f)
* fix(abs): match real audiobookshelf auth + session-sync contract
Align the ABS-compat auth flow with real audiobookshelf (v2.26+) so
third-party clients (yaabsa, Plappa, native iOS) authenticate and sync
playback correctly:
- login/refresh: always emit user.accessToken; x-return-tokens gates
only the refresh token (body vs HttpOnly refresh_token cookie)
- /auth/refresh returns the full login envelope (was a thin token map)
- /me returns the full user object (toOldJSONForBrowser), shared with
login/authorize via a single absUserObject() builder
- /logout returns 200 {redirect_url:null} and clears the cookie (was 204)
- add POST /session/{sid}/sync (real ABS heartbeat path); it was
PATCH-only, so the official client's sync POST 404'd and playback
progress never synced
Verified against advplyr/audiobookshelf server/{Auth.js,models/User.js,
controllers,routers}. Unit tests updated/added; full abs suite green.
Not yet live-verified.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 336e932471d4be021d82299106a120611783836a)
* fix(abs): conform browse/list items to real audiobookshelf minified shape
Strict ABS clients (yaabsa, Plappa) crash or drop items when the browse
list shape only approximates real audiobookshelf. Match the serializers:
- add media.id + media.libraryItemId (= ContentID) to LibraryItemMedia;
yaabsa BookMedia.id is required non-null and was missing → the whole
item failed to parse ("Null is not a subtype of String")
- rebuild the minified list shape to LibraryItem.toOldJSONMinified +
Book.toOldJSONMinified + oldMetadataToJSONMinified key-for-key (ino,
path, isFile, numFiles/size, media.{id,tags,numTracks,numAudioFiles,
numChapters,size,ebookFormat}, flat author/series metadata)
- force media.numTracks/numAudioFiles >= 1 in the browse projection so
Plappa doesn't drop items reporting 0 audio files
- default /items list to minified (real ABS list is always minified);
minified=0 opts into the full shape
Verified against advplyr/audiobookshelf models/{Book,LibraryItem}.js.
Adds minified_test.go key-set conformance guards; abs suite green.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 6c9387a8c4b60be3dbe541049ed8c06344b10717)
* fix(abs): conform /items/{id} detail to real audiobookshelf expanded shape
Match real audiobookshelf LibraryItem.toOldJSONExpanded +
Book.toOldJSONExpanded + oldMetadataToJSONExpanded so strict clients
decode the item-detail page with the same model they use elsewhere:
- add expanded outer keys to LibraryItem (oldLibraryItemId, lastScan,
scanVersion, libraryFiles, size) and populate libraryFiles + summed
size from the item's media files in the detail builder
- add media.size (Book.toOldJSONExpanded)
- make the typed Metadata the full expanded superset: subtitle,
titleIgnorePrefix, authorName, authorNameLF, narratorName, seriesName,
descriptionPlain, publishedDate, asin, language, abridged; drop the
omitempty that previously dropped description/publishedYear/isbn/
publisher when empty (a missing key crashes strict clients)
Verified against advplyr/audiobookshelf models/Book.js + LibraryItem.js.
Adds items_detail_test.go expanded key-set guard; abs suite green.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 8bd485f0291e9db9f32e13a68609a68ee8a945ec)
* fix(abs): conform authors/series endpoints to real audiobookshelf shapes
Match the real audiobookshelf serializers so strict clients decode the
authors/series browse + detail responses:
- GET /libraries/{id}/authors now branches like LibraryController.getAuthors:
bare { authors: [...] } when not paginated, paged { results, total, ... }
only when limit+page are present (was always paged → clients keying on
`authors` got keyNotFound)
- author objects carry the full Author.toOldJSON key set (id, asin, name,
description, imagePath, libraryId, addedAt, updatedAt, numBooks); silo has
no analog for asin/description/imagePath/timestamps so they are null/0
- series objects carry the full Series.toOldJSON key set (adds
nameIgnorePrefix, description, libraryId, addedAt, updatedAt)
- series/author books are now FULL minified library items (real ABS shape)
instead of thin {id,media:{metadata:{title}}} stubs that crash Plappa;
author items moved to the real-ABS `libraryItems` key
Verified against advplyr/audiobookshelf controllers/LibraryController.js and
models/{Author,Series}.js. Tests updated + envelope-branch guard added; abs
suite green.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 8a22eb0900ed881d500ded315a508e1a07da14f3)
* fix(abs): add libraryId to collection/playlist objects (real ABS shape)
Real audiobookshelf Collection.toOldJSON and Playlist.toOldJSON both carry
a libraryId; silo's emitters omitted it, so a strict client modeling the
object with a required libraryId crashed. silo collections/playlists are
cross-library user-personal, so emit the virtual audiobook library id.
The books[]/items[] entries already carry the full LibraryItem shape and
inherit the browse-conformance fixes (media.id etc.). Envelopes were
already correct (paged for library-scoped, {collections}/{playlists} for
global).
Verified against advplyr/audiobookshelf models/{Collection,Playlist}.js.
Envelope key-set tests updated; abs suite green.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit f7d2ff0565f05c3a6ef7f36f2b1f252bd373fa7a)
* fix(abs): conform library object + /libraries/{id} to real audiobookshelf
The library object was only {id,name,mediaType}; real audiobookshelf
Library.toOldJSON has 12 keys, so a strict client decoding the library
model crashed on the missing ones. Also GET /libraries/{id} always wrapped
the object in { library: ... }, but real ABS returns it directly unless
?include=filterdata is requested.
- audiobookLibraryMap now emits the full Library.toOldJSON shape (folders[]
as LibraryFolder.toOldJSON, displayOrder, icon, provider, settings,
lastScan, lastScanVersion, createdAt, lastUpdate). This also enriches the
libraries[] on the login envelope, which shares the builder.
- handleLibraryDetail returns the library object DIRECTLY without include,
and wraps in { filterdata, issues, numUserPlaylists,
customMetadataProviders, library } (adds the missing
customMetadataProviders) with include=filterdata.
GET /libraries already returned { libraries: [...] } (correct). Verified
against advplyr/audiobookshelf models/Library.js +
controllers/LibraryController.js. Adds libraries_shape_test.go; abs suite green.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit d05a2f2af1caf21a4ad04577a4787ba02cff091c)
* fix(abs): conform personalized recent-series shelf to real ABS series shape
The /libraries/{id}/personalized "Recent Series" shelf emitted thin
{id,name,numBooks,libraryId,books:[]} entities with an always-empty cover
stack. Emit the full real-ABS series object (seriesObjectABS, adds
nameIgnorePrefix/description/addedAt/updatedAt) with minified book items
(seriesBookMinified) — the same shape as /libraries/{id}/series so the
shelf card decodes identically and shows real covers.
Book shelves already used full minified items; the shelves array is a bare
array (matches real ABS getUserPersonalizedShelves). abs suite green.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 7c586f8c923cbc481f6f94e304af48dee379a999)
* fix(abs): conform listening-sessions to real audiobookshelf PlaybackSession shape
silo's /me/listening-sessions returned a thin 5-field session object
(id, libraryItemId, userId, timeListening, currentTime) wrapped in the
generic pagedEnvelope shape ({results,sortBy,filterBy,minified}). Real
audiobookshelf clients (Flutter/Swift strict decoders) expect the
MeController.getListeningSessions envelope
({total,numPages,page,itemsPerPage,sessions}) and each session to carry
the full PlaybackSession.toJSON() key set, so the missing keys (notably
mediaType, mediaMetadata, displayTitle, displayAuthor, coverPath,
duration, chapters, deviceInfo, playMethod, mediaPlayer, serverVersion,
date, dayOfWeek, startTime, startedAt, updatedAt, libraryId, bookId,
episodeId) crashed with keyNotFound errors.
Both handleListeningSessions and handleListeningSessionDetail now build
the response via a shared sessionToABS() that reuses
buildSiloPlayMediaMetadata (already used by /play) to hydrate
mediaMetadata/displayTitle/displayAuthor from MediaStore, batching
lookups via GetAudiobooksByIDs for the list endpoint. Lookups are
best-effort: a missing/inaccessible item falls back to a stub
MediaItem so every key is still emitted, never a crash.
Verified against advplyr/audiobookshelf server/controllers/MeController.js
(getListeningSessions) and server/objects/PlaybackSession.js (toJSON())
on GitHub master.
Known placeholders (real ABS fields we can't populate without extra
cost): chapters (empty array — would require a per-session media-files
fetch), duration (0 — total book duration isn't tracked on the session
row), startTime (0 — not persisted separately from currentTime),
deviceInfo (static "unknown" device, matching the /play endpoint's
existing placeholder — no device info is persisted per session).
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 9471497c99b96c8d3defc6c8112c913f7c55924b)
* feat(abs): add offline session sync endpoints (/session/local, /session/local-all)
The official ABS mobile app records playback while offline and POSTs those
PlaybackSession objects back on reconnect via SessionController.syncLocal and
syncLocalSessions. silo was missing both endpoints, so offline listening
progress was silently lost. Add them to the bearerAuth-protected session group
(both /abs/api and /api prefixes) alongside /session/{sid}/sync and /close.
POST /session/local decodes one PlaybackSession and updates the caller's resume
position via ProgressStore.UpdateProgressPosition (the same call handleSessionSync
uses), emitting user_item_progress_updated. POST /session/local-all decodes
{sessions:[...]} and loops each robustly — a malformed or unknown item marks that
one result failed without sinking the batch — returning {results:[...]}. No new
store persistence or migration; podcast/episode sessions are accepted as no-ops.
Verified against advplyr/audiobookshelf server/controllers/SessionController.js
and server/managers/PlaybackSessionManager.js.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 008a4df948d855a4bfe62b24f89bfc484f088033)
* fix(abs): conform library search + items-in-progress to real audiobookshelf
Real ABS's libraryItemsBookFilters.search() (delegated from
LibraryController.search) returns { book, narrators, tags, genres,
series, authors } with no "podcast" key for a book library, and each
book entry is only { libraryItem } — no matchKey/matchText, which our
handler was inventing. Search now matches those keys, drops the
fabricated matchKey/matchText fields, and best-effort populates
authors/series buckets via client-side substring filtering over the
existing aggregate listers (narrators/tags/genres stay empty-but-present
since silo has no backing aggregation query for them yet).
MeController.getAllLibraryItemsInProgress wraps items as
{ ...libraryItem.toOldJSONMinified(), progressLastUpdate }; our handler
was emitting a hand-rolled subset of fields plus a nested
userMediaProgress object that doesn't exist in the real response.
items-in-progress now reuses the existing Minify() projection and merges
a flat progressLastUpdate (ms) field to match.
Verified against advplyr/audiobookshelf controllers/{Library,Me}Controller.js
and server/utils/queries/{libraryItemsBookFilters,authorFilters}.js.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 998ff55f3cf27d504f0e5aec8c7c29fa57f10247)
* fix(abs): /ping returns success:true and /status carries authMethods
The ABS apps validate a server address by reading response.success from
GET /ping; silo returned {pong:true,...} with no `success`, so the app
reported "unable to reach" even though the server responded 200. Also
/status was missing authMethods/authFormData, which the app reads to render
the login form.
- /ping now includes {"success": true} (pong/server/version kept as extras)
- /status now returns {app,serverVersion,isInit,language,authMethods,
authFormData} matching real audiobookshelf Server.js
Verified against advplyr/audiobookshelf server/Server.js. Adds
ping_status_test.go; abs suite green.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit df732d09355303608bc4d5fc2138555e37497a02)
* fix(abs): mount login + auth/refresh under /api prefix
Clients that post to /api/login (and /api/auth/refresh) got a 404 because
login/refresh were only mounted at root and /abs/api — while the rest of the
authenticated ABS surface (/api/me, /api/authorize, /api/libraries, covers)
is served under both /api and /abs/api. The 404 surfaced in the client as a
generic "unknown error occurred" on sign-in.
Mount /login and /auth/refresh under all three prefixes ("", /api, /abs/api),
matching the authenticated groups.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 18071e180b02131cda354303eadd1ff3a0708065)
* fix(abs): accept form-encoded login bodies (not just JSON)
Real audiobookshelf (express body-parser + passport local) accepts both
application/json and application/x-www-form-urlencoded credential bodies.
Silo only json-decoded the body, so a form-encoded client got 400 "invalid
request body" — surfaced in the app as a generic "unknown error" on sign-in
(confirmed live: JSON creds -> 200, identical form-encoded creds -> 400).
Buffer the body once, try JSON, then fall back to url.ParseQuery for the
form-encoded case.
Adds login_body_test.go (form + JSON both reach the validator). abs suite green.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 408dc33debb7a7ee363778094511ccfdd1ee70d2)
* fix(abs): emit full real-ABS serverSettings (OpenID/auth fields)
silo's login/authorize serverSettings omitted the auth + OpenID fields that
real audiobookshelf ServerSettings.toJSONForBrowser includes
(authLoginCustomMessage, authOpenID*, rateLimitLogin*, backupPath,
allowedOrigins). OIDC-aware strict clients (Prologue, iOS/Swift) decode
serverSettings into a model that requires those keys, so their absence throws
keyNotFound and the ENTIRE login response fails to decode — the client stays
on the login screen with a generic "unknown error" even though the server
returned 200. Simpler clients that don't model OpenID were unaffected.
Emit real ABS's OIDC-disabled defaults; authActiveAuthMethods still advertises
only "local" so no client initiates the OpenID flow.
Diagnosed from a packet capture (Prologue posts /login? with X-Return-Tokens
and gets a 200 it can't decode) + real ABS ServerSettings.js. Verified against
advplyr/audiobookshelf.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 283826c952824e97233e46e057f37385ddc3054b)
* fix(abs): GET /me returns the real display username, not the userID
/me built its user object from the token claims and passed the numeric
userID as the username, so clients saw "98" instead of "puksthepirate".
Login gets the display name from the credential validator, but /me only has
the token, so it needs a lookup.
Add an optional UsernameResolver to the abs Dependencies; wire it from the
concrete SiloCredValidator (which holds the pgx pool) via a new
ResolveUsername method that mirrors Validate's display-name logic — the
profile name when a profile is set and named, else the account username.
handleMe uses it and falls back to the userID when unresolved.
abs package compiles + tests pass; the audiobooks package (service.go,
cred_validator.go) could not be linked locally (pre-existing bimg/libvips
pkg-config gap) and is validated at the Docker build.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 39ff3e3350aad087757f7fb0e94d5a7f10c08ae5)
* fix(abs): always emit AudioTrack keys + correct media.duration
Two item-detail issues that made Prologue report "Unable to load book
contents" (can't press Start Listening):
- AudioTrack used omitempty on chapters/metaTags/format/bitRate/codec/
metadata/etc, so empty values dropped those keys. Real ABS AudioFile/
AudioTrack always emit them; strict clients (Prologue, yaabsa) decode
tracks into a required-field model and throw keyNotFound on the missing
keys, failing the whole track decode. Removed omitempty and emit
chapters/metaTags as [] / {} (non-nil) in both track builders.
- media.duration used the item's Runtime, which is often stale/mis-scanned
(e.g. 222s for a 3.7h book) and desyncs the player scrubber. Now sum the
track durations (real ABS: sum of audio file durations), falling back to
Runtime only when there are no tracks.
Verified against advplyr/audiobookshelf models/Book.js (AudioFile/AudioTrack)
via a live packet capture of Prologue's item-detail decode failure. abs
suite green.
AI-use: implemented with Claude Code (Opus 4.8).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 8210ed2fc63e782f158b4168ef693e671ae19638)
* perf(abs): push down library browse filters + author counts MV
The ABS audiobook library-serving path was slow on large libraries
(~255k items): /libraries/{id}/items?filter=authors.{id} loaded and
hydrated the whole library into Go before filtering (~4.8s each), and
/libraries/{id}/authors ran a full GroupAggregate + COUNT(DISTINCT)
per page (~53s full sync) — slow enough to trip ABS client sync
timeouts (e.g. Prologue).
- Push author/series/narrator/no-series filters into indexed SQL
EXISTS predicates in ListAudiobooks; paginate + COUNT in SQL.
Semantically equivalent to the prior Go-side filter (kind=7 author,
kind=8 narrator, exact-case match, no-series sentinel).
- Add covering index media_items(content_id, type) so the count/list
type check runs index-only (CONCURRENTLY, NO TRANSACTION — no
write-lock on the live table).
- Serve /authors from a materialized view (abs_audiobook_author_counts)
refreshed every 15min, with a live-query fallback when the view is
empty/unrefreshed so the endpoint never blanks on a fresh deploy.
Conformance preserved: keeps authorObjectABS/seriesObjectABS shapes and
the limit&&page envelope decision; adds a regression test for the
bare {authors:[...]} envelope on limit-only requests.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 0d55754051dd3ad016b3cec6a0921307071d3219)
* perf(abs): index-back audiobook search via trigram GIN
SearchAudiobooks matched the raw media_items.title with ILIKE '%q%'
OR'd with an author/narrator EXISTS. The un-indexed raw-title column
plus the OR forced a full seq scan of the ~255k-item library on every
search (~560ms on library 18).
Reshape into a UNION of two index-driven arms that reuse the search
infrastructure the rest of the catalog already relies on: the title arm
matches media_items.title_normalized (idx_media_items_title_normalized_trgm)
via the shared normalize_search_text(), the people arm matches people.name
(idx_people_name_trgm). GROUP BY content_id keeps the best rank when an
item matches both; a normalize_search_text($2) <> '' guard stops a
punctuation-only query from degenerating into ILIKE '%%'.
No new index or migration — the trigram indexes already existed and were
simply unused. ~560ms -> ~35ms, both indexes engaged, no seq scan.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 98bbd1712719ecd03e4db87f840774cec788f177)
* perf(abs): index-ordered item paging + cached library count
The unfiltered /libraries/{id}/items path that ABS clients page through
to sync a library recomputed COUNT(*) over the whole library on every
page (~150ms each) and ordered by LOWER(sort_title), LOWER(title) — an
expression matching no index, forcing a full in-memory sort of all
~255k rows per page (~324ms shallow, ~543ms deep). A full sync is
thousands of pages, so both costs dominated indexing time.
- Order by lower(coalesce(nullif(btrim(sort_title),''), title)),
content_id so the page is served by an ordered index scan on the
existing idx_media_items_sort_key (~324ms -> ~1ms). content_id (PK)
is a stable tiebreaker, making sequential pagination deterministic —
the prior ordering could skip/repeat rows when sort keys collided.
- Memoize the per-page COUNT in a 60s TTL cache keyed on the fully
rendered count SQL + bound args, so it covers every input the WHERE
depends on (library, pushed-down filter, all access predicates) and
can't drift as access logic evolves. Expired entries swept on write.
No new index or migration — reuses idx_media_items_sort_key.
total may lag up to 60s during an active scan; clients re-sync.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 32e26c2f99a1ffc071f600071c2ea7ddcd3397b4)
* fix(abs): address PR review — access-aware authors, offline progress create, cookie refresh, body limits
- media_store: ListLibraryAuthors bypassed per-item access when reading the
author materialized view (keyed by library only), leaking authors of books
hidden by a content-rating cap or excluded media types. Take the access-aware
live path whenever the filter carries an item-level predicate.
- session_local: offline sync used UPDATE-only UpdateProgressPosition, so a book
listened to entirely offline (no progress row yet) had its position silently
dropped while still reporting progressSynced. Create the row via UpsertProgress
when none exists; keep the monotonic update path for existing rows.
- login: handleRefresh never read the refresh_token cookie, so cookie-flow ABS
clients got 400 refreshToken required once the access token expired. Read the
cookie as a third source after header and body.
- session_local: cap /session/local and /session/local-all request bodies at
1 MiB via io.LimitReader, matching the rest of the package.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
1256 lines
38 KiB
Go
1256 lines
38 KiB
Go
package scanner
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/Silo-Server/silo-server/internal/idgen"
|
|
"github.com/Silo-Server/silo-server/internal/models"
|
|
"github.com/Silo-Server/silo-server/internal/titleutil"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
)
|
|
|
|
type filesystemRootContentFinder interface {
|
|
FindContentIDByRootPath(ctx context.Context, folderID int, rootPath, preferredType string) (string, error)
|
|
}
|
|
|
|
type filesystemMediaItemWriter interface {
|
|
Upsert(ctx context.Context, item *models.MediaItem) error
|
|
}
|
|
|
|
type audiobookPosterExec interface {
|
|
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
|
|
}
|
|
|
|
type audiobookPosterPathReader interface {
|
|
GetPosterPath(ctx context.Context, contentID string) (string, error)
|
|
}
|
|
|
|
const audiobookDuplicateCandidateSQL = `
|
|
SELECT mi.content_id, mi.title
|
|
FROM media_items mi
|
|
JOIN item_people ipa ON ipa.content_id = mi.content_id AND ipa.kind = 7
|
|
JOIN people pa ON pa.id = ipa.person_id AND LOWER(pa.name) = LOWER($1)
|
|
JOIN item_people ipn ON ipn.content_id = mi.content_id AND ipn.kind = 8
|
|
JOIN people pn ON pn.id = ipn.person_id AND LOWER(pn.name) = LOWER($2)
|
|
JOIN LATERAL (
|
|
SELECT COALESCE(SUM(mf.duration), 0) AS dur
|
|
FROM media_files mf WHERE mf.content_id = mi.content_id
|
|
) f ON TRUE
|
|
JOIN LATERAL (
|
|
SELECT btrim(regexp_replace(
|
|
regexp_replace(lower(mi.title), '[^a-z0-9]+', ' ', 'g'),
|
|
'[[:space:]]+', ' ', 'g'
|
|
)) AS normalized_title
|
|
) t ON TRUE
|
|
WHERE mi.type = 'audiobook'
|
|
AND mi.year = $3
|
|
AND f.dur > 0
|
|
AND ABS(f.dur - $4) <= $5
|
|
AND (
|
|
t.normalized_title = $6
|
|
OR t.normalized_title LIKE $6 || ' %'
|
|
OR $6 LIKE t.normalized_title || ' %'
|
|
)
|
|
ORDER BY ABS(f.dur - $4), LENGTH(mi.title), mi.content_id
|
|
LIMIT 25
|
|
`
|
|
|
|
// audiobookDiskFile is the on-disk projection used by audiobookFolderUnchanged.
|
|
// Path is the absolute file path; Size and ModTime come from os.Stat.
|
|
type audiobookDiskFile struct {
|
|
Path string
|
|
Size int64
|
|
ModTime time.Time
|
|
}
|
|
|
|
// audiobookFolderUnchanged reports whether the audio files on disk match the
|
|
// existing media_files rows for the same folder one-for-one on path, size,
|
|
// and mtime. A new file, removed file, or any byte-level / mtime drift returns
|
|
// false so the caller falls through to a full reconcile.
|
|
//
|
|
// Comparison uses sameFileModifiedAt for mtime to absorb sub-second precision
|
|
// differences between filesystem reads.
|
|
func audiobookFolderUnchanged(existing []*models.MediaFile, onDisk []audiobookDiskFile) bool {
|
|
if len(existing) != len(onDisk) {
|
|
return false
|
|
}
|
|
byPath := make(map[string]*models.MediaFile, len(existing))
|
|
for _, mf := range existing {
|
|
byPath[mf.FilePath] = mf
|
|
}
|
|
for _, d := range onDisk {
|
|
mf, ok := byPath[d.Path]
|
|
if !ok {
|
|
return false
|
|
}
|
|
if mf.FileSize != d.Size {
|
|
return false
|
|
}
|
|
if mf.FileModifiedAt == nil || !sameFileModifiedAt(mf.FileModifiedAt, d.ModTime) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// audiobookFolderShouldSkip returns true when every audio file on disk in
|
|
// folderPath matches an existing media_files row by size + mtime AND the
|
|
// linked media_items row is in a non-unmatched status. False under any
|
|
// drift, missing row, or unmatched status — the caller then falls through
|
|
// to the full reconcile path.
|
|
//
|
|
// Errors are returned but the worker loop treats them as "do not skip".
|
|
func (s *Scanner) audiobookFolderShouldSkip(ctx context.Context, folder *models.MediaFolder, folderPath string) (string, bool, error) {
|
|
if s.fileRepo == nil || s.itemRepo == nil {
|
|
return "", false, nil
|
|
}
|
|
|
|
entries, err := os.ReadDir(folderPath)
|
|
if err != nil {
|
|
return "", false, fmt.Errorf("read folder: %w", err)
|
|
}
|
|
var onDisk []audiobookDiskFile
|
|
for _, e := range entries {
|
|
if e.IsDir() || !SupportsAudioFile(e.Name()) {
|
|
continue
|
|
}
|
|
full := filepath.Join(folderPath, e.Name())
|
|
info, statErr := os.Stat(full)
|
|
if statErr != nil {
|
|
return "", false, fmt.Errorf("stat %s: %w", full, statErr)
|
|
}
|
|
onDisk = append(onDisk, audiobookDiskFile{
|
|
Path: full,
|
|
Size: info.Size(),
|
|
ModTime: normalizeFileModifiedAt(info.ModTime()),
|
|
})
|
|
}
|
|
if len(onDisk) == 0 {
|
|
return "", false, nil
|
|
}
|
|
|
|
existing, err := s.fileRepo.ListByObservedRootPath(ctx, folder.ID, folderPath)
|
|
if err != nil {
|
|
return "", false, fmt.Errorf("list existing files: %w", err)
|
|
}
|
|
if !audiobookFolderUnchanged(existing, onDisk) {
|
|
return "", false, nil
|
|
}
|
|
|
|
contentID := existing[0].ContentID
|
|
if contentID == "" {
|
|
return "", false, nil
|
|
}
|
|
// All files must share the same content_id; fragmented folders need reconcile.
|
|
for _, mf := range existing[1:] {
|
|
if mf.ContentID != contentID {
|
|
return "", false, nil
|
|
}
|
|
}
|
|
items, err := s.itemRepo.GetByIDs(ctx, []string{contentID})
|
|
if err != nil {
|
|
return "", false, fmt.Errorf("get item for skip check: %w", err)
|
|
}
|
|
if len(items) == 0 || items[0] == nil {
|
|
return "", false, nil
|
|
}
|
|
if strings.TrimSpace(items[0].Title) == "" {
|
|
return "", false, nil
|
|
}
|
|
if strings.EqualFold(strings.TrimSpace(items[0].Status), "unmatched") {
|
|
return "", false, nil
|
|
}
|
|
return contentID, true, nil
|
|
}
|
|
|
|
// audiobookScanWorkers returns the configured number of parallel workers
|
|
// for audiobook reconciliation. Defaults to 8 — high enough to keep all
|
|
// cores busy on the ffprobe step (which dominates per-book wall time)
|
|
// without overwhelming a small server. Override with SILO_AUDIOBOOK_SCAN_WORKERS.
|
|
func audiobookScanWorkers() int {
|
|
if v := os.Getenv("SILO_AUDIOBOOK_SCAN_WORKERS"); v != "" {
|
|
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
|
return n
|
|
}
|
|
}
|
|
return 8
|
|
}
|
|
|
|
type audiobookRootScan struct {
|
|
root string
|
|
candidates []string
|
|
seenPaths map[string]bool
|
|
rootErr error
|
|
walkFailures int
|
|
}
|
|
|
|
func (r *audiobookRootScan) failed() bool {
|
|
return r.rootErr != nil || r.walkFailures > 0
|
|
}
|
|
|
|
func collectAudiobookRootScans(ctx context.Context, folderID int, roots []string) ([]audiobookRootScan, error) {
|
|
scans := make([]audiobookRootScan, 0, len(roots))
|
|
for _, root := range roots {
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
cleanRoot := filepath.Clean(strings.TrimSpace(root))
|
|
if cleanRoot == "" || cleanRoot == "." {
|
|
continue
|
|
}
|
|
scan := audiobookRootScan{
|
|
root: cleanRoot,
|
|
seenPaths: make(map[string]bool),
|
|
}
|
|
info, statErr := os.Stat(cleanRoot)
|
|
switch {
|
|
case statErr != nil:
|
|
scan.rootErr = fmt.Errorf("stat root: %w", statErr)
|
|
case !info.IsDir():
|
|
scan.rootErr = fmt.Errorf("root is not a directory after symlink resolution")
|
|
}
|
|
if statErr == nil && scan.rootErr == nil {
|
|
walkErr := filepath.WalkDir(cleanRoot, func(path string, d fs.DirEntry, walkErr error) error {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
if walkErr != nil {
|
|
scan.walkFailures++
|
|
slog.Warn("audiobook scan: walk error", "path", path, "error", walkErr)
|
|
return nil
|
|
}
|
|
if !d.IsDir() {
|
|
return nil
|
|
}
|
|
entries, err := os.ReadDir(path)
|
|
if err != nil {
|
|
scan.walkFailures++
|
|
slog.Warn("audiobook scan: read dir failed", "path", path, "error", err)
|
|
return nil
|
|
}
|
|
hadAudio := false
|
|
for _, e := range entries {
|
|
if !e.IsDir() && SupportsAudioFile(e.Name()) {
|
|
scan.seenPaths[filepath.Join(path, e.Name())] = true
|
|
hadAudio = true
|
|
}
|
|
}
|
|
if hadAudio {
|
|
scan.candidates = append(scan.candidates, path)
|
|
return filepath.SkipDir
|
|
}
|
|
return nil
|
|
})
|
|
if walkErr != nil {
|
|
if errors.Is(walkErr, context.Canceled) || errors.Is(walkErr, context.DeadlineExceeded) {
|
|
return nil, walkErr
|
|
}
|
|
scan.rootErr = fmt.Errorf("walk root: %w", walkErr)
|
|
}
|
|
}
|
|
if scan.failed() {
|
|
slog.Warn("audiobook scan: root walk incomplete; root excluded from missing-file reconciliation",
|
|
"folder_id", folderID,
|
|
"root", cleanRoot,
|
|
"walk_failures", scan.walkFailures,
|
|
"error", scan.rootErr,
|
|
)
|
|
}
|
|
scans = append(scans, scan)
|
|
}
|
|
return scans, nil
|
|
}
|
|
|
|
func splitAudiobookReconcileRoots(scans []audiobookRootScan) (roots []string, seenPaths map[string]bool, sawFiles bool) {
|
|
roots = make([]string, 0, len(scans))
|
|
seenPaths = make(map[string]bool)
|
|
for i := range scans {
|
|
scan := &scans[i]
|
|
if scan.failed() {
|
|
continue
|
|
}
|
|
roots = append(roots, scan.root)
|
|
if len(scan.seenPaths) > 0 {
|
|
sawFiles = true
|
|
for path := range scan.seenPaths {
|
|
seenPaths[path] = true
|
|
}
|
|
}
|
|
}
|
|
return roots, seenPaths, sawFiles
|
|
}
|
|
|
|
// ScanAudiobookFolder walks an audiobooks-typed media folder and writes
|
|
// one media_items row per subdirectory it can parse as an audiobook,
|
|
// plus the corresponding media_files rows and author/narrator links in
|
|
// item_people.
|
|
//
|
|
// Each immediate subdirectory of one of folder.Paths is treated as a
|
|
// single audiobook. Subdirectories that contain zero audio files are
|
|
// silently skipped (parseAudiobookFolder returns os.ErrNotExist).
|
|
//
|
|
// This bypasses the per-file movie/TV pipeline because audiobooks are
|
|
// inherently folder-scoped (one book = one item, possibly multi-file).
|
|
func (s *Scanner) ScanAudiobookFolder(ctx context.Context, folder *models.MediaFolder, fullScan bool) error {
|
|
if s == nil || folder == nil {
|
|
return fmt.Errorf("ScanAudiobookFolder: nil scanner or folder")
|
|
}
|
|
|
|
// Phase 1: walk the tree to collect candidate book folders. This is
|
|
// I/O-light (no ffprobe), and avoids holding the worker pool open
|
|
// for the duration of a 240k-folder scan.
|
|
scans, err := collectAudiobookRootScans(ctx, folder.ID, folder.Paths)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
candidates := make([]string, 0)
|
|
for i := range scans {
|
|
candidates = append(candidates, scans[i].candidates...)
|
|
}
|
|
reconcileRoots, seenPaths, sawFiles := splitAudiobookReconcileRoots(scans)
|
|
|
|
if len(candidates) == 0 {
|
|
// No books on disk. Still reconcile (guarded) so a legitimately-emptied
|
|
// library converges — but only when a root was readable, and the
|
|
// empty-walk guard requires operator confirmation before deleting.
|
|
if len(reconcileRoots) > 0 {
|
|
if err := s.reconcileAudiobookMissingFiles(ctx, folder, reconcileRoots, seenPaths, sawFiles, fullScan); err != nil {
|
|
slog.Warn("audiobook scan: missing-file reconcile failed", "folder_id", folder.ID, "error", err)
|
|
}
|
|
} else if len(scans) > 0 {
|
|
slog.Warn("audiobook scan: every root walk failed; skipping missing-file reconciliation",
|
|
"folder_id", folder.ID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Phase 2: reconcile in parallel. ffprobe dominates per-book wall time
|
|
// (hundreds of ms each), so single-threaded scans of a large library
|
|
// take days. Worker pool brings this to ~hours.
|
|
workers := audiobookScanWorkers()
|
|
slog.Info("audiobook scan: starting",
|
|
"folder_id", folder.ID,
|
|
"candidates", len(candidates),
|
|
"workers", workers,
|
|
)
|
|
|
|
ch := make(chan string, workers*2)
|
|
var (
|
|
wg sync.WaitGroup
|
|
processed int64
|
|
failed int64
|
|
skipped int64
|
|
failMu sync.Mutex
|
|
failures []error
|
|
cancelErr error
|
|
)
|
|
start := time.Now()
|
|
for i := 0; i < workers; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
for path := range ch {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
if err := s.reconcileAudiobookFolder(ctx, folder, path, &skipped); err != nil {
|
|
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
|
failMu.Lock()
|
|
if cancelErr == nil {
|
|
cancelErr = err
|
|
}
|
|
failMu.Unlock()
|
|
return
|
|
}
|
|
atomic.AddInt64(&failed, 1)
|
|
failMu.Lock()
|
|
failures = append(failures, fmt.Errorf("%s: %w", path, err))
|
|
failMu.Unlock()
|
|
slog.Warn("audiobook scan: folder failed",
|
|
"folder_id", folder.ID,
|
|
"path", path,
|
|
"error", err,
|
|
)
|
|
}
|
|
n := atomic.AddInt64(&processed, 1)
|
|
if n%500 == 0 {
|
|
slog.Info("audiobook scan: progress",
|
|
"folder_id", folder.ID,
|
|
"processed", n,
|
|
"failed", atomic.LoadInt64(&failed),
|
|
"skipped", atomic.LoadInt64(&skipped),
|
|
"total", len(candidates),
|
|
"elapsed_sec", int(time.Since(start).Seconds()),
|
|
)
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
|
|
for _, p := range candidates {
|
|
if ctx.Err() != nil {
|
|
break
|
|
}
|
|
ch <- p
|
|
}
|
|
close(ch)
|
|
wg.Wait()
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
if cancelErr != nil {
|
|
return cancelErr
|
|
}
|
|
|
|
slog.Info("audiobook scan: completed",
|
|
"folder_id", folder.ID,
|
|
"processed", atomic.LoadInt64(&processed),
|
|
"failed", atomic.LoadInt64(&failed),
|
|
"skipped", atomic.LoadInt64(&skipped),
|
|
"elapsed_sec", int(time.Since(start).Seconds()),
|
|
)
|
|
if processedCount := atomic.LoadInt64(&processed); processedCount > 0 {
|
|
failedCount := atomic.LoadInt64(&failed)
|
|
skippedCount := atomic.LoadInt64(&skipped)
|
|
if failedCount > 0 && skippedCount == 0 && failedCount == processedCount {
|
|
return fmt.Errorf("audiobook scan failed for every attempted folder_id=%d: %w", folder.ID, errors.Join(failures...))
|
|
}
|
|
}
|
|
|
|
// Reconcile files that vanished from disk now that the full walk's
|
|
// seenPaths is known and the scan completed without cancellation.
|
|
if err := s.reconcileAudiobookMissingFiles(ctx, folder, reconcileRoots, seenPaths, sawFiles, fullScan); err != nil {
|
|
slog.Warn("audiobook scan: missing-file reconcile failed", "folder_id", folder.ID, "error", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// reconcileAudiobookMissingFiles mirrors reconcileMissingEbookFiles: DB files
|
|
// under the scanned roots that were not seen on disk are marked missing, the
|
|
// folder trash is optionally emptied, and library memberships are reconciled so
|
|
// books with no remaining files are removed (a rename therefore converges on
|
|
// the newly indexed path instead of leaving a stale duplicate). A scan that saw
|
|
// zero files while the DB still has rows only reconciles when the operator has
|
|
// confirmed cleanup, so an unmounted source can't wipe the catalog.
|
|
func (s *Scanner) reconcileAudiobookMissingFiles(ctx context.Context, folder *models.MediaFolder, roots []string, seenPaths map[string]bool, sawFiles, fullScan bool) error {
|
|
if s.fileRepo == nil || s.libraryRepo == nil || len(roots) == 0 {
|
|
return nil
|
|
}
|
|
|
|
if !sawFiles {
|
|
existingCount := 0
|
|
for _, root := range roots {
|
|
existing, err := s.fileRepo.GetByFolderAndPathPrefix(ctx, folder.ID, root)
|
|
if err != nil {
|
|
return fmt.Errorf("listing existing audiobook files for %q: %w", root, err)
|
|
}
|
|
existingCount += len(existing)
|
|
}
|
|
if existingCount > 0 {
|
|
var guard ebookCleanupGuardRepo
|
|
if s.folderRepo != nil {
|
|
guard = s.folderRepo
|
|
}
|
|
// Only a full scan may consume the operator's one-shot empty-cleanup
|
|
// allowance; an incremental/subtree scan that happens to see zero
|
|
// files must not (mirrors the ebook path).
|
|
allowed, err := ebookEmptyCleanupAllowed(ctx, guard, folder.ID, fullScan)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !allowed {
|
|
slog.Warn("audiobook scan: walk saw zero files but the database has files under the scanned roots; skipping reconciliation until cleanup is confirmed",
|
|
"folder_id", folder.ID, "existing_files", existingCount)
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
|
|
now := time.Now().UTC()
|
|
missing := 0
|
|
for _, root := range roots {
|
|
existing, err := s.fileRepo.GetByFolderAndPathPrefix(ctx, folder.ID, root)
|
|
if err != nil {
|
|
return fmt.Errorf("listing existing audiobook files for %q: %w", root, err)
|
|
}
|
|
for _, mf := range existing {
|
|
if mf == nil || seenPaths[mf.FilePath] {
|
|
continue
|
|
}
|
|
if mf.MissingSince == nil {
|
|
if err := s.fileRepo.MarkMissing(ctx, mf.ID, now); err != nil {
|
|
slog.Error("audiobook scan: failed to mark file missing",
|
|
"folder_id", folder.ID, "path", mf.FilePath, "error", err)
|
|
continue
|
|
}
|
|
}
|
|
missing++
|
|
}
|
|
}
|
|
|
|
if s.emptyTrashAfterScan {
|
|
trashed, err := s.fileRepo.DeleteMissingByFolder(ctx, folder.ID)
|
|
if err != nil {
|
|
return fmt.Errorf("emptying trash for folder %d: %w", folder.ID, err)
|
|
}
|
|
if trashed > 0 {
|
|
slog.Info("audiobook scan: emptied trash", "folder_id", folder.ID, "deleted", trashed)
|
|
}
|
|
}
|
|
|
|
removedMemberships, deletedItems, orphanedImageDirs, err := s.reconcileLibraryMemberships(ctx, folder.ID)
|
|
if err != nil {
|
|
return fmt.Errorf("reconciling library membership for folder %d: %w", folder.ID, err)
|
|
}
|
|
if s.s3Client != nil && len(orphanedImageDirs) > 0 {
|
|
bucket := s.s3Client.Bucket()
|
|
for _, dir := range orphanedImageDirs {
|
|
_, _ = s.s3Client.DeletePrefix(ctx, bucket, dir)
|
|
}
|
|
}
|
|
if missing > 0 || removedMemberships > 0 || deletedItems > 0 {
|
|
slog.Info("audiobook scan: reconciled missing files",
|
|
"folder_id", folder.ID, "missing", missing,
|
|
"memberships_removed", removedMemberships, "items_deleted", deletedItems)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Scanner) reconcileAudiobookFolder(ctx context.Context, folder *models.MediaFolder, folderPath string, skipped *int64) error {
|
|
existingContentID, isUnchanged, skipErr := s.audiobookFolderShouldSkip(ctx, folder, folderPath)
|
|
if skipErr != nil {
|
|
slog.Warn("audiobook scan: skip-check failed, falling through",
|
|
"folder_id", folder.ID,
|
|
"path", folderPath,
|
|
"error", skipErr,
|
|
)
|
|
} else if isUnchanged {
|
|
s.autoLinkLiteraryWork(ctx, existingContentID)
|
|
atomic.AddInt64(skipped, 1)
|
|
return nil
|
|
}
|
|
parsed, err := parseAudiobookFolder(ctx, s.ffprobePath, folderPath)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("parse audiobook folder %s: %w", folderPath, err)
|
|
}
|
|
|
|
contentID, err := s.upsertAudiobookMediaItem(ctx, folder.ID, folderPath, parsed)
|
|
if err != nil {
|
|
return fmt.Errorf("upsert audiobook item: %w", err)
|
|
}
|
|
if err := s.upsertAudiobookMediaFiles(ctx, folder, contentID, folderPath, parsed); err != nil {
|
|
return fmt.Errorf("upsert audiobook files: %w", err)
|
|
}
|
|
if err := applyAudiobookSidecarCover(ctx, s.itemRepo, s.imageCacher, contentID, folderPath); err != nil {
|
|
slog.Warn("audiobook scan: sidecar cover upload failed",
|
|
"folder_id", folder.ID,
|
|
"content_id", contentID,
|
|
"path", folderPath,
|
|
"error", err,
|
|
)
|
|
}
|
|
if len(parsed.Files) > 0 && s.fileRepo != nil {
|
|
if _, err := applyAudiobookEmbeddedCover(ctx, s.itemRepo, s.fileRepo.Pool(), FFmpegPathFromFFprobe(s.ffprobePath), s.imageCacher, parsed.Files[0].Path, contentID); err != nil {
|
|
slog.Warn("audiobook scan: embedded cover failed",
|
|
"folder_id", folder.ID,
|
|
"content_id", contentID,
|
|
"path", parsed.Files[0].Path,
|
|
"error", err,
|
|
)
|
|
}
|
|
}
|
|
if err := s.upsertAudiobookPeople(ctx, contentID, parsed); err != nil {
|
|
return fmt.Errorf("upsert audiobook people: %w", err)
|
|
}
|
|
if err := s.upsertAudiobookSeries(ctx, contentID, parsed); err != nil {
|
|
return fmt.Errorf("upsert audiobook series: %w", err)
|
|
}
|
|
if _, err := s.fileRepo.Pool().Exec(ctx, `
|
|
INSERT INTO media_item_libraries (content_id, media_folder_id, first_seen_at)
|
|
VALUES ($1, $2, NOW())
|
|
ON CONFLICT (content_id, media_folder_id) DO NOTHING
|
|
`, contentID, folder.ID); err != nil {
|
|
return fmt.Errorf("upsert audiobook library membership: %w", err)
|
|
}
|
|
if parsed.ASIN != "" {
|
|
// Two unique constraints can conflict: (content_id, provider) is the
|
|
// PK, and (provider, provider_id, item_type) prevents two content
|
|
// rows from claiming the same external ID. We want to silently skip
|
|
// when either fires; ON CONFLICT DO NOTHING (no target) catches both.
|
|
if _, err := s.fileRepo.Pool().Exec(ctx, `
|
|
INSERT INTO media_item_provider_ids (content_id, provider, provider_id, item_type)
|
|
VALUES ($1, 'asin', $2, 'audiobook')
|
|
ON CONFLICT DO NOTHING
|
|
`, contentID, parsed.ASIN); err != nil {
|
|
return fmt.Errorf("upsert audiobook ASIN provider id: %w", err)
|
|
}
|
|
}
|
|
s.autoLinkLiteraryWork(ctx, contentID)
|
|
slog.Info("audiobook scan: indexed",
|
|
"folder_id", folder.ID,
|
|
"content_id", contentID,
|
|
"title", parsed.Title,
|
|
"author", parsed.Author,
|
|
"files", len(parsed.Files),
|
|
)
|
|
return nil
|
|
}
|
|
|
|
func applyAudiobookEmbeddedCover(
|
|
ctx context.Context,
|
|
reader audiobookPosterPathReader,
|
|
exec audiobookPosterExec,
|
|
ffmpegPath string,
|
|
cacher audiobookCoverCacher,
|
|
audioFilePath string,
|
|
contentID string,
|
|
) (bool, error) {
|
|
if exec == nil {
|
|
return false, nil
|
|
}
|
|
if reader != nil {
|
|
existingPosterPath, err := reader.GetPosterPath(ctx, contentID)
|
|
if err != nil {
|
|
return false, fmt.Errorf("get audiobook poster path for embedded cover: %w", err)
|
|
}
|
|
if strings.TrimSpace(existingPosterPath) != "" {
|
|
return false, nil
|
|
}
|
|
}
|
|
poster, thumb := ExtractAndUploadAudiobookCover(ctx, ffmpegPath, cacher, audioFilePath, contentID)
|
|
if poster == "" {
|
|
return false, nil
|
|
}
|
|
_, err := exec.Exec(ctx, `
|
|
UPDATE media_items
|
|
SET poster_path = $1, poster_thumbhash = $2, updated_at = NOW()
|
|
WHERE content_id = $3 AND (poster_path IS NULL OR poster_path = '')
|
|
`, poster, thumb, contentID)
|
|
if err != nil {
|
|
return false, fmt.Errorf("update audiobook embedded cover: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// upsertAudiobookMediaItem reuses an item already linked to the same filesystem
|
|
// root, then falls back to the stricter ABS duplicate rule, or creates a new row.
|
|
// It intentionally avoids title/year-only dedupe because audiobooks often share
|
|
// titles, unknown years, or edition-specific credits. Returns the content_id used.
|
|
func (s *Scanner) upsertAudiobookMediaItem(ctx context.Context, folderID int, folderPath string, book *parsedAudiobook) (string, error) {
|
|
if s.itemRepo == nil {
|
|
return "", fmt.Errorf("itemRepo not configured on Scanner")
|
|
}
|
|
if s.fileRepo == nil {
|
|
return "", fmt.Errorf("fileRepo not configured on Scanner")
|
|
}
|
|
|
|
existingID, err := s.fileRepo.FindContentIDByRootPath(ctx, folderID, folderPath, "audiobook")
|
|
if err != nil {
|
|
return "", fmt.Errorf("find audiobook by root path: %w", err)
|
|
}
|
|
if existingID != "" {
|
|
if err := s.updateExistingAudiobookMediaItem(ctx, existingID, book); err != nil {
|
|
return "", err
|
|
}
|
|
return existingID, nil
|
|
}
|
|
|
|
cleanTitle := stripNarratorSuffix(book.Title)
|
|
if cleanTitle == "" {
|
|
cleanTitle = book.Title
|
|
}
|
|
|
|
if existing := s.findAudiobookByFilePath(ctx, folderID, book); existing != nil {
|
|
applyBookToMediaItem(existing, book)
|
|
if existing.SortTitle == "" {
|
|
existing.SortTitle = titleutil.DeriveDefaultSortTitle(existing.Title)
|
|
}
|
|
if err := s.itemRepo.Upsert(ctx, existing); err != nil {
|
|
return "", err
|
|
}
|
|
return existing.ContentID, nil
|
|
}
|
|
|
|
// Secondary dedup: catch books stored under two folders ("Foo" + "Foo
|
|
// Subtitle Version"). Same scan-time rule as the one-shot
|
|
// scripts/dedup_audiobooks.py — author + narrator + year + duration
|
|
// within tolerance + title is equal or an exact "X" / "X: subtitle"
|
|
// prefix relation. Attaches the new file to the existing row so we
|
|
// don't pile up duplicates as the scan progresses.
|
|
if existing := s.findAudiobookDuplicate(ctx, book, cleanTitle); existing != nil {
|
|
applyBookToMediaItem(existing, book)
|
|
if existing.SortTitle == "" {
|
|
existing.SortTitle = titleutil.DeriveDefaultSortTitle(existing.Title)
|
|
}
|
|
if err := s.itemRepo.Upsert(ctx, existing); err != nil {
|
|
return "", err
|
|
}
|
|
return existing.ContentID, nil
|
|
}
|
|
|
|
return createAudiobookMediaItem(ctx, s.itemRepo, book, cleanTitle)
|
|
}
|
|
|
|
func (s *Scanner) updateExistingAudiobookMediaItem(ctx context.Context, contentID string, book *parsedAudiobook) error {
|
|
items, err := s.itemRepo.GetByIDs(ctx, []string{contentID})
|
|
if err != nil {
|
|
return fmt.Errorf("get audiobook media item %s: %w", contentID, err)
|
|
}
|
|
if len(items) == 0 || items[0] == nil {
|
|
return fmt.Errorf("audiobook media item %s not found", contentID)
|
|
}
|
|
item := items[0]
|
|
applyBookToMediaItem(item, book)
|
|
if item.SortTitle == "" {
|
|
item.SortTitle = titleutil.DeriveDefaultSortTitle(item.Title)
|
|
}
|
|
return s.itemRepo.Upsert(ctx, item)
|
|
}
|
|
|
|
func resolveAudiobookMediaItem(
|
|
ctx context.Context,
|
|
rootFinder filesystemRootContentFinder,
|
|
itemWriter filesystemMediaItemWriter,
|
|
folderID int,
|
|
folderPath string,
|
|
book *parsedAudiobook,
|
|
) (string, error) {
|
|
if rootFinder == nil {
|
|
return "", fmt.Errorf("root content finder not configured")
|
|
}
|
|
if itemWriter == nil {
|
|
return "", fmt.Errorf("media item writer not configured")
|
|
}
|
|
existingID, err := rootFinder.FindContentIDByRootPath(ctx, folderID, folderPath, "audiobook")
|
|
if err != nil {
|
|
return "", fmt.Errorf("find audiobook by root path: %w", err)
|
|
}
|
|
if existingID != "" {
|
|
return existingID, nil
|
|
}
|
|
|
|
cleanTitle := stripNarratorSuffix(book.Title)
|
|
if cleanTitle == "" {
|
|
cleanTitle = book.Title
|
|
}
|
|
return createAudiobookMediaItem(ctx, itemWriter, book, cleanTitle)
|
|
}
|
|
|
|
func createAudiobookMediaItem(ctx context.Context, itemWriter filesystemMediaItemWriter, book *parsedAudiobook, cleanTitle string) (string, error) {
|
|
id, err := idgen.NextID()
|
|
if err != nil {
|
|
return "", fmt.Errorf("generate content_id: %w", err)
|
|
}
|
|
item := &models.MediaItem{
|
|
ContentID: id,
|
|
Type: "audiobook",
|
|
Title: cleanTitle,
|
|
SortTitle: titleutil.DeriveDefaultSortTitle(cleanTitle),
|
|
Year: book.Year,
|
|
}
|
|
applyBookToMediaItem(item, book)
|
|
if item.SortTitle == "" {
|
|
item.SortTitle = titleutil.DeriveDefaultSortTitle(item.Title)
|
|
}
|
|
if err := itemWriter.Upsert(ctx, item); err != nil {
|
|
return "", err
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
// findAudiobookDuplicate returns an existing audiobook media_items row that
|
|
// matches the parsed book on (author, narrator, year, duration ±0.5%/±10s,
|
|
// punctuation-normalized title). Used after the file-path lookup misses to
|
|
// detect the same recording stored under a different folder name. Returns nil
|
|
// when no match exists or any required attribute (author, narrator, year,
|
|
// duration) is missing — under-tagged files don't qualify for automatic dedup.
|
|
func (s *Scanner) findAudiobookDuplicate(ctx context.Context, book *parsedAudiobook, cleanTitle string) *models.MediaItem {
|
|
if s.fileRepo == nil {
|
|
return nil
|
|
}
|
|
if book.Author == "" || book.Narrator == "" || book.Year == 0 {
|
|
return nil
|
|
}
|
|
var totalDuration int
|
|
for _, f := range book.Files {
|
|
totalDuration += f.Duration
|
|
}
|
|
if totalDuration <= 0 {
|
|
return nil
|
|
}
|
|
tolerance := totalDuration / 200 // 0.5%
|
|
if tolerance < 10 {
|
|
tolerance = 10
|
|
}
|
|
titleKey := normalizeAudiobookDedupeTitle(cleanTitle)
|
|
if titleKey == "" {
|
|
return nil
|
|
}
|
|
rows, err := s.fileRepo.Pool().Query(ctx,
|
|
audiobookDuplicateCandidateSQL,
|
|
book.Author,
|
|
book.Narrator,
|
|
book.Year,
|
|
totalDuration,
|
|
tolerance,
|
|
titleKey,
|
|
)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
defer rows.Close()
|
|
|
|
var existingID string
|
|
for rows.Next() {
|
|
var candidateID, candidateTitle string
|
|
if err := rows.Scan(&candidateID, &candidateTitle); err != nil {
|
|
return nil
|
|
}
|
|
if audiobookDedupeTitlesMatch(candidateTitle, cleanTitle) {
|
|
existingID = candidateID
|
|
break
|
|
}
|
|
}
|
|
if rows.Err() != nil || existingID == "" {
|
|
return nil
|
|
}
|
|
|
|
items, err := s.itemRepo.GetByIDs(ctx, []string{existingID})
|
|
if err != nil || len(items) == 0 {
|
|
return nil
|
|
}
|
|
return items[0]
|
|
}
|
|
|
|
// findAudiobookByFilePath returns an existing audiobook media_items row
|
|
// whose media_files reference any of this book's audio file paths.
|
|
// Returns nil when no match exists (a fresh scan of a new folder).
|
|
func (s *Scanner) findAudiobookByFilePath(ctx context.Context, folderID int, book *parsedAudiobook) *models.MediaItem {
|
|
if s.fileRepo == nil || len(book.Files) == 0 {
|
|
return nil
|
|
}
|
|
paths := audiobookLookupPaths(book.Files)
|
|
if len(paths) == 0 {
|
|
return nil
|
|
}
|
|
var existingID string
|
|
err := s.fileRepo.Pool().QueryRow(ctx, `
|
|
SELECT mf.content_id
|
|
FROM media_files mf
|
|
JOIN media_items mi ON mi.content_id = mf.content_id
|
|
WHERE mf.media_folder_id = $2
|
|
AND (mf.file_path = ANY($1) OR LOWER(mf.file_path) = ANY($1))
|
|
AND mi.type = 'audiobook'
|
|
LIMIT 1
|
|
`, paths, folderID).Scan(&existingID)
|
|
if err != nil || existingID == "" {
|
|
return nil
|
|
}
|
|
items, err := s.itemRepo.GetByIDs(ctx, []string{existingID})
|
|
if err != nil || len(items) == 0 {
|
|
return nil
|
|
}
|
|
return items[0]
|
|
}
|
|
|
|
func audiobookLookupPaths(files []parsedAudiobookFile) []string {
|
|
seen := make(map[string]struct{}, len(files)*2)
|
|
paths := make([]string, 0, len(files)*2)
|
|
for _, f := range files {
|
|
path := strings.TrimSpace(f.Path)
|
|
if path == "" {
|
|
continue
|
|
}
|
|
for _, candidate := range []string{path, strings.ToLower(path)} {
|
|
if candidate == "" {
|
|
continue
|
|
}
|
|
if _, ok := seen[candidate]; ok {
|
|
continue
|
|
}
|
|
seen[candidate] = struct{}{}
|
|
paths = append(paths, candidate)
|
|
}
|
|
}
|
|
return paths
|
|
}
|
|
|
|
// applyBookToMediaItem copies parsed-audiobook tag fields onto the
|
|
// MediaItem. Used for both fresh inserts and re-scans of existing rows
|
|
// so manual edits to fields not driven by the file (e.g., poster_path
|
|
// set by the metadata enricher) survive.
|
|
//
|
|
// Audiobook titles are stripped of trailing narrator/edition suffixes
|
|
// (`Foo (Read by Bar)`, `Foo - read by Bar`, etc.) since that data is
|
|
// already captured as item_people kind=8. The raw tag value is preserved
|
|
// in OriginalTitle when it differs so the original is never lost.
|
|
func applyBookToMediaItem(item *models.MediaItem, book *parsedAudiobook) {
|
|
item.Type = "audiobook"
|
|
raw := strings.TrimSpace(book.Title)
|
|
cleaned := stripNarratorSuffix(raw)
|
|
if cleaned == "" {
|
|
cleaned = raw
|
|
}
|
|
item.Title = cleaned
|
|
if cleaned != raw && item.OriginalTitle == "" {
|
|
item.OriginalTitle = raw
|
|
}
|
|
item.Year = book.Year
|
|
if book.Overview != "" && item.Overview == "" {
|
|
item.Overview = book.Overview
|
|
}
|
|
if book.Publisher != "" {
|
|
item.Studios = mergeUniqueStrings(item.Studios, []string{book.Publisher})
|
|
}
|
|
if len(book.Genres) > 0 {
|
|
item.Genres = mergeUniqueStrings(item.Genres, book.Genres)
|
|
}
|
|
if rd := normalizeReleaseDateForSQL(book.ReleaseDate); rd != "" && (item.ReleaseDate == nil || *item.ReleaseDate == "") {
|
|
item.ReleaseDate = &rd
|
|
}
|
|
if book.Language != "" && item.OriginalLanguage == "" {
|
|
item.OriginalLanguage = book.Language
|
|
}
|
|
}
|
|
|
|
// normalizeReleaseDateForSQL coerces tag-derived date strings into the
|
|
// ISO YYYY-MM-DD shape media_items.release_date expects. Year-only
|
|
// tags ("2018") become "2018-01-01"; ISO already-correct values pass
|
|
// through; everything else returns "" (skip the column).
|
|
func normalizeReleaseDateForSQL(s string) string {
|
|
s = strings.TrimSpace(s)
|
|
if s == "" {
|
|
return ""
|
|
}
|
|
if len(s) >= 10 && s[4] == '-' && s[7] == '-' {
|
|
return s[:10]
|
|
}
|
|
if len(s) >= 4 {
|
|
y := s[:4]
|
|
ok := true
|
|
for _, c := range y {
|
|
if c < '0' || c > '9' {
|
|
ok = false
|
|
break
|
|
}
|
|
}
|
|
if ok {
|
|
return y + "-01-01"
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func mergeUniqueStrings(existing, additions []string) []string {
|
|
seen := make(map[string]struct{}, len(existing)+len(additions))
|
|
out := make([]string, 0, len(existing)+len(additions))
|
|
for _, v := range existing {
|
|
k := strings.ToLower(strings.TrimSpace(v))
|
|
if k == "" {
|
|
continue
|
|
}
|
|
if _, ok := seen[k]; ok {
|
|
continue
|
|
}
|
|
seen[k] = struct{}{}
|
|
out = append(out, v)
|
|
}
|
|
for _, v := range additions {
|
|
k := strings.ToLower(strings.TrimSpace(v))
|
|
if k == "" {
|
|
continue
|
|
}
|
|
if _, ok := seen[k]; ok {
|
|
continue
|
|
}
|
|
seen[k] = struct{}{}
|
|
out = append(out, v)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// upsertAudiobookMediaFiles writes one media_files row per audio file in the
|
|
// parsed audiobook. The content_id ties each file back to the media_items row.
|
|
// folderPath is used as the canonical_root_path / observed_root_path.
|
|
func (s *Scanner) upsertAudiobookMediaFiles(
|
|
ctx context.Context,
|
|
folder *models.MediaFolder,
|
|
contentID string,
|
|
folderPath string,
|
|
book *parsedAudiobook,
|
|
) error {
|
|
partTotal := len(book.Files)
|
|
for idx, af := range book.Files {
|
|
chapters := make([]models.MediaChapter, len(af.Chapters))
|
|
for i, ch := range af.Chapters {
|
|
chapters[i] = models.MediaChapter{
|
|
Index: ch.Index,
|
|
Title: ch.Title,
|
|
StartSeconds: ch.StartSeconds,
|
|
EndSeconds: ch.EndSeconds,
|
|
Source: ch.Source,
|
|
}
|
|
}
|
|
|
|
mf := models.MediaFile{
|
|
ContentID: contentID,
|
|
MediaFolderID: folder.ID,
|
|
CanonicalRootPath: folderPath,
|
|
ObservedRootPath: folderPath,
|
|
ContentGroupKey: contentID,
|
|
GroupKeyVersion: 1,
|
|
BaseTitle: book.Title,
|
|
BaseYear: book.Year,
|
|
BaseType: "audiobook",
|
|
IdentityConfidence: audiobookIdentityConfidence(book, af),
|
|
FilePath: af.Path,
|
|
Chapters: chapters,
|
|
ProbeSource: "local",
|
|
Duration: af.Duration,
|
|
Bitrate: af.Bitrate,
|
|
CodecAudio: af.CodecAudio,
|
|
Container: af.Container,
|
|
AudioChannels: af.AudioChannels,
|
|
}
|
|
if partTotal > 1 {
|
|
mf.PresentationKind = "multipart"
|
|
mf.PresentationGroupKey = contentID
|
|
mf.PresentationPartIndex = idx + 1
|
|
mf.PresentationPartTotal = partTotal
|
|
}
|
|
|
|
if _, err := s.fileRepo.Upsert(ctx, mf); err != nil {
|
|
return fmt.Errorf("upsert media file %s: %w", af.Path, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// audiobookCredit pairs a person name with a credit kind. Used to compare
|
|
// the desired-from-tags set against the existing item_people set without
|
|
// having to materialize a full []models.ItemPerson (which requires
|
|
// resolved person IDs).
|
|
type audiobookCredit struct {
|
|
Name string
|
|
Kind models.PersonKind
|
|
}
|
|
|
|
// audiobookPeopleCreditsEqual returns true when the existing item_people
|
|
// rows for an audiobook match the desired credit set one-for-one on
|
|
// (case-insensitive name, kind). Order is irrelevant because the upsert
|
|
// path orders by SortOrder.
|
|
//
|
|
// Case-insensitive comparison: audiobook tag casing drifts between rips
|
|
// and we don't want a stylistic re-cap to trigger DELETE+INSERT on every
|
|
// scan.
|
|
func audiobookPeopleCreditsEqual(existing []models.ItemPerson, desired []audiobookCredit) bool {
|
|
if len(existing) != len(desired) {
|
|
return false
|
|
}
|
|
type key struct {
|
|
name string
|
|
kind models.PersonKind
|
|
}
|
|
have := make(map[key]struct{}, len(existing))
|
|
for _, p := range existing {
|
|
have[key{strings.ToLower(strings.TrimSpace(p.Person.Name)), p.Kind}] = struct{}{}
|
|
}
|
|
for _, d := range desired {
|
|
k := key{strings.ToLower(strings.TrimSpace(d.Name)), d.Kind}
|
|
if _, ok := have[k]; !ok {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// upsertAudiobookPeople upserts author and narrator rows into item_people,
|
|
// using the PersonRepository to find-or-create each person by name. When the
|
|
// parsed credits differ, ReplacePeople makes scanner-derived credits authoritative.
|
|
// Skips the DELETE+INSERT entirely when the existing credit set already
|
|
// matches the desired set (case-insensitive on name, exact on kind).
|
|
func (s *Scanner) upsertAudiobookPeople(ctx context.Context, contentID string, book *parsedAudiobook) error {
|
|
if s.personRepo == nil {
|
|
return fmt.Errorf("personRepo not configured on Scanner")
|
|
}
|
|
|
|
var desired []audiobookCredit
|
|
if book.Author != "" {
|
|
desired = append(desired, audiobookCredit{Name: book.Author, Kind: models.PersonKindAuthor})
|
|
}
|
|
if book.Narrator != "" {
|
|
desired = append(desired, audiobookCredit{Name: book.Narrator, Kind: models.PersonKindNarrator})
|
|
}
|
|
if len(desired) == 0 {
|
|
return nil
|
|
}
|
|
|
|
existing, err := s.itemRepo.GetPeople(ctx, contentID)
|
|
if err == nil && audiobookPeopleCreditsEqual(existing, desired) {
|
|
return nil
|
|
}
|
|
|
|
people := make([]models.ItemPerson, 0, len(desired))
|
|
for i, c := range desired {
|
|
personID, err := s.personRepo.FindOrCreate(ctx, models.Person{Name: c.Name})
|
|
if err != nil {
|
|
return fmt.Errorf("find-or-create person %q: %w", c.Name, err)
|
|
}
|
|
people = append(people, models.ItemPerson{
|
|
Person: models.Person{ID: personID},
|
|
Kind: c.Kind,
|
|
SortOrder: i,
|
|
})
|
|
}
|
|
|
|
return s.itemRepo.ReplacePeople(ctx, contentID, people)
|
|
}
|
|
|
|
// upsertAudiobookSeries writes the parsed series_name and series_index into
|
|
// the audiobook_series table, overwriting any prior row (e.g. one populated
|
|
// by migration 145's title-pattern backfill). A blank book.Series clears
|
|
// the row so books explicitly retagged out of a series stop appearing in
|
|
// the "In this series" rail on the next scan.
|
|
func (s *Scanner) upsertAudiobookSeries(ctx context.Context, contentID string, book *parsedAudiobook) error {
|
|
if s.fileRepo == nil {
|
|
return fmt.Errorf("fileRepo not configured on Scanner")
|
|
}
|
|
desiredName := strings.TrimSpace(book.Series)
|
|
desiredIdx := parseSeriesIndex(book.SeriesPosition)
|
|
|
|
// Read current row.
|
|
var currentName *string
|
|
var currentIdx *float64
|
|
err := s.fileRepo.Pool().QueryRow(ctx, `
|
|
SELECT series_name, series_index FROM audiobook_series WHERE content_id = $1
|
|
`, contentID).Scan(¤tName, ¤tIdx)
|
|
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
|
return fmt.Errorf("query audiobook_series: %w", err)
|
|
}
|
|
|
|
if desiredName == "" {
|
|
if currentName == nil {
|
|
return nil // already absent
|
|
}
|
|
if _, delErr := s.fileRepo.Pool().Exec(ctx,
|
|
`DELETE FROM audiobook_series WHERE content_id = $1`, contentID); delErr != nil {
|
|
return fmt.Errorf("delete audiobook_series row: %w", delErr)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
if currentName != nil && *currentName == desiredName && floatPtrEqual(currentIdx, desiredIdx) {
|
|
return nil // identical row, skip the write
|
|
}
|
|
|
|
var idx any
|
|
if desiredIdx != nil {
|
|
idx = *desiredIdx
|
|
}
|
|
if _, err := s.fileRepo.Pool().Exec(ctx, `
|
|
INSERT INTO audiobook_series (content_id, series_name, series_index, updated_at)
|
|
VALUES ($1, $2, $3, NOW())
|
|
ON CONFLICT (content_id) DO UPDATE SET
|
|
series_name = EXCLUDED.series_name,
|
|
series_index = EXCLUDED.series_index,
|
|
updated_at = NOW()
|
|
`, contentID, desiredName, idx); err != nil {
|
|
return fmt.Errorf("upsert audiobook_series row: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func audiobookIdentityConfidence(book *parsedAudiobook, file parsedAudiobookFile) string {
|
|
if book == nil {
|
|
return "low"
|
|
}
|
|
|
|
score := 0
|
|
if book.Title != "" {
|
|
score++
|
|
}
|
|
if book.Author != "" || book.Narrator != "" {
|
|
score++
|
|
}
|
|
if book.Year > 0 {
|
|
score++
|
|
}
|
|
for _, ch := range file.Chapters {
|
|
if ch.Title != "" && ch.EndSeconds > ch.StartSeconds {
|
|
score++
|
|
break
|
|
}
|
|
}
|
|
|
|
switch {
|
|
case score >= 4:
|
|
return "high"
|
|
case score > 0:
|
|
return "medium"
|
|
default:
|
|
return "low"
|
|
}
|
|
}
|
|
|
|
// floatPtrEqual returns true when two *float64 values represent the same
|
|
// state — both nil, or both non-nil and equal. Used to skip audiobook_series
|
|
// re-upserts when only the series_index needs to be NULL=NULL compared.
|
|
func floatPtrEqual(a, b *float64) bool {
|
|
if a == nil && b == nil {
|
|
return true
|
|
}
|
|
if a == nil || b == nil {
|
|
return false
|
|
}
|
|
return *a == *b
|
|
}
|
|
|
|
// parseSeriesIndex extracts a leading numeric value from a freeform tag
|
|
// like "5", "1.5", "2 of 8", or "1a". Returns nil when no leading number
|
|
// is present so the audiobook_series.series_index column stays NULL rather
|
|
// than carrying a misleading zero.
|
|
func parseSeriesIndex(raw string) *float64 {
|
|
raw = strings.TrimSpace(raw)
|
|
if raw == "" {
|
|
return nil
|
|
}
|
|
end := 0
|
|
dot := false
|
|
for end < len(raw) {
|
|
c := raw[end]
|
|
if c >= '0' && c <= '9' {
|
|
end++
|
|
continue
|
|
}
|
|
if c == '.' && !dot {
|
|
dot = true
|
|
end++
|
|
continue
|
|
}
|
|
break
|
|
}
|
|
if end == 0 {
|
|
return nil
|
|
}
|
|
var v float64
|
|
if _, err := fmt.Sscanf(raw[:end], "%f", &v); err != nil {
|
|
return nil
|
|
}
|
|
return &v
|
|
}
|