From 21ef4eb0e7eda8cc1192a9d176f82dbed239d015 Mon Sep 17 00:00:00 2001
From: Eyji
Date: Mon, 19 Oct 2026 20:35:57 +0200
Subject: [PATCH] feat(audible): optional filter for other-language editions in
search, BookDate and shelf sync
Keyword search on the catalog API returns every language, so on a non-English
region search, BookDate and shelf sync can surface (and request) editions that
are not in the region's language.
New admin setting `audible.language_filter` (off by default), a checkbox under
the Audible region in Settings > Library. When on, `search()` drops products whose
language fails `isAcceptedLanguage()` for the region, for callers that pass
`respectLanguageFilter`. Bulk import does not, since it matches files on disk.
Refs #259
Co-Authored-By: Claude Opus 5.5
---
documentation/features/bookdate.md | 2 +-
documentation/integrations/audible.md | 9 ++
documentation/settings-pages.md | 15 ++-
src/app/admin/settings/lib/helpers.ts | 7 +-
src/app/admin/settings/lib/types.ts | 1 +
.../AudibleLanguageFilterOption.tsx | 33 +++++++
.../tabs/LibraryTab/AudiobookshelfSection.tsx | 2 +
.../settings/tabs/LibraryTab/PlexSection.tsx | 2 +
src/app/api/admin/settings/audible/route.ts | 27 +++++-
src/app/api/admin/settings/route.ts | 1 +
src/app/api/audiobooks/search/route.ts | 2 +-
src/lib/bookdate/helpers.ts | 2 +-
src/lib/integrations/audible.service.ts | 32 ++++++-
src/lib/services/config.service.ts | 7 ++
src/lib/services/shelf-sync-core.service.ts | 4 +-
.../api/admin-settings-audible.routes.test.ts | 94 +++++++++++++++++++
tests/api/admin-settings-core.routes.test.ts | 13 +--
tests/api/audiobooks-browse.routes.test.ts | 1 +
tests/app/admin-settings.page.test.tsx | 1 +
.../admin/settings/hooks/useSettings.test.tsx | 1 +
tests/app/admin/settings/lib/helpers.test.ts | 6 +-
.../AudibleLanguageFilterOption.test.tsx | 27 ++++++
tests/bookdate/helpers.test.ts | 4 +-
.../admin-settings-indexers.test.tsx | 1 +
tests/integrations/audible.service.test.ts | 59 ++++++++++++
.../services/shelf-sync-core.service.test.ts | 57 +++++++++++
26 files changed, 376 insertions(+), 34 deletions(-)
create mode 100644 src/app/admin/settings/tabs/LibraryTab/AudibleLanguageFilterOption.tsx
create mode 100644 tests/api/admin-settings-audible.routes.test.ts
create mode 100644 tests/app/admin/settings/tabs/LibraryTab/AudibleLanguageFilterOption.test.tsx
create mode 100644 tests/services/shelf-sync-core.service.test.ts
diff --git a/documentation/features/bookdate.md b/documentation/features/bookdate.md
index 372ed0380..10db503b0 100644
--- a/documentation/features/bookdate.md
+++ b/documentation/features/bookdate.md
@@ -150,7 +150,7 @@ Personalized audiobook discovery using OpenAI/Claude APIs. Admin configures AI p
- Request: 20 recommendations (expect ~10 after filtering)
3. **Post-Processing:**
- - Match to Audnexus (database cache first, API fallback)
+ - Match to Audnexus (database cache first, API fallback: first Audible search result, filtered by `audible.language_filter` when on)
- Filter: Already in library (uses centralized audiobook-matcher.ts - same as homepage), already requested, already swiped
- Two-stage library filtering:
- Stage 1: Fuzzy match with AI-provided title/author (before Audnexus)
diff --git a/documentation/integrations/audible.md b/documentation/integrations/audible.md
index 7c76c858f..0972ac8dd 100644
--- a/documentation/integrations/audible.md
+++ b/documentation/integrations/audible.md
@@ -61,6 +61,7 @@ Populates every `AudibleAudiobook` field. Covered:
- **Catalog API cannot filter preorders or surface curated bestsellers.** The API's `BestSellers` sort is a right-now velocity rank that spikes on launch-day promos and preorder windows; the `-ReleaseDate` sort returns 100% future preorders. There is no server-side `release_time`, `released-only`, `customer_rights`, or alternate sort (`Reviewed`, `MostListened`, etc.) — every plausible variant was tested and silently ignored. This is why the nightly refresh job uses the curated HTML storefront pages instead.
- **`author=` takes a name, not an ASIN.** The catalog API has no ASIN-based author param. `searchByAuthorAsin()` queries by name, then filters client-side: keeps only products where `products[].authors[].asin === authorAsin`. Preserves ASIN-authoritative author identity. Also filters by `product.language` via `isAcceptedLanguage()` for the configured region.
+- **Keyword search returns every language.** `search()` sends no language param, so results include editions in languages other than the region's. Opt-in filter, see Language Filter below.
- **Invalid ASIN returns HTTP 200 with stub body.** `/1.0/catalog/products/{asin}` responds 200 with `{product: {asin: INPUT}}` and no other fields. `fetchAudibleDetailsFromApi()` detects this via missing `product.title` and returns `null`.
- **`publisher_summary` is HTML.** Service strips tags via inline `stripHtml()` helper (regex-based, no cheerio) before populating `description`. Falls back to `merchandising_summary` (plain text) if `publisher_summary` missing.
- **Series is an array.** `products[].series[]` — a book may belong to multiple series. Service picks the first entry with non-empty `sequence`, else the first entry. `sequence` is cleaned by extracting first `/\d+(?:\.\d+)?/` match for numeric ordering.
@@ -111,6 +112,14 @@ Configurable Audible region for accurate metadata matching across international
- Cache clearing: Region change clears ConfigService cache and AudibleService state.
- Automatic refresh: Region change triggers `audible_refresh` job.
+**Language Filter:**
+- Key: `audible.language_filter` (`'true'`/`'false'`, default off). Read via `ConfigService.getAudibleLanguageFilter()`.
+- `search(query, page, { respectLanguageFilter: true })`: when the key is on, drops products whose `language` fails `isAcceptedLanguage()` for the region. Products without `language` are kept.
+- Opted in: search page (`/api/audiobooks/search`), BookDate (`matchToAudnexus`), shelf sync (`performAudibleLookup`). Not opted in: bulk import (matches files already on disk).
+- Shelf sync: a book with no edition in the region's language becomes a `noMatch` mapping (retried every 7 days). Mappings resolved before the filter was enabled are not re-resolved.
+- `hasMore` is computed on the raw page, so a page whose books were all filtered out does not end pagination for API callers. `totalResults` stays Audible's unfiltered total.
+- Discovery pages (popular, new releases, categories) are not filtered: they come from the region's HTML storefronts, not keyword search.
+
**Per-region HTTP clients (on init):**
- `apiClient` — `baseURL=apiBaseUrl`, `Accept: application/json`, `User-Agent: ReadMeABook/1.0`, no language/ipRedirect params. Used for the real-time JSON catalog operations (search, author books, categories listing, per-ASIN details fallback).
- `htmlClient` — `baseURL=baseUrl`, rotating browser headers (`pickUserAgent` + `getBrowserHeaders`), default params `ipRedirectOverride=true` + `language=`. Used by the nightly discovery refresh (`/adblbestsellers`, `/newreleases`, `/search?node=...`), by `audible-series.ts`, and by `getBaseUrl()`-based link generation.
diff --git a/documentation/settings-pages.md b/documentation/settings-pages.md
index ef89fa981..dd1d4e897 100644
--- a/documentation/settings-pages.md
+++ b/documentation/settings-pages.md
@@ -64,8 +64,8 @@ src/app/admin/settings/
## Sections
-1. **Plex** - URL, token (masked), library ID, Audible region, filesystem scan trigger toggle
-2. **Audiobookshelf** - URL, API token (masked), library ID, Audible region, filesystem scan trigger toggle
+1. **Plex** - URL, token (masked), library ID, Audible region, language filter toggle, filesystem scan trigger toggle
+2. **Audiobookshelf** - URL, API token (masked), library ID, Audible region, language filter toggle, filesystem scan trigger toggle
3. **Prowlarr** - URL, API key (masked), indexer selection with priority, seeding time, RSS monitoring toggle, **audiobook/ebook categories per indexer**
4. **Download Client** - Type (qBittorrent, Transmission, SABnzbd), URL, credentials (masked), custom download path (per-client relative sub-path with live preview)
5. **Paths** - Download + media directories, audiobook organization template, metadata tagging toggle, chapter merging toggle, Plex format coercion toggle
@@ -176,6 +176,11 @@ src/app/admin/settings/
- **Smart re-initialization**: Service automatically detects region changes and re-initializes before each request
- See: `documentation/integrations/audible.md` for technical details
+**Language filter toggle** ("Only show books in the region's language"):
+- Key: `audible.language_filter` (boolean as string, default off)
+- UI: `AudibleLanguageFilterOption` checkbox under the region dropdown, shared by both sections
+- Effect: hides other-language editions from search, BookDate and shelf sync. See `documentation/integrations/audible.md#region-configuration`
+
## Audiobook Organization Template
**Purpose:** Customize how audiobooks are organized within the media directory using variable-based templates.
@@ -310,9 +315,9 @@ src/app/admin/settings/
- Requires prior successful test if values changed
**PUT /api/admin/settings/audible**
-- Updates Audible region
-- Body: `{ region: string }` (one of: us, ca, uk, au, in, es, fr)
-- No validation required
+- Updates Audible region and, when sent, the language filter
+- Body: `{ region: string, languageFilter?: boolean }` (region one of: us, ca, uk, au, in, es, fr)
+- 400 if `region` is invalid or `languageFilter` is not a boolean; omitted `languageFilter` leaves the stored value unchanged
**PUT /api/admin/settings/prowlarr/indexers**
- Updates indexer configuration (enabled, priority, seeding time, RSS)
diff --git a/src/app/admin/settings/lib/helpers.ts b/src/app/admin/settings/lib/helpers.ts
index e210b3133..69199a84e 100644
--- a/src/app/admin/settings/lib/helpers.ts
+++ b/src/app/admin/settings/lib/helpers.ts
@@ -39,11 +39,14 @@ export const saveTabSettings = async (
): Promise => {
switch (activeTab) {
case 'library':
- // Save Audible region
+ // Save Audible region and language filter
await fetchWithAuth('/api/admin/settings/audible', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ region: settings.audibleRegion }),
+ body: JSON.stringify({
+ region: settings.audibleRegion,
+ languageFilter: settings.audibleLanguageFilter,
+ }),
}).then(res => {
if (!res.ok) throw new Error('Failed to save Audible region settings');
});
diff --git a/src/app/admin/settings/lib/types.ts b/src/app/admin/settings/lib/types.ts
index 46b4ab46f..58cface28 100644
--- a/src/app/admin/settings/lib/types.ts
+++ b/src/app/admin/settings/lib/types.ts
@@ -11,6 +11,7 @@ export interface Settings {
hasLocalUsers: boolean;
hasLocalAdmins: boolean;
audibleRegion: string;
+ audibleLanguageFilter: boolean;
plex: PlexSettings;
audiobookshelf: AudiobookshelfSettings;
oidc: OIDCSettings;
diff --git a/src/app/admin/settings/tabs/LibraryTab/AudibleLanguageFilterOption.tsx b/src/app/admin/settings/tabs/LibraryTab/AudibleLanguageFilterOption.tsx
new file mode 100644
index 000000000..564f42c77
--- /dev/null
+++ b/src/app/admin/settings/tabs/LibraryTab/AudibleLanguageFilterOption.tsx
@@ -0,0 +1,33 @@
+/**
+ * Component: Audible Language Filter Toggle
+ * Documentation: documentation/settings-pages.md
+ */
+
+import { Settings } from '../../lib/types';
+
+interface AudibleLanguageFilterOptionProps {
+ settings: Settings;
+ onChange: (settings: Settings) => void;
+}
+
+export function AudibleLanguageFilterOption({ settings, onChange }: AudibleLanguageFilterOptionProps) {
+ return (
+
+ );
+}
diff --git a/src/app/admin/settings/tabs/LibraryTab/AudiobookshelfSection.tsx b/src/app/admin/settings/tabs/LibraryTab/AudiobookshelfSection.tsx
index 46e6c8e9d..82ae5e89e 100644
--- a/src/app/admin/settings/tabs/LibraryTab/AudiobookshelfSection.tsx
+++ b/src/app/admin/settings/tabs/LibraryTab/AudiobookshelfSection.tsx
@@ -7,6 +7,7 @@ import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { Settings, ABSLibrary } from '../../lib/types';
import { AUDIBLE_REGIONS } from '@/lib/types/audible';
+import { AudibleLanguageFilterOption } from './AudibleLanguageFilterOption';
interface AudiobookshelfSectionProps {
settings: Settings;
@@ -199,6 +200,7 @@ export function AudiobookshelfSection({
Select the Audible region that matches your metadata engine (Audnexus/Audible Agent)
configuration in Audiobookshelf. This ensures accurate book matching and metadata.
+
diff --git a/src/app/admin/settings/tabs/LibraryTab/PlexSection.tsx b/src/app/admin/settings/tabs/LibraryTab/PlexSection.tsx
index 3ad225530..d9e4e8ec1 100644
--- a/src/app/admin/settings/tabs/LibraryTab/PlexSection.tsx
+++ b/src/app/admin/settings/tabs/LibraryTab/PlexSection.tsx
@@ -7,6 +7,7 @@ import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { Settings, PlexLibrary } from '../../lib/types';
import { AUDIBLE_REGIONS } from '@/lib/types/audible';
+import { AudibleLanguageFilterOption } from './AudibleLanguageFilterOption';
interface PlexSectionProps {
settings: Settings;
@@ -199,6 +200,7 @@ export function PlexSection({
Select the Audible region that matches your metadata engine (Audnexus/Audible Agent)
configuration in Plex. This ensures accurate book matching and metadata.
+