Skip to main content

rs_plugin_common_interfaces/domain/
library.rs

1use std::cmp::Ordering;
2
3use serde::{Deserialize, Serialize};
4use strum_macros::{Display, EnumString};
5
6use super::ElementAction;
7
8#[derive(Debug, Serialize, Deserialize, Clone, Default)]
9pub struct ServerLibrary {
10    pub id: String,
11    pub name: String,
12    pub source: String,
13    pub root: Option<String>,
14    #[serde(rename = "type")]
15    pub kind: LibraryType,
16    pub crypt: Option<bool>,
17    pub settings: ServerLibrarySettings,
18    pub credentials: Option<String>,
19    pub plugin: Option<String>,
20    pub password: Option<String>,
21
22    #[serde(default)]
23    pub hidden: bool,
24}
25
26impl ServerLibrary {
27    pub fn is_virtual(&self) -> bool {
28        self.source == "virtual"
29    }
30}
31
32/// Space of the storage holding a library, in bytes. A provider gives what it knows:
33/// one without a quota leaves out `free` and `total`.
34#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
35#[serde(rename_all = "camelCase")]
36pub struct LibraryStorage {
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub used: Option<u64>,
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub free: Option<u64>,
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub total: Option<u64>,
43    /// Libraries with the same value share this storage: count its space once.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub volume: Option<String>,
46}
47
48#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, EnumString, Default)]
49#[serde(rename_all = "camelCase")]
50#[strum(serialize_all = "camelCase")]
51pub enum LibraryRole {
52    Admin,
53    Read,
54    Write,
55    #[default]
56    None,
57}
58
59impl From<u8> for &LibraryRole {
60    fn from(level: u8) -> Self {
61        if level < 9 {
62            &LibraryRole::None
63        } else if level < 20 {
64            &LibraryRole::Read
65        } else if level < 30 {
66            &LibraryRole::Write
67        } else if level == 254 {
68            &LibraryRole::Admin
69        } else {
70            &LibraryRole::None
71        }
72    }
73}
74
75impl From<&LibraryRole> for u8 {
76    fn from(role: &LibraryRole) -> Self {
77        match role {
78            LibraryRole::Admin => 254,
79            LibraryRole::Write => 20,
80            LibraryRole::Read => 10,
81            LibraryRole::None => 0,
82        }
83    }
84}
85
86impl PartialOrd for LibraryRole {
87    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
88        let a = u8::from(self);
89        let b = u8::from(other);
90        Some(a.cmp(&b))
91    }
92}
93
94impl core::fmt::Display for LibraryRole {
95    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
96        match self {
97            LibraryRole::Admin => write!(f, "admin"),
98            LibraryRole::Read => write!(f, "read"),
99            LibraryRole::Write => write!(f, "write"),
100            LibraryRole::None => write!(f, "none"),
101        }
102    }
103}
104
105#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
106pub struct LibraryLimits {
107    #[serde(default)]
108    pub tags: bool,
109    #[serde(default)]
110    pub people: bool,
111    #[serde(default)]
112    pub albums: bool,
113    #[serde(default)]
114    pub delay: Option<i64>,
115    #[serde(default)]
116    pub user_id: Option<String>,
117}
118
119impl LibraryLimits {
120    pub fn init_with_user(user_id: Option<String>) -> Self {
121        LibraryLimits {
122            user_id,
123            ..Default::default()
124        }
125    }
126}
127
128#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, EnumString, Display)]
129#[serde(rename_all = "camelCase")]
130#[strum(serialize_all = "camelCase")]
131pub enum LibraryType {
132    Photos,
133    Shows,
134    Movies,
135    Iptv,
136    Books,
137    #[default]
138    Other,
139}
140
141#[derive(Debug, Serialize, Deserialize, Clone)]
142#[serde(rename_all = "camelCase")]
143pub struct UserMapping {
144    pub from: String,
145    pub to: String,
146}
147
148#[derive(Debug, Serialize, Deserialize, Clone, Default)]
149#[serde(rename_all = "camelCase")]
150pub struct ServerLibrarySettings {
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub face_threshold: Option<f32>,
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub ignore_groups: Option<bool>,
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub preduction_model: Option<String>,
157    /// Compute media embeddings in the background (semantic search). Off when absent.
158    #[serde(skip_serializing_if = "Option::is_none")]
159    pub embeddings: Option<bool>,
160    /// Background embedding is suspended until it is resumed. Stored here so a
161    /// pause survives a restart.
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub embeddings_paused: Option<bool>,
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub map_progress: Option<Vec<UserMapping>>,
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub data_path: Option<String>,
168
169    // IPTV settings
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub epg_url: Option<String>,
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub max_streams: Option<u32>,
174}
175
176impl ServerLibrarySettings {
177    /// Applies a change: the settings the patch does not name are kept.
178    pub fn apply(&mut self, patch: ServerLibrarySettingsPatch) {
179        patch_setting(&mut self.face_threshold, patch.face_threshold);
180        patch_setting(&mut self.ignore_groups, patch.ignore_groups);
181        patch_setting(&mut self.preduction_model, patch.preduction_model);
182        patch_setting(&mut self.embeddings, patch.embeddings);
183        patch_setting(&mut self.embeddings_paused, patch.embeddings_paused);
184        patch_setting(&mut self.map_progress, patch.map_progress);
185        patch_setting(&mut self.data_path, patch.data_path);
186        patch_setting(&mut self.epg_url, patch.epg_url);
187        patch_setting(&mut self.max_streams, patch.max_streams);
188    }
189}
190
191fn patch_setting<T>(setting: &mut Option<T>, change: Option<Option<T>>) {
192    if let Some(value) = change {
193        *setting = value;
194    }
195}
196
197/// Change to the settings of a library, read as a JSON Merge Patch (RFC 7396): a
198/// setting that is absent is kept, `null` clears it and a value replaces it.
199/// An unknown setting is refused instead of being dropped silently.
200#[derive(Debug, Serialize, Deserialize, Clone, Default)]
201#[serde(rename_all = "camelCase", deny_unknown_fields)]
202pub struct ServerLibrarySettingsPatch {
203    #[serde(default, skip_serializing_if = "Option::is_none", with = "double_option")]
204    pub face_threshold: Option<Option<f32>>,
205    #[serde(default, skip_serializing_if = "Option::is_none", with = "double_option")]
206    pub ignore_groups: Option<Option<bool>>,
207    #[serde(default, skip_serializing_if = "Option::is_none", with = "double_option")]
208    pub preduction_model: Option<Option<String>>,
209    #[serde(default, skip_serializing_if = "Option::is_none", with = "double_option")]
210    pub embeddings: Option<Option<bool>>,
211    /// Owned by the server: only the pause and resume endpoints change it. What a
212    /// client sends is read and dropped, so it can send back the settings it got.
213    #[serde(
214        default,
215        skip_serializing_if = "Option::is_none",
216        serialize_with = "double_option::serialize",
217        deserialize_with = "ignore_server_owned_setting"
218    )]
219    pub embeddings_paused: Option<Option<bool>>,
220    #[serde(default, skip_serializing_if = "Option::is_none", with = "double_option")]
221    pub map_progress: Option<Option<Vec<UserMapping>>>,
222    #[serde(default, skip_serializing_if = "Option::is_none", with = "double_option")]
223    pub data_path: Option<Option<String>>,
224
225    // IPTV settings
226    #[serde(default, skip_serializing_if = "Option::is_none", with = "double_option")]
227    pub epg_url: Option<Option<String>>,
228    #[serde(default, skip_serializing_if = "Option::is_none", with = "double_option")]
229    pub max_streams: Option<Option<u32>>,
230}
231
232impl ServerLibrarySettingsPatch {
233    /// Refuses values the server cannot work with. Only what the patch sets is
234    /// checked, so a library keeps accepting changes whatever it has stored.
235    pub fn validate(&self) -> Result<(), String> {
236        // Faces match when their cosine similarity reaches the threshold: at 0 or
237        // below every face is the same person, above 1 none ever match.
238        if let Some(Some(threshold)) = self.face_threshold {
239            if !(threshold > 0.0 && threshold <= 1.0) {
240                return Err(format!(
241                    "faceThreshold must be above 0 and at most 1, got {threshold}"
242                ));
243            }
244        }
245        // No stream could ever start with zero slots.
246        if self.max_streams == Some(Some(0)) {
247            return Err("maxStreams must be at least 1".to_string());
248        }
249        Ok(())
250    }
251}
252
253fn ignore_server_owned_setting<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
254where
255    D: serde::Deserializer<'de>,
256{
257    serde::de::IgnoredAny::deserialize(deserializer)?;
258    Ok(None)
259}
260
261/// Tells a missing field (`None`, with `#[serde(default)]`) from an explicit
262/// `null` (`Some(None)`) and a value (`Some(Some(value))`).
263mod double_option {
264    use serde::{Deserialize, Deserializer, Serialize, Serializer};
265
266    pub fn serialize<S, T>(value: &Option<Option<T>>, serializer: S) -> Result<S::Ok, S::Error>
267    where
268        S: Serializer,
269        T: Serialize,
270    {
271        match value {
272            None => serializer.serialize_unit(),
273            Some(None) => serializer.serialize_none(),
274            Some(Some(value)) => serializer.serialize_some(value),
275        }
276    }
277
278    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
279    where
280        D: Deserializer<'de>,
281        T: Deserialize<'de>,
282    {
283        Option::<T>::deserialize(deserializer).map(Some)
284    }
285}
286
287#[derive(Debug, Serialize, Deserialize, Clone)]
288#[serde(rename_all = "camelCase")]
289pub struct LibraryMessage {
290    pub action: ElementAction,
291    pub library: ServerLibrary,
292}
293
294#[derive(Debug, Serialize, Deserialize, Clone)]
295#[serde(rename_all = "camelCase")]
296pub struct LibraryStatusMessage {
297    pub message: String,
298    pub library: String,
299}
300
301#[cfg(test)]
302mod tests {
303    use std::str::FromStr;
304
305    use serde_json::{json, Value};
306
307    use super::{LibraryType, ServerLibrarySettings, ServerLibrarySettingsPatch, UserMapping};
308
309    fn patch(value: Value) -> ServerLibrarySettingsPatch {
310        serde_json::from_value(value).unwrap()
311    }
312
313    /// Every setting filled in. A new setting has to be added here, which makes
314    /// `every_setting_can_be_patched` check that the patch knows it too.
315    fn full_settings() -> ServerLibrarySettings {
316        ServerLibrarySettings {
317            face_threshold: Some(0.5),
318            ignore_groups: Some(true),
319            preduction_model: Some("model".to_string()),
320            embeddings: Some(true),
321            embeddings_paused: Some(true),
322            map_progress: Some(vec![UserMapping {
323                from: "user-a".to_string(),
324                to: "user-b".to_string(),
325            }]),
326            data_path: Some("/data".to_string()),
327            epg_url: Some("http://epg".to_string()),
328            max_streams: Some(2),
329        }
330    }
331
332    #[test]
333    fn settings_patch_keeps_what_it_does_not_name() {
334        let mut settings = full_settings();
335        settings.apply(patch(json!({ "maxStreams": 4, "epgUrl": null })));
336
337        let mut expected = serde_json::to_value(full_settings()).unwrap();
338        expected["maxStreams"] = json!(4);
339        expected.as_object_mut().unwrap().remove("epgUrl");
340        assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
341
342        settings.apply(patch(json!({})));
343        assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
344    }
345
346    #[test]
347    fn every_setting_can_be_patched() {
348        // A client may send back the settings it read: all of them are accepted,
349        // and all but the one the server owns are applied.
350        let full = serde_json::to_value(full_settings()).unwrap();
351        let mut settings = ServerLibrarySettings::default();
352        settings.apply(patch(full.clone()));
353        let mut expected = full.clone();
354        expected.as_object_mut().unwrap().remove("embeddingsPaused");
355        assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
356
357        let mut cleared = full.clone();
358        for value in cleared.as_object_mut().unwrap().values_mut() {
359            *value = Value::Null;
360        }
361        let mut settings = full_settings();
362        settings.apply(patch(cleared));
363        assert_eq!(
364            serde_json::to_value(&settings).unwrap(),
365            json!({ "embeddingsPaused": true })
366        );
367    }
368
369    #[test]
370    fn settings_patch_serializes_null_and_values_and_skips_missing() {
371        let patch = ServerLibrarySettingsPatch {
372            max_streams: Some(Some(3)),
373            epg_url: Some(None),
374            ..Default::default()
375        };
376        assert_eq!(
377            serde_json::to_value(&patch).unwrap(),
378            json!({ "maxStreams": 3, "epgUrl": null })
379        );
380    }
381
382    #[test]
383    fn settings_patch_refuses_unknown_settings() {
384        for value in [
385            json!({ "faceTreshold": 0.5 }),
386            json!({ "faceTreshold": null }),
387        ] {
388            let error = serde_json::from_value::<ServerLibrarySettingsPatch>(value).unwrap_err();
389            assert!(error.to_string().contains("faceTreshold"), "{error}");
390        }
391        assert!(serde_json::from_value::<ServerLibrarySettingsPatch>(
392            json!({ "maxStreams": "two" })
393        )
394        .is_err());
395    }
396
397    #[test]
398    fn settings_patch_from_a_client_cannot_change_the_pause() {
399        for sent in [json!(true), json!(false), Value::Null] {
400            let from_client = patch(json!({ "embeddingsPaused": sent }));
401            assert_eq!(from_client.embeddings_paused, None);
402        }
403
404        // The server sets it and clears it through the same patch.
405        let mut settings = ServerLibrarySettings::default();
406        settings.apply(ServerLibrarySettingsPatch {
407            embeddings_paused: Some(Some(true)),
408            ..Default::default()
409        });
410        assert_eq!(settings.embeddings_paused, Some(true));
411        settings.apply(ServerLibrarySettingsPatch {
412            embeddings_paused: Some(None),
413            ..Default::default()
414        });
415        assert_eq!(settings.embeddings_paused, None);
416    }
417
418    #[test]
419    fn settings_patch_checks_only_the_values_it_sets() {
420        for refused in [
421            json!({ "faceThreshold": 0 }),
422            json!({ "faceThreshold": -0.2 }),
423            json!({ "faceThreshold": 1.5 }),
424            json!({ "maxStreams": 0 }),
425        ] {
426            assert!(patch(refused.clone()).validate().is_err(), "{refused}");
427        }
428        for accepted in [
429            json!({}),
430            json!({ "faceThreshold": 0.4, "maxStreams": 1 }),
431            json!({ "faceThreshold": 1 }),
432            json!({ "faceThreshold": null, "maxStreams": null }),
433        ] {
434            assert!(patch(accepted.clone()).validate().is_ok(), "{accepted}");
435        }
436    }
437
438    #[test]
439    fn library_type_books_serde_roundtrip() {
440        let parsed: LibraryType = serde_json::from_str("\"books\"").unwrap();
441        assert_eq!(parsed, LibraryType::Books);
442
443        let serialized = serde_json::to_string(&LibraryType::Books).unwrap();
444        assert_eq!(serialized, "\"books\"");
445    }
446
447    #[test]
448    fn library_type_books_strum_roundtrip() {
449        let parsed = LibraryType::from_str("books").unwrap();
450        assert_eq!(parsed, LibraryType::Books);
451        assert_eq!(LibraryType::Books.to_string(), "books");
452    }
453}