Skip to main content

rs_plugin_common_interfaces/domain/
person.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use crate::{
5    domain::{
6        other_ids::OtherIds,
7        rs_ids::{ApplyRsIds, RsIds},
8    },
9    url::RsLink,
10    Gender,
11};
12
13/// A person's primary type. Plugins map provider labels to canonical variants.
14/// Unknown strings are preserved verbatim; no aliases or translations are applied.
15#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
16#[serde(from = "String", into = "String")]
17pub enum PersonType {
18    Actor,
19    Director,
20    Writer,
21    Producer,
22    Creator,
23    Author,
24    Family,
25    Friends,
26    Singer,
27    /// A fictional character, including anime and manga characters.
28    Character,
29    Custom(String),
30}
31
32impl PersonType {
33    pub fn as_str(&self) -> &str {
34        match self {
35            Self::Actor => "Actor",
36            Self::Director => "Director",
37            Self::Writer => "Writer",
38            Self::Producer => "Producer",
39            Self::Creator => "Creator",
40            Self::Author => "Author",
41            Self::Family => "Family",
42            Self::Friends => "Friends",
43            Self::Singer => "Singer",
44            Self::Character => "Character",
45            Self::Custom(value) => value,
46        }
47    }
48}
49
50impl From<String> for PersonType {
51    fn from(value: String) -> Self {
52        match value.as_str() {
53            "Actor" => Self::Actor,
54            "Director" => Self::Director,
55            "Writer" => Self::Writer,
56            "Producer" => Self::Producer,
57            "Creator" => Self::Creator,
58            "Author" => Self::Author,
59            "Family" => Self::Family,
60            "Friends" => Self::Friends,
61            "Singer" => Self::Singer,
62            "Character" => Self::Character,
63            _ => Self::Custom(value),
64        }
65    }
66}
67
68impl From<&str> for PersonType {
69    fn from(value: &str) -> Self {
70        Self::from(value.to_owned())
71    }
72}
73
74impl From<PersonType> for String {
75    fn from(value: PersonType) -> Self {
76        match value {
77            PersonType::Custom(value) => value,
78            value => value.as_str().to_owned(),
79        }
80    }
81}
82
83impl std::str::FromStr for PersonType {
84    type Err = std::convert::Infallible;
85    fn from_str(value: &str) -> Result<Self, Self::Err> {
86        Ok(value.into())
87    }
88}
89
90impl std::fmt::Display for PersonType {
91    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        formatter.write_str(self.as_str())
93    }
94}
95
96#[cfg(feature = "rusqlite")]
97impl rusqlite::ToSql for PersonType {
98    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
99        Ok(rusqlite::types::ToSqlOutput::Borrowed(
100            rusqlite::types::ValueRef::Text(self.as_str().as_bytes()),
101        ))
102    }
103}
104
105#[cfg(feature = "rusqlite")]
106impl rusqlite::types::FromSql for PersonType {
107    fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
108        Ok(value.as_str()?.into())
109    }
110}
111
112#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
113#[serde(rename_all = "camelCase")]
114pub struct Person {
115    pub id: String,
116    pub name: String,
117    pub socials: Option<Vec<RsLink>>,
118    #[serde(skip_serializing_if = "Option::is_none")]
119    #[serde(rename = "type")]
120    pub kind: Option<PersonType>,
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub alt: Option<Vec<String>>,
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub portrait: Option<String>,
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub params: Option<Value>,
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub birthday: Option<i64>,
129    pub modified: u64,
130    pub added: u64,
131    pub posterv: u32,
132    #[serde(default)]
133    pub generated: bool,
134
135    pub imdb: Option<String>,
136    pub slug: Option<String>,
137    pub tmdb: Option<u64>,
138    pub trakt: Option<u64>,
139
140    pub death: Option<i64>,
141    pub gender: Option<Gender>,
142    pub country: Option<String>,
143    pub bio: Option<String>,
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub otherids: Option<OtherIds>,
146}
147
148impl ApplyRsIds for Person {
149    fn apply_rs_ids(&mut self, ids: &RsIds) {
150        if let Some(trakt) = ids.trakt() {
151            self.trakt = Some(trakt);
152        }
153        if let Some(slug) = ids.slug() {
154            self.slug = Some(slug.to_string());
155        }
156        if let Some(imdb) = ids.imdb() {
157            self.imdb = Some(imdb.to_string());
158        }
159        if let Some(tmdb) = ids.tmdb() {
160            self.tmdb = Some(tmdb);
161        }
162        let known: &[&str] = &["redseat", "trakt", "slug", "imdb", "tmdb"];
163        let mut other = self.otherids.take().unwrap_or_default();
164        for (k, v) in ids.iter() {
165            if !known.contains(&k.as_str()) {
166                other.add(k, v);
167            }
168        }
169        if !other.as_slice().is_empty() {
170            self.otherids = Some(other);
171        }
172    }
173}
174
175impl From<Person> for RsIds {
176    fn from(value: Person) -> Self {
177        let mut ids = RsIds::default();
178        if let Some(v) = value.trakt {
179            ids.set("trakt", v);
180        }
181        if let Some(v) = value.slug {
182            ids.set("slug", v);
183        }
184        if let Some(v) = value.imdb {
185            ids.set("imdb", v);
186        }
187        if let Some(v) = value.tmdb {
188            ids.set("tmdb", v);
189        }
190        if let Some(other) = value.otherids {
191            for entry in other.into_vec() {
192                let _ = ids.try_add(entry);
193            }
194        }
195        if ids.try_add(value.id.clone()).is_err() {
196            ids.set("redseat", value.id);
197        }
198        ids
199    }
200}
201
202#[cfg(test)]
203mod person_type_tests {
204    use super::*;
205
206    #[test]
207    fn canonical_types_use_plain_strings() {
208        let cases = [
209            (PersonType::Actor, "Actor"),
210            (PersonType::Director, "Director"),
211            (PersonType::Writer, "Writer"),
212            (PersonType::Producer, "Producer"),
213            (PersonType::Creator, "Creator"),
214            (PersonType::Author, "Author"),
215            (PersonType::Family, "Family"),
216            (PersonType::Friends, "Friends"),
217            (PersonType::Singer, "Singer"),
218            (PersonType::Character, "Character"),
219        ];
220        for (kind, wire) in cases {
221            let person = Person {
222                kind: Some(kind.clone()),
223                ..Default::default()
224            };
225            let json = serde_json::to_value(&person).unwrap();
226            assert_eq!(json["type"], wire);
227            assert!(json.get("kind").is_none());
228            assert_eq!(
229                serde_json::from_value::<Person>(json).unwrap().kind,
230                Some(kind.clone())
231            );
232            assert_eq!(wire.parse::<PersonType>().unwrap(), kind);
233            assert_eq!(kind.to_string(), wire);
234        }
235    }
236
237    #[test]
238    fn custom_and_legacy_strings_are_preserved_without_mapping() {
239        for value in [
240            "custom name",
241            "acting",
242            "acteur",
243            "actor",
244            "Acting",
245            "",
246            "  Family friend  ",
247            "Réalisateur",
248        ] {
249            let kind = PersonType::Custom(value.into());
250            let mut json = serde_json::to_value(Person::default()).unwrap();
251            json["type"] = value.into();
252            let person: Person = serde_json::from_value(json).unwrap();
253            assert_eq!(person.kind, Some(kind));
254            assert_eq!(serde_json::to_value(person).unwrap()["type"], value);
255        }
256    }
257
258    #[test]
259    fn missing_and_null_types_remain_optional_and_objects_are_rejected() {
260        let mut json = serde_json::to_value(Person::default()).unwrap();
261        assert!(json.get("type").is_none());
262        assert!(serde_json::from_value::<Person>(json.clone())
263            .unwrap()
264            .kind
265            .is_none());
266        json["type"] = serde_json::Value::Null;
267        assert!(serde_json::from_value::<Person>(json.clone())
268            .unwrap()
269            .kind
270            .is_none());
271        for invalid in [serde_json::json!({"Custom": "actor"}), serde_json::json!(3)] {
272            json["type"] = invalid;
273            assert!(serde_json::from_value::<Person>(json.clone()).is_err());
274        }
275    }
276
277    #[cfg(feature = "rusqlite")]
278    #[test]
279    fn sqlite_types_remain_plain_text() {
280        let conn = rusqlite::Connection::open_in_memory().unwrap();
281        conn.execute("CREATE TABLE people (type TEXT)", []).unwrap();
282        for kind in [
283            PersonType::Actor,
284            PersonType::Character,
285            PersonType::Custom("custom name".into()),
286        ] {
287            conn.execute("INSERT INTO people (type) VALUES (?)", [&kind])
288                .unwrap();
289            let (text, restored): (String, PersonType) = conn
290                .query_row(
291                    "SELECT type, type FROM people ORDER BY rowid DESC LIMIT 1",
292                    [],
293                    |row| Ok((row.get(0)?, row.get(1)?)),
294                )
295                .unwrap();
296            assert_eq!(text, kind.as_str());
297            assert_eq!(restored, kind);
298        }
299    }
300}
301
302/// A person viewed in the context of a book, movie, or show relationship.
303#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
304#[serde(rename_all = "camelCase")]
305pub struct PersonWithRoles {
306    #[serde(flatten)]
307    pub person: Person,
308    #[serde(skip_serializing_if = "Option::is_none")]
309    pub roles: Option<Vec<PersonType>>,
310    #[serde(skip_serializing_if = "Option::is_none")]
311    pub characters: Option<Vec<String>>,
312    /// Per-title credit rank, independent of person popularity. Lower comes first.
313    #[serde(skip_serializing_if = "Option::is_none")]
314    pub rank: Option<u32>,
315    /// Optional confidence of the title/person relationship.
316    #[serde(skip_serializing_if = "Option::is_none")]
317    pub conf: Option<u16>,
318}
319
320impl From<Person> for PersonWithRoles {
321    fn from(person: Person) -> Self {
322        Self { person, ..Default::default() }
323    }
324}
325
326#[cfg(test)]
327mod credit_tests {
328    use super::*;
329    use crate::domain::Relations;
330
331    #[test]
332    fn credit_objects_round_trip_with_optional_context() {
333        let credit = PersonWithRoles {
334            person: Person { id: "tmdb:1".into(), name: "Actor".into(), ..Default::default() },
335            roles: Some(vec![PersonType::Actor, PersonType::Custom("Guest".into())]),
336            characters: Some(vec!["Character".into()]),
337            rank: Some(0),
338            conf: Some(80),
339        };
340        let relations = Relations { people_details: Some(vec![credit]), ..Default::default() };
341        let wire = serde_json::to_value(&relations).unwrap();
342        assert_eq!(wire.as_object().unwrap().len(), 1);
343        let person = &wire["peopleDetails"][0];
344        assert_eq!(person["id"], "tmdb:1");
345        assert_eq!(person["rank"], 0);
346        assert_eq!(person["conf"], 80);
347        assert_eq!(person["roles"], serde_json::json!(["Actor", "Guest"]));
348        assert_eq!(person["characters"], serde_json::json!(["Character"]));
349        assert_eq!(serde_json::from_value::<Relations>(wire).unwrap(), relations);
350    }
351
352    #[test]
353    fn credit_context_is_optional_and_preserves_explicit_empty_lists() {
354        let credit = PersonWithRoles::from(Person { id: "person".into(), ..Default::default() });
355        let mut wire = serde_json::to_value(&credit).unwrap();
356        for field in ["roles", "characters", "rank", "conf"] {
357            assert!(wire.get(field).is_none());
358        }
359        assert_eq!(serde_json::from_value::<PersonWithRoles>(wire.clone()).unwrap(), credit);
360        wire["roles"] = serde_json::json!([]);
361        wire["characters"] = serde_json::json!([]);
362        let restored: PersonWithRoles = serde_json::from_value(wire).unwrap();
363        assert_eq!(restored.roles, Some(vec![]));
364        assert_eq!(restored.characters, Some(vec![]));
365    }
366
367    #[test]
368    fn credit_rank_accepts_unsigned_integers_only() {
369        let mut wire = serde_json::to_value(PersonWithRoles::default()).unwrap();
370        for rank in [0, u32::MAX] {
371            wire["rank"] = serde_json::json!(rank);
372            assert_eq!(serde_json::from_value::<PersonWithRoles>(wire.clone()).unwrap().rank, Some(rank));
373        }
374        for invalid in [serde_json::json!(-1), serde_json::json!(1.5), serde_json::json!(4294967296u64)] {
375            wire["rank"] = invalid;
376            assert!(serde_json::from_value::<PersonWithRoles>(wire.clone()).is_err());
377        }
378    }
379}
380
381#[derive(Debug, Serialize, Deserialize, Clone)]
382#[serde(rename_all = "camelCase")]
383pub struct PeopleMessage {
384    pub library: String,
385    pub people: Vec<PersonWithAction>,
386}
387
388#[derive(Debug, Serialize, Deserialize, Clone)]
389#[serde(rename_all = "camelCase")]
390pub struct PersonWithAction {
391    pub action: crate::domain::ElementAction,
392    pub person: Person,
393}
394
395/// A detected face not linked to a person yet.
396#[derive(Debug, Serialize, Deserialize, Clone)]
397#[serde(rename_all = "camelCase")]
398pub struct UnassignedFace {
399    pub id: String,
400    pub embedding: Vec<f32>,
401    pub media_ref: String,
402    pub bbox: crate::domain::media::FaceBBox,
403    pub confidence: f32,
404    pub pose: Option<(f32, f32, f32)>,
405    pub cluster_id: Option<String>,
406    pub created: i64,
407}
408
409/// Filter of a people list (`GET /libraries/:id/people`). Its fields keep their snake_case names in JSON.
410#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
411pub struct PeopleQuery {
412    /// Only people modified strictly after this time, in unix milliseconds.
413    pub after: Option<i64>,
414    pub name: Option<String>,
415    pub limit: Option<u32>,
416    pub offset: Option<u32>,
417}
418
419impl PeopleQuery {
420    pub fn new_empty() -> PeopleQuery {
421        PeopleQuery::default()
422    }
423    pub fn from_after(after: i64) -> PeopleQuery {
424        PeopleQuery {
425            after: Some(after),
426            ..Default::default()
427        }
428    }
429    pub fn from_name(name: &str) -> PeopleQuery {
430        PeopleQuery {
431            name: Some(name.to_owned()),
432            ..Default::default()
433        }
434    }
435}