Skip to main content

rs_plugin_common_interfaces/domain/
book.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use crate::domain::{
5    media::MediaItemReference, other_ids::OtherIds, person::Person, rs_ids::{ApplyRsIds, RsIds}, tag::Tag
6};
7
8#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
9#[serde(rename_all = "camelCase")]
10pub struct Book {
11    #[serde(default)]
12    pub id: String,
13    pub name: String,
14    #[serde(skip_serializing_if = "Option::is_none")]
15    #[serde(rename = "type")]
16    pub kind: Option<String>,
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub serie_ref: Option<String>,
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub volume: Option<f64>,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub chapter: Option<f64>,
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub year: Option<u16>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub airdate: Option<i64>,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub overview: Option<String>,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub pages: Option<u32>,
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub params: Option<Value>,
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub lang: Option<String>,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub original: Option<String>,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub isbn13: Option<String>,
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub openlibrary_edition_id: Option<String>,
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub openlibrary_work_id: Option<String>,
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub google_books_volume_id: Option<String>,
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub asin: Option<String>,
47    pub otherids: Option<OtherIds>,
48    #[serde(default)]
49    pub modified: u64,
50    #[serde(default)]
51    pub added: u64,
52    /// Request-user-specific read timestamp hydrated from global history.
53    /// This is response data and is intentionally absent from `BookForUpdate`.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub watched: Option<i64>,
56}
57
58impl From<Book> for RsIds {
59    fn from(value: Book) -> Self {
60        let mut ids = RsIds::default();
61        if let Some(v) = value.isbn13 { ids.set("isbn13", v); }
62        if let Some(v) = value.openlibrary_edition_id { ids.set("oleid", v); }
63        if let Some(v) = value.openlibrary_work_id { ids.set("olwid", v); }
64        if let Some(v) = value.google_books_volume_id { ids.set("gbvid", v); }
65        if let Some(v) = value.asin { ids.set("asin", v); }
66        if let Some(v) = value.volume { ids.set("volume", v); }
67        if let Some(v) = value.chapter { ids.set("chapter", v); }
68        if let Some(other) = value.otherids {
69            for entry in other.into_vec() {
70                let _ = ids.try_add(entry);
71            }
72        }
73        if ids.try_add(value.id.clone()).is_err() {
74            ids.set("redseat", value.id);
75        }
76        ids
77    }
78}
79
80impl ApplyRsIds for Book {
81    fn apply_rs_ids(&mut self, ids: &RsIds) {
82        if let Some(redseat) = ids.redseat() {
83            self.id = redseat.to_string();
84        }
85        if let Some(isbn13) = ids.isbn13() {
86            self.isbn13 = Some(isbn13.to_string());
87        }
88        if let Some(oleid) = ids.openlibrary_edition_id() {
89            self.openlibrary_edition_id = Some(oleid.to_string());
90        }
91        if let Some(olwid) = ids.openlibrary_work_id() {
92            self.openlibrary_work_id = Some(olwid.to_string());
93        }
94        if let Some(gbvid) = ids.google_books_volume_id() {
95            self.google_books_volume_id = Some(gbvid.to_string());
96        }
97        if let Some(asin) = ids.asin() {
98            self.asin = Some(asin.to_string());
99        }
100        if let Some(volume) = ids.find_detail_f64("volume") {
101            self.volume = Some(volume);
102        }
103        if let Some(chapter) = ids.find_detail_f64("chapter") {
104            self.chapter = Some(chapter);
105        }
106        let known: &[&str] = &["redseat", "isbn13", "oleid", "olwid", "gbvid", "asin"];
107        let mut other = self.otherids.take().unwrap_or_default();
108        for (k, v) in ids.iter() {
109            if !known.contains(&k.as_str()) { other.add(k, v); }
110        }
111        if !other.as_slice().is_empty() { self.otherids = Some(other); }
112    }
113}
114
115#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
116#[serde(rename_all = "camelCase")]
117pub struct BookForUpdate {
118    pub name: Option<String>,
119    #[serde(rename = "type")]
120    pub kind: Option<String>,
121    pub serie_ref: Option<String>,
122    pub volume: Option<f64>,
123    pub chapter: Option<f64>,
124    pub year: Option<u16>,
125    pub airdate: Option<i64>,
126    pub overview: Option<String>,
127    pub pages: Option<u32>,
128    pub params: Option<Value>,
129    pub lang: Option<String>,
130    pub original: Option<String>,
131    pub isbn13: Option<String>,
132    pub openlibrary_edition_id: Option<String>,
133    pub openlibrary_work_id: Option<String>,
134    pub google_books_volume_id: Option<String>,
135    pub asin: Option<String>,
136    pub otherids: Option<OtherIds>,
137
138
139    pub add_tags: Option<Vec<MediaItemReference>>,
140    pub remove_tags: Option<Vec<String>>,
141    pub tags_lookup: Option<Vec<Tag>>,
142
143    pub add_people: Option<Vec<MediaItemReference>>,
144    pub remove_people: Option<Vec<String>>,
145    pub people_lookup: Option<Vec<Person>>,
146}
147
148impl BookForUpdate {
149    pub fn has_update(&self) -> bool {
150        self != &BookForUpdate::default()
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::Book;
157    use crate::domain::{
158        other_ids::OtherIds,
159        rs_ids::{ApplyRsIds, RsIds},
160    };
161    use serde_json::json;
162
163    #[test]
164    fn book_otherids_serializes_as_array_and_rejects_string() {
165        let book = Book {
166            id: "book-1".to_string(),
167            name: "Book 1".to_string(),
168            otherids: Some(OtherIds(vec!["goodreads:321".to_string()])),
169            ..Default::default()
170        };
171        let value = serde_json::to_value(&book).unwrap();
172        assert_eq!(value.get("otherids"), Some(&json!(["goodreads:321"])));
173
174        let parsed: Book = serde_json::from_value(json!({
175            "id": "book-1",
176            "name": "Book 1",
177            "otherids": ["custom:1"]
178        }))
179        .unwrap();
180        assert_eq!(
181            parsed.otherids,
182            Some(OtherIds(vec!["custom:1".to_string()]))
183        );
184
185        let invalid = serde_json::from_value::<Book>(json!({
186            "id": "book-1",
187            "name": "Book 1",
188            "otherids": "custom:1"
189        }));
190        assert!(invalid.is_err());
191    }
192
193    #[test]
194    fn book_apply_rs_ids_updates_only_present_values() {
195        let mut book = Book {
196            id: "book-old".to_string(),
197            name: "Book 1".to_string(),
198            openlibrary_work_id: Some("olw-old".to_string()),
199            chapter: Some(7.0),
200            ..Default::default()
201        };
202        let mut ids = RsIds::default();
203        ids.set("redseat", "book-new");
204        ids.set("isbn13", "9783161484100");
205        ids.set("oleid", "ole-new");
206        ids.set("gbvid", "gb-1");
207        ids.set("asin", "B00TEST");
208        ids.set("volume", "3");
209
210        book.apply_rs_ids(&ids);
211
212        assert_eq!(book.id, "book-new");
213        assert_eq!(book.isbn13.as_deref(), Some("9783161484100"));
214        assert_eq!(book.openlibrary_edition_id.as_deref(), Some("ole-new"));
215        assert_eq!(book.openlibrary_work_id.as_deref(), Some("olw-old"));
216        assert_eq!(book.google_books_volume_id.as_deref(), Some("gb-1"));
217        assert_eq!(book.asin.as_deref(), Some("B00TEST"));
218        assert_eq!(book.volume, Some(3.0));
219        assert_eq!(book.chapter, Some(7.0));
220    }
221
222    #[test]
223    fn book_watched_is_optional_response_data() {
224        let read = Book {
225            id: "book-1".to_string(),
226            name: "Book 1".to_string(),
227            watched: Some(1_725_000_000_123),
228            ..Default::default()
229        };
230        let read_value = serde_json::to_value(&read).unwrap();
231        assert_eq!(read_value.get("watched"), Some(&json!(1_725_000_000_123_i64)));
232
233        let unread = Book {
234            id: "book-2".to_string(),
235            name: "Book 2".to_string(),
236            ..Default::default()
237        };
238        let unread_value = serde_json::to_value(&unread).unwrap();
239        assert!(unread_value.get("watched").is_none());
240    }
241}
242
243#[derive(Debug, Serialize, Deserialize, Clone)]
244#[serde(rename_all = "camelCase")]
245pub struct BookWithAction {
246    pub action: crate::domain::ElementAction,
247    pub book: crate::domain::ItemWithRelations<Book>,
248}
249
250#[derive(Debug, Serialize, Deserialize, Clone)]
251#[serde(rename_all = "camelCase")]
252pub struct BooksMessage {
253    pub library: String,
254    pub books: Vec<BookWithAction>,
255}