Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions docs/chaptarr/COMPATIBILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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`:
Expand Down Expand Up @@ -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.
Expand Down
178 changes: 153 additions & 25 deletions doplarr/src/providers/chaptarr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -585,20 +586,39 @@ impl MediaBackend for Chaptarr {
async fn search(&self, term: &str) -> Result<Vec<Box<dyn MediaItem>>> {
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::<BookShape>(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!(
"{}|{}",
Expand All @@ -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()
Expand All @@ -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()) {
Expand All @@ -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<dyn MediaItem>)
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -925,6 +965,17 @@ mod tests {
}
}

fn audiobook_projection_item() -> ChaptarrItem {
let rows: Vec<Value> = 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>,
) -> (String, Arc<Mutex<Vec<String>>>, tokio::task::JoinHandle<()>) {
Expand Down Expand Up @@ -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);
Expand All @@ -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()
Expand All @@ -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::<ChaptarrItem>().unwrap();
assert_eq!(item.book.media_type, "audiobook");
assert_eq!(item.existing_book_id, None);
assert!(
chaptarr
.additional_details(results[0].as_ref())
Expand All @@ -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::<ChaptarrItem>().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::<ChaptarrItem>().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!({
Expand Down
33 changes: 27 additions & 6 deletions doplarr/src/providers/chaptarr/selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Profile> = serde_json::from_str(QUALITY).unwrap();
Expand Down
27 changes: 27 additions & 0 deletions doplarr/tests/fixtures/chaptarr/lookup_audiobook_projection.json
Original file line number Diff line number Diff line change
@@ -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": []
}
]