diff --git a/docs/chaptarr/COMPATIBILITY.md b/docs/chaptarr/COMPATIBILITY.md index b8fdfb6..deb1ba7 100644 --- a/docs/chaptarr/COMPATIBILITY.md +++ b/docs/chaptarr/COMPATIBILITY.md @@ -33,8 +33,10 @@ put it in a URL, log line, fixture, or Discord response. | `POST` | `/command` | Queue one `BookSearch`, or a narrowly gated `RefreshAuthor` | command acknowledgement; the body is otherwise opaque | Unknown response fields must be ignored. Fields used only for ranking or -covers must be optional. A missing identity, format discriminator, or local -row ID is not optional: stop before a write rather than guessing. +covers must be optional. A missing identity is not optional. A format +discriminator and local row ID become mandatory when resolving the exact local +row before a write; they are not required merely to display a work-level lookup +result. ## Shape and field rules @@ -56,6 +58,14 @@ row ID is not optional: stop before a write rather than guessing. Lookup order is not stable and is not a ranking guarantee. Never use a local audiobook ID to satisfy an ebook request, or the reverse. +The lookup row's `mediaType` and edition `isEbook` values describe the metadata +projection Chaptarr returned; they do not prove that the work cannot be +requested in the other format. Live `0.9.720.0` testing returned only +`audiobook` projections for generic queries initiated as ebook searches. +Retain those work results, prefer a requested-format projection when the same +foreign work appears more than once, and enforce format only when selecting a +local row before mutation. + ### Profile and root discriminators Chaptarr uses two different representations for `profileType`: @@ -207,8 +217,9 @@ verifying every silent-write-prone step is more important than minimizing GETs. 4. Re-resolve the selected lookup identity. Read local author/book state and short-circuit available or already-requested rows before changing an author. 5. If the author is new, `POST /book` with both roots, all four profile IDs, - every book-level monitor flag false, only the requested format's author-level - `*MonitorFuture` gate true, and search-on-add false. If the author exists but + an explicit requested `mediaType`, every book-level monitor flag false, only + the requested format's author-level `*MonitorFuture` gate true, and + search-on-add false. If the author exists but the exact work does not, post the selected work with that local `authorId`. A post response is only an acknowledgement and never implies that a usable or correctly identified row already exists. diff --git a/doplarr/src/providers/chaptarr.rs b/doplarr/src/providers/chaptarr.rs index a5a2995..41b0c56 100644 --- a/doplarr/src/providers/chaptarr.rs +++ b/doplarr/src/providers/chaptarr.rs @@ -13,7 +13,7 @@ use serde_json::{Value, json}; use std::{ any::Any, cmp::Reverse, - collections::{HashMap, HashSet, VecDeque}, + collections::{HashMap, VecDeque}, sync::{Arc, OnceLock, Weak}, time::Duration, }; @@ -451,6 +451,7 @@ impl Chaptarr { json!({ "title": item.book.title, "foreignBookId": item.book.foreign_book_id, + "mediaType": format_name(self.format), "monitored": false, "ebookMonitored": false, "audiobookMonitored": false, @@ -585,20 +586,39 @@ impl MediaBackend for Chaptarr { async fn search(&self, term: &str) -> Result>> { info!(format = ?self.format, "Searching Chaptarr for book"); let lookup = self.lookup(term).await?; + let raw_count = lookup.len(); let mut items = Vec::new(); - let mut seen = HashSet::new(); + let mut item_affinities = Vec::new(); + let mut seen = HashMap::new(); + let mut malformed_count = 0; + let mut incomplete_identity_count = 0; + let mut junk_count = 0; + let mut duplicate_count = 0; + let mut other_format_projection_count = 0; for raw in lookup { let Ok(book) = serde_json::from_value::(raw.clone()) else { + malformed_count += 1; warn!("Skipping malformed Chaptarr lookup result"); continue; }; - if !book_identity_complete(&book) - || junk_title(&book.title) - || !search_shape_matches_format(&book, self.format) - { - debug!(title = %book.title, "Skipping incomplete or incompatible Chaptarr lookup result"); + if !book_identity_complete(&book) { + incomplete_identity_count += 1; + debug!(title = %book.title, "Skipping incomplete Chaptarr lookup result"); continue; } + if junk_title(&book.title) { + junk_count += 1; + debug!(title = %book.title, "Skipping Chaptarr lookup result marked as non-work material"); + continue; + } + // Chaptarr's lookup endpoint projects a work through one metadata + // format. A row labelled `audiobook` can still be the correct work + // for an ebook request (and vice versa), so this is a preference + // for duplicate projections, never a search-stage exclusion. + let format_affinity = search_format_affinity(&book, self.format); + if format_affinity == 0 { + other_format_projection_count += 1; + } let key = if book.foreign_book_id.is_empty() { format!( "{}|{}", @@ -608,9 +628,6 @@ impl MediaBackend for Chaptarr { } else { book.foreign_book_id.clone() }; - if !seen.insert(key) { - continue; - } let author = book.author.author_name.trim(); let display_title = if author.is_empty() { book.title.clone() @@ -624,12 +641,23 @@ impl MediaBackend for Chaptarr { ChaptarrFormat::Audiobook => &book.local_audiobook_books, }; let existing_book_id = local.iter().find_map(|b| positive_id(Some(&b.id))); - items.push(ChaptarrItem { + let item = ChaptarrItem { book, display_title, cover, existing_book_id, - }); + }; + if let Some(&index) = seen.get(&key) { + duplicate_count += 1; + if format_affinity > item_affinities[index] { + items[index] = item; + item_affinities[index] = format_affinity; + } + continue; + } + seen.insert(key, items.len()); + items.push(item); + item_affinities.push(format_affinity); } if self.openlibrary_covers && items.iter().any(|item| item.cover.is_none()) { @@ -647,7 +675,17 @@ impl MediaBackend for Chaptarr { } let query = normalize(term); items.sort_by_key(|item| Reverse(search_rank(&item.book.title, &query))); - debug!(count = items.len(), "Chaptarr search complete"); + info!( + format = ?self.format, + raw_count, + accepted_count = items.len(), + malformed_count, + incomplete_identity_count, + junk_count, + duplicate_count, + other_format_projection_count, + "Chaptarr search complete" + ); Ok(items .into_iter() .map(|item| Box::new(item) as Box) @@ -890,6 +928,8 @@ mod tests { use tokio::net::TcpListener; const LOOKUP: &str = include_str!("../../tests/fixtures/chaptarr/lookup.json"); + const AUDIOBOOK_PROJECTION_LOOKUP: &str = + include_str!("../../tests/fixtures/chaptarr/lookup_audiobook_projection.json"); const AUTHOR: &str = include_str!("../../tests/fixtures/chaptarr/author.json"); fn backend(format: ChaptarrFormat) -> Chaptarr { @@ -925,6 +965,17 @@ mod tests { } } + fn audiobook_projection_item() -> ChaptarrItem { + let rows: Vec = serde_json::from_str(AUDIOBOOK_PROJECTION_LOOKUP).unwrap(); + let book: BookShape = serde_json::from_value(rows[0].clone()).unwrap(); + ChaptarrItem { + display_title: format!("{} — {}", book.title, book.author.author_name), + cover: None, + existing_book_id: None, + book, + } + } + async fn mock_api( responses: Vec, ) -> (String, Arc>>, tokio::task::JoinHandle<()>) { @@ -1018,6 +1069,7 @@ mod tests { fn new_author_body_contains_both_format_settings_but_no_book_monitoring() { let item = lookup_item(); let body = backend(ChaptarrFormat::Audiobook).new_author_body(&item); + assert_eq!(body["mediaType"], "audiobook"); assert_eq!(body["rootFolderPath"], "/library/audiobooks"); assert_eq!(body["ebookQualityProfileId"], 11); assert_eq!(body["audiobookQualityProfileId"], 12); @@ -1029,21 +1081,24 @@ mod tests { assert_eq!(body["author"]["audiobookMonitorFuture"], true); } + #[test] + fn new_author_ebook_body_overrides_audiobook_lookup_projection() { + let item = audiobook_projection_item(); + assert_eq!(item.book.media_type, "audiobook"); + + let body = backend(ChaptarrFormat::Ebook).new_author_body(&item); + + assert_eq!(body["mediaType"], "ebook"); + assert_eq!(body["rootFolderPath"], "/library/ebooks"); + assert_eq!(body["author"]["ebookMonitorFuture"], true); + assert_eq!(body["author"]["audiobookMonitorFuture"], false); + assert_eq!(body["monitored"], false); + } + #[tokio::test] async fn search_and_confirmation_use_only_get_requests() { - let lookup = json!([{ - "title": "The Clockwork Orchard", - "overview": "A synthetic test book.", - "foreignBookId": "hc:work-1001", - "author": { - "id": 0, - "authorName": "Mara Vale", - "foreignAuthorId": "hc:author-1001" - }, - "editions": [{"isEbook": true}] - }]); let (base_url, requests, server) = - mock_api(vec![lookup.to_string(), "[]".to_string()]).await; + mock_api(vec![AUDIOBOOK_PROJECTION_LOOKUP.into(), "[]".to_string()]).await; let mut chaptarr = backend(ChaptarrFormat::Ebook); chaptarr.base_url = base_url; chaptarr.client = reqwest::Client::builder() @@ -1053,6 +1108,9 @@ mod tests { let results = chaptarr.search("Clockwork Orchard").await.unwrap(); assert_eq!(results.len(), 1); + let item = results[0].as_any().downcast_ref::().unwrap(); + assert_eq!(item.book.media_type, "audiobook"); + assert_eq!(item.existing_book_id, None); assert!( chaptarr .additional_details(results[0].as_ref()) @@ -1076,6 +1134,76 @@ mod tests { ); } + #[tokio::test] + async fn cross_format_projection_uses_only_the_requested_local_id_bridge() { + let lookup = json!([{ + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "audiobook", + "author": { + "authorName": "Mara Vale", + "foreignAuthorId": "hc:author-1001" + }, + "editions": [{"isEbook": false}], + "localEbookBooks": [{"id": 4101}], + "localAudiobookBooks": [{"id": 5101}] + }]); + let (base_url, _requests, server) = mock_api(vec![lookup.to_string()]).await; + let mut chaptarr = backend(ChaptarrFormat::Ebook); + chaptarr.base_url = base_url; + + let results = chaptarr.search("Clockwork Orchard").await.unwrap(); + assert_eq!(results.len(), 1); + let item = results[0].as_any().downcast_ref::().unwrap(); + assert_eq!(item.book.media_type, "audiobook"); + assert_eq!(item.existing_book_id, Some(4101)); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + } + + #[tokio::test] + async fn requested_format_projection_wins_when_lookup_repeats_a_work() { + let lookup = json!([ + { + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "audiobook", + "author": { + "authorName": "Mara Vale", + "foreignAuthorId": "hc:author-1001" + }, + "editions": [{"isEbook": false}], + "localEbookBooks": [] + }, + { + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "ebook", + "author": { + "authorName": "Mara Vale", + "foreignAuthorId": "hc:author-1001" + }, + "editions": [{"isEbook": true}], + "localEbookBooks": [{"id": 4101}] + } + ]); + let (base_url, _requests, server) = mock_api(vec![lookup.to_string()]).await; + let mut chaptarr = backend(ChaptarrFormat::Ebook); + chaptarr.base_url = base_url; + + let results = chaptarr.search("Clockwork Orchard").await.unwrap(); + assert_eq!(results.len(), 1); + let item = results[0].as_any().downcast_ref::().unwrap(); + assert_eq!(item.book.media_type, "ebook"); + assert_eq!(item.existing_book_id, Some(4101)); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + } + #[tokio::test] async fn new_author_audiobook_request_uses_safe_payload_and_readbacks() { let author = json!({ diff --git a/doplarr/src/providers/chaptarr/selection.rs b/doplarr/src/providers/chaptarr/selection.rs index a419af4..7e01c73 100644 --- a/doplarr/src/providers/chaptarr/selection.rs +++ b/doplarr/src/providers/chaptarr/selection.rs @@ -234,15 +234,24 @@ pub(super) fn local_row_matches_item( } } -pub(super) fn search_shape_matches_format(book: &BookShape, format: ChaptarrFormat) -> bool { +/// Rank duplicate lookup projections without treating a projection as an +/// availability claim. Chaptarr can return an audiobook-shaped projection for +/// a work requested as an ebook, so even a score of zero remains searchable. +pub(super) fn search_format_affinity(book: &BookShape, format: ChaptarrFormat) -> u8 { if !book.media_type.is_empty() { - return book.media_type.eq_ignore_ascii_case(format_name(format)); + return u8::from(book.media_type.eq_ignore_ascii_case(format_name(format))) * 3; } let flags: Vec<_> = book.editions.iter().filter_map(|e| e.is_ebook).collect(); - flags.is_empty() - || flags - .into_iter() - .any(|v| v == (format == ChaptarrFormat::Ebook)) + if flags.is_empty() { + 1 + } else if flags + .into_iter() + .any(|v| v == (format == ChaptarrFormat::Ebook)) + { + 2 + } else { + 0 + } } pub(super) fn format_is_monitored(value: &Value, format: ChaptarrFormat) -> bool { @@ -533,6 +542,18 @@ mod tests { assert!(junk_title(&junk.title)); } + #[test] + fn lookup_projection_is_a_preference_not_an_exclusion() { + let mut book = lookup_book(); + book.media_type = "audiobook".into(); + assert_eq!(search_format_affinity(&book, ChaptarrFormat::Ebook), 0); + assert_eq!(search_format_affinity(&book, ChaptarrFormat::Audiobook), 3); + + book.media_type.clear(); + assert_eq!(search_format_affinity(&book, ChaptarrFormat::Ebook), 2); + assert_eq!(search_format_affinity(&book, ChaptarrFormat::Audiobook), 2); + } + #[test] fn fixture_profiles_and_roots_resolve_exactly() { let quality: Vec = serde_json::from_str(QUALITY).unwrap(); diff --git a/doplarr/tests/fixtures/chaptarr/lookup_audiobook_projection.json b/doplarr/tests/fixtures/chaptarr/lookup_audiobook_projection.json new file mode 100644 index 0000000..606ad16 --- /dev/null +++ b/doplarr/tests/fixtures/chaptarr/lookup_audiobook_projection.json @@ -0,0 +1,27 @@ +[ + { + "id": 0, + "title": "The Clockwork Orchard", + "titleSlug": "the-clockwork-orchard-mara-vale", + "foreignBookId": "hc:work-1001", + "foreignEditionId": "az:ZZ00000001", + "releaseDate": "2024-05-14T00:00:00Z", + "overview": "A synthetic work returned through an audiobook projection.", + "mediaType": "audiobook", + "author": { + "id": 0, + "authorName": "Mara Vale", + "foreignAuthorId": "hc:author-2001" + }, + "editions": [ + { + "title": "The Clockwork Orchard", + "foreignEditionId": "az:ZZ00000001", + "isEbook": false, + "images": [] + } + ], + "localEbookBooks": [], + "localAudiobookBooks": [] + } +]