Skip to main content

rs_plugin_common_interfaces/domain/
serie.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use strum_macros::{Display, EnumString};
4
5use crate::domain::{
6    other_ids::OtherIds,
7    rs_ids::{ApplyRsIds, RsIds},
8    tools::rating_serializer,
9};
10
11#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Display, EnumString)]
12#[serde(from = "String", into = "String")]
13#[strum(serialize_all = "snake_case")]
14pub enum SerieType {
15    Tv,
16    TvShort,
17    TvSpecial,
18    Manga,
19    Anime,
20    Movie,
21    Special,
22    Ova,
23    Ona,
24    Music,
25    Novel,
26    OneShot,
27    LightNovel,
28    Doujinshi,
29    Manhwa,
30    Manhua,
31    Oel,
32    Cm,
33    Pv,
34    Book,
35    #[strum(default)]
36    Custom(String),
37}
38
39impl SerieType {
40    pub fn from_string(value: &str) -> Self {
41        let normalized = value.to_ascii_lowercase();
42        match SerieType::try_from(normalized.as_str()) {
43            Ok(SerieType::Custom(_)) => SerieType::Custom(value.to_string()),
44            Ok(parsed) => parsed,
45            Err(_) => SerieType::Custom(value.to_string()),
46        }
47    }
48
49    pub fn to_string(&self) -> String {
50        match self {
51            SerieType::Tv => "tv".to_string(),
52            SerieType::TvShort => "tv_short".to_string(),
53            SerieType::TvSpecial => "tv_special".to_string(),
54            SerieType::Manga => "manga".to_string(),
55            SerieType::Anime => "anime".to_string(),
56            SerieType::Movie => "movie".to_string(),
57            SerieType::Special => "special".to_string(),
58            SerieType::Ova => "ova".to_string(),
59            SerieType::Ona => "ona".to_string(),
60            SerieType::Music => "music".to_string(),
61            SerieType::Novel => "novel".to_string(),
62            SerieType::OneShot => "one_shot".to_string(),
63            SerieType::LightNovel => "light_novel".to_string(),
64            SerieType::Doujinshi => "doujinshi".to_string(),
65            SerieType::Manhwa => "manhwa".to_string(),
66            SerieType::Manhua => "manhua".to_string(),
67            SerieType::Oel => "oel".to_string(),
68            SerieType::Cm => "cm".to_string(),
69            SerieType::Pv => "pv".to_string(),
70            SerieType::Book => "book".to_string(),
71            SerieType::Custom(value) => value.clone(),
72        }
73    }
74}
75
76impl From<String> for SerieType {
77    fn from(value: String) -> Self {
78        SerieType::from_string(&value)
79    }
80}
81
82impl From<SerieType> for String {
83    fn from(value: SerieType) -> Self {
84        value.to_string()
85    }
86}
87
88#[derive(Serialize, Deserialize, Default, Debug, PartialEq, Clone, Display, EnumString)]
89#[serde(rename_all = "camelCase")]
90#[strum(serialize_all = "camelCase")]
91pub enum SerieStatus {
92    Returning,
93    InProduction,
94    PostProduction,
95    Planned,
96    Rumored,
97    Ended,
98    Released,
99    Canceled,
100    Pilot,
101    #[strum(default)]
102    Other(String),
103    #[default]
104    Unknown,
105}
106
107#[derive(Debug, Serialize, PartialEq, Deserialize, Clone, Default)]
108#[serde(rename_all = "camelCase")]
109pub struct Serie {
110    #[serde(default)]
111    pub id: String,
112
113    pub name: String,
114    #[serde(skip_serializing_if = "Option::is_none")]
115    #[serde(rename = "type")]
116    pub kind: Option<SerieType>,
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub alt: Option<Vec<String>>,
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub status: Option<SerieStatus>,
121    pub params: Option<Value>,
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub imdb: Option<String>,
124    pub slug: Option<String>,
125    pub tmdb: Option<u64>,
126    pub trakt: Option<u64>,
127    pub tvdb: Option<u64>,
128    pub otherids: Option<OtherIds>,
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub openlibrary_work_id: Option<String>,
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub anilist_manga_id: Option<u64>,
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub mangadex_manga_uuid: Option<String>,
135    #[serde(skip_serializing_if = "Option::is_none")]
136    pub myanimelist_manga_id: Option<u64>,
137
138    /// Original language of the show (ISO 639-1, e.g. "en").
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub lang: Option<String>,
141    /// Original title of the show.
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub original: Option<String>,
144    /// Synopsis of the show.
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub overview: Option<String>,
147
148    #[serde(serialize_with = "rating_serializer")]
149    pub imdb_rating: Option<f32>,
150    pub imdb_votes: Option<u64>,
151    #[serde(serialize_with = "rating_serializer")]
152    pub trakt_rating: Option<f32>,
153    pub trakt_votes: Option<u64>,
154
155    pub trailer: Option<String>,
156
157    pub year: Option<u16>,
158
159    pub max_created: Option<i64>,
160
161    #[serde(default)]
162    pub modified: u64,
163    #[serde(default)]
164    pub added: u64,
165
166    #[serde(default)]
167    pub posterv: u64,
168    #[serde(default)]
169    pub backgroundv: u64,
170    #[serde(default)]
171    pub cardv: u64,
172}
173
174impl From<Serie> for RsIds {
175    fn from(value: Serie) -> Self {
176        let mut ids = RsIds::default();
177        if let Some(v) = value.trakt { ids.set("trakt", v); }
178        if let Some(v) = value.slug { ids.set("slug", v); }
179        if let Some(v) = value.tvdb { ids.set("tvdb", v); }
180        if let Some(v) = value.imdb { ids.set("imdb", v); }
181        if let Some(v) = value.tmdb { ids.set("tmdb", v); }
182        if let Some(v) = value.anilist_manga_id { ids.set("anilist", v); }
183        if let Some(v) = value.mangadex_manga_uuid { ids.set("mangadex", v); }
184        if let Some(v) = value.myanimelist_manga_id { ids.set("mal", v); }
185        if let Some(v) = value.openlibrary_work_id { ids.set("olwid", v); }
186        if let Some(other) = value.otherids {
187            for entry in other.into_vec() {
188                let _ = ids.try_add(entry);
189            }
190        }
191        if ids.try_add(value.id.clone()).is_err() {
192            ids.set("redseat", value.id);
193        }
194        ids
195    }
196}
197
198impl ApplyRsIds for Serie {
199    fn apply_rs_ids(&mut self, ids: &RsIds) {
200        if let Some(redseat) = ids.redseat() {
201            self.id = redseat.to_string();
202        }
203        if let Some(trakt) = ids.trakt() {
204            self.trakt = Some(trakt);
205        }
206        if let Some(slug) = ids.slug() {
207            self.slug = Some(slug.to_string());
208        }
209        if let Some(tvdb) = ids.tvdb() {
210            self.tvdb = Some(tvdb);
211        }
212        if let Some(imdb) = ids.imdb() {
213            self.imdb = Some(imdb.to_string());
214        }
215        if let Some(tmdb) = ids.tmdb() {
216            self.tmdb = Some(tmdb);
217        }
218        if let Some(olwid) = ids.openlibrary_work_id() {
219            self.openlibrary_work_id = Some(olwid.to_string());
220        }
221        if let Some(anilist) = ids.anilist_manga_id() {
222            self.anilist_manga_id = Some(anilist);
223        }
224        if let Some(mangadex) = ids.mangadex_manga_uuid() {
225            self.mangadex_manga_uuid = Some(mangadex.to_string());
226        }
227        if let Some(mal) = ids.myanimelist_manga_id() {
228            self.myanimelist_manga_id = Some(mal);
229        }
230        let known: &[&str] = &["redseat", "trakt", "slug", "tvdb", "imdb", "tmdb", "olwid", "anilist", "mangadex", "mal"];
231        let mut other = self.otherids.take().unwrap_or_default();
232        for (k, v) in ids.iter() {
233            if !known.contains(&k.as_str()) { other.add(k, v); }
234        }
235        if !other.as_slice().is_empty() { self.otherids = Some(other); }
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use serde_json::json;
242
243    use super::{Serie, SerieType};
244    use crate::domain::{
245        other_ids::OtherIds,
246        rs_ids::{ApplyRsIds, RsIds},
247    };
248
249    #[test]
250    fn serie_type_serde() {
251        let known: SerieType = serde_json::from_str("\"tv\"").unwrap();
252        assert_eq!(known, SerieType::Tv);
253        let known_snake_case: SerieType = serde_json::from_str("\"one_shot\"").unwrap();
254        assert_eq!(known_snake_case, SerieType::OneShot);
255        let known_case_insensitive: SerieType = serde_json::from_str("\"TV_SPECIAL\"").unwrap();
256        assert_eq!(known_case_insensitive, SerieType::TvSpecial);
257
258        let custom: SerieType = serde_json::from_str("\"manhwa\"").unwrap();
259        assert_eq!(custom, SerieType::Manhwa);
260        let custom: SerieType = serde_json::from_str("\"webtoon\"").unwrap();
261        assert_eq!(custom, SerieType::Custom("webtoon".to_string()));
262
263        assert_eq!(
264            serde_json::to_string(&SerieType::Anime).unwrap(),
265            "\"anime\""
266        );
267        assert_eq!(
268            serde_json::to_string(&SerieType::Custom("lightnovel".to_string())).unwrap(),
269            "\"lightnovel\""
270        );
271        assert_eq!(
272            serde_json::to_string(&SerieType::LightNovel).unwrap(),
273            "\"light_novel\""
274        );
275    }
276
277    #[test]
278    fn serie_otherids_serializes_as_array_and_rejects_string() {
279        let serie = Serie {
280            id: "serie-1".to_string(),
281            name: "Serie 1".to_string(),
282            otherids: Some(OtherIds(vec!["tvmaze:123".to_string()])),
283            ..Default::default()
284        };
285        let value = serde_json::to_value(&serie).unwrap();
286        assert_eq!(value.get("otherids"), Some(&json!(["tvmaze:123"])));
287
288        let parsed: Serie = serde_json::from_value(json!({
289            "id": "serie-1",
290            "name": "Serie 1",
291            "otherids": ["anidb:12"]
292        }))
293        .unwrap();
294        assert_eq!(
295            parsed.otherids,
296            Some(OtherIds(vec!["anidb:12".to_string()]))
297        );
298
299        let invalid = serde_json::from_value::<Serie>(json!({
300            "id": "serie-1",
301            "name": "Serie 1",
302            "otherids": "anidb:12"
303        }));
304        assert!(invalid.is_err());
305    }
306
307    #[test]
308    fn serie_lang_original_and_overview_round_trip_and_are_omitted_when_none() {
309        let serie = Serie {
310            id: "serie-1".to_string(),
311            name: "Dark".to_string(),
312            lang: Some("de".to_string()),
313            original: Some("Dark".to_string()),
314            overview: Some("A missing child sets four families on a hunt.".to_string()),
315            ..Default::default()
316        };
317        let value = serde_json::to_value(&serie).unwrap();
318        assert_eq!(value.get("lang"), Some(&json!("de")));
319        assert_eq!(value.get("original"), Some(&json!("Dark")));
320        assert_eq!(value.get("overview"), Some(&json!("A missing child sets four families on a hunt.")));
321        assert_eq!(serde_json::from_value::<Serie>(value).unwrap(), serie);
322
323        let value = serde_json::to_value(Serie { name: "Serie".to_string(), ..Default::default() }).unwrap();
324        assert!(value.get("lang").is_none());
325        assert!(value.get("original").is_none());
326        assert!(value.get("overview").is_none());
327    }
328
329    #[test]
330    fn serie_apply_rs_ids_updates_only_present_values() {
331        let mut serie = Serie {
332            id: "serie-old".to_string(),
333            name: "Serie 1".to_string(),
334            tvdb: Some(500),
335            ..Default::default()
336        };
337        let mut ids = RsIds::default();
338        ids.set("redseat", "serie-new");
339        ids.set("trakt", 101u64);
340        ids.set("imdb", "tt0000101");
341        ids.set("tmdb", 201u64);
342        ids.set("slug", "serie-slug");
343        ids.set("anilist", 301u64);
344        ids.set("mangadex", "uuid-123");
345        ids.set("mal", 401u64);
346        ids.set("olwid", "olw-123");
347
348        serie.apply_rs_ids(&ids);
349
350        assert_eq!(serie.id, "serie-new");
351        assert_eq!(serie.trakt, Some(101));
352        assert_eq!(serie.imdb.as_deref(), Some("tt0000101"));
353        assert_eq!(serie.tmdb, Some(201));
354        assert_eq!(serie.slug.as_deref(), Some("serie-slug"));
355        assert_eq!(serie.tvdb, Some(500));
356        assert_eq!(serie.anilist_manga_id, Some(301));
357        assert_eq!(serie.mangadex_manga_uuid.as_deref(), Some("uuid-123"));
358        assert_eq!(serie.myanimelist_manga_id, Some(401));
359        assert_eq!(serie.openlibrary_work_id.as_deref(), Some("olw-123"));
360    }
361}
362
363#[derive(Debug, Serialize, Deserialize, Clone)]
364#[serde(rename_all = "camelCase")]
365pub struct SerieWithAction {
366    pub action: crate::domain::ElementAction,
367    pub serie: crate::domain::ItemWithRelations<Serie>,
368}
369
370#[derive(Debug, Serialize, Deserialize, Clone)]
371#[serde(rename_all = "camelCase")]
372pub struct SeriesMessage {
373    pub library: String,
374    pub series: Vec<SerieWithAction>,
375}
376
377/// Filter of a series list (`GET /libraries/:id/series`). Its fields keep their snake_case names in JSON.
378#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
379pub struct SerieQuery {
380    pub person: Option<String>,
381    pub role: Option<crate::domain::person::PersonType>,
382    /// Only series modified strictly after this time, in unix milliseconds.
383    pub after: Option<i64>,
384
385    pub name: Option<String>,
386
387    #[serde(default)]
388    pub sort: crate::domain::media::RsSort,
389    #[serde(default)]
390    pub order: crate::domain::media::SqlOrder,
391    pub limit: Option<u32>,
392    pub offset: Option<u32>,
393}
394
395impl SerieQuery {
396    pub fn new_empty() -> SerieQuery {
397        SerieQuery::default()
398    }
399    pub fn from_after(after: i64) -> SerieQuery {
400        SerieQuery {
401            after: Some(after),
402            ..Default::default()
403        }
404    }
405}