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#[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 #[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 #[serde(skip_serializing_if = "Option::is_none")]
159 pub embeddings: Option<bool>,
160 #[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 #[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 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#[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 #[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 #[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 pub fn validate(&self) -> Result<(), String> {
236 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 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
261mod 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::{
308 LibraryRole, LibraryType, ServerLibrary, ServerLibraryForRead, ServerLibrarySettings,
309 ServerLibrarySettingsPatch, UserMapping,
310 };
311
312 fn patch(value: Value) -> ServerLibrarySettingsPatch {
313 serde_json::from_value(value).unwrap()
314 }
315
316 fn full_settings() -> ServerLibrarySettings {
319 ServerLibrarySettings {
320 face_threshold: Some(0.5),
321 ignore_groups: Some(true),
322 preduction_model: Some("model".to_string()),
323 embeddings: Some(true),
324 embeddings_paused: Some(true),
325 map_progress: Some(vec![UserMapping {
326 from: "user-a".to_string(),
327 to: "user-b".to_string(),
328 }]),
329 data_path: Some("/data".to_string()),
330 epg_url: Some("http://epg".to_string()),
331 max_streams: Some(2),
332 }
333 }
334
335 #[test]
336 fn settings_patch_keeps_what_it_does_not_name() {
337 let mut settings = full_settings();
338 settings.apply(patch(json!({ "maxStreams": 4, "epgUrl": null })));
339
340 let mut expected = serde_json::to_value(full_settings()).unwrap();
341 expected["maxStreams"] = json!(4);
342 expected.as_object_mut().unwrap().remove("epgUrl");
343 assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
344
345 settings.apply(patch(json!({})));
346 assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
347 }
348
349 #[test]
350 fn every_setting_can_be_patched() {
351 let full = serde_json::to_value(full_settings()).unwrap();
354 let mut settings = ServerLibrarySettings::default();
355 settings.apply(patch(full.clone()));
356 let mut expected = full.clone();
357 expected.as_object_mut().unwrap().remove("embeddingsPaused");
358 assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
359
360 let mut cleared = full.clone();
361 for value in cleared.as_object_mut().unwrap().values_mut() {
362 *value = Value::Null;
363 }
364 let mut settings = full_settings();
365 settings.apply(patch(cleared));
366 assert_eq!(
367 serde_json::to_value(&settings).unwrap(),
368 json!({ "embeddingsPaused": true })
369 );
370 }
371
372 #[test]
373 fn settings_patch_serializes_null_and_values_and_skips_missing() {
374 let patch = ServerLibrarySettingsPatch {
375 max_streams: Some(Some(3)),
376 epg_url: Some(None),
377 ..Default::default()
378 };
379 assert_eq!(
380 serde_json::to_value(&patch).unwrap(),
381 json!({ "maxStreams": 3, "epgUrl": null })
382 );
383 }
384
385 #[test]
386 fn settings_patch_refuses_unknown_settings() {
387 for value in [
388 json!({ "faceTreshold": 0.5 }),
389 json!({ "faceTreshold": null }),
390 ] {
391 let error = serde_json::from_value::<ServerLibrarySettingsPatch>(value).unwrap_err();
392 assert!(error.to_string().contains("faceTreshold"), "{error}");
393 }
394 assert!(serde_json::from_value::<ServerLibrarySettingsPatch>(
395 json!({ "maxStreams": "two" })
396 )
397 .is_err());
398 }
399
400 #[test]
401 fn settings_patch_from_a_client_cannot_change_the_pause() {
402 for sent in [json!(true), json!(false), Value::Null] {
403 let from_client = patch(json!({ "embeddingsPaused": sent }));
404 assert_eq!(from_client.embeddings_paused, None);
405 }
406
407 let mut settings = ServerLibrarySettings::default();
409 settings.apply(ServerLibrarySettingsPatch {
410 embeddings_paused: Some(Some(true)),
411 ..Default::default()
412 });
413 assert_eq!(settings.embeddings_paused, Some(true));
414 settings.apply(ServerLibrarySettingsPatch {
415 embeddings_paused: Some(None),
416 ..Default::default()
417 });
418 assert_eq!(settings.embeddings_paused, None);
419 }
420
421 #[test]
422 fn settings_patch_checks_only_the_values_it_sets() {
423 for refused in [
424 json!({ "faceThreshold": 0 }),
425 json!({ "faceThreshold": -0.2 }),
426 json!({ "faceThreshold": 1.5 }),
427 json!({ "maxStreams": 0 }),
428 ] {
429 assert!(patch(refused.clone()).validate().is_err(), "{refused}");
430 }
431 for accepted in [
432 json!({}),
433 json!({ "faceThreshold": 0.4, "maxStreams": 1 }),
434 json!({ "faceThreshold": 1 }),
435 json!({ "faceThreshold": null, "maxStreams": null }),
436 ] {
437 assert!(patch(accepted.clone()).validate().is_ok(), "{accepted}");
438 }
439 }
440
441 #[test]
442 fn library_for_read_keeps_the_hidden_flag() {
443 let library = ServerLibrary {
444 id: "lib".into(),
445 source: "PathProvider".into(),
446 password: Some("secret".into()),
447 hidden: true,
448 ..Default::default()
449 };
450 let read = ServerLibraryForRead::from(library.clone());
451 assert!(read.hidden);
452 assert!(read.password_protected);
453 assert_eq!(read.roles, None);
454
455 let with_roles = ServerLibraryForRead::with_roles(library, &[LibraryRole::Read]);
456 assert!(with_roles.hidden);
457 assert_eq!(with_roles.roles, Some(vec![LibraryRole::Read]));
458
459 let visible = ServerLibraryForRead::from(ServerLibrary::default());
460 assert!(!visible.hidden);
461 }
462
463 #[test]
464 fn library_type_books_serde_roundtrip() {
465 let parsed: LibraryType = serde_json::from_str("\"books\"").unwrap();
466 assert_eq!(parsed, LibraryType::Books);
467
468 let serialized = serde_json::to_string(&LibraryType::Books).unwrap();
469 assert_eq!(serialized, "\"books\"");
470 }
471
472 #[test]
473 fn library_type_books_strum_roundtrip() {
474 let parsed = LibraryType::from_str("books").unwrap();
475 assert_eq!(parsed, LibraryType::Books);
476 assert_eq!(LibraryType::Books.to_string(), "books");
477 }
478}
479
480#[derive(Debug, Serialize, Deserialize, Clone, Default)]
483pub struct ServerLibraryForRead {
484 pub id: String,
485 pub name: String,
486 #[serde(skip_serializing_if = "Option::is_none")]
487 pub source: Option<String>,
488 #[serde(skip_serializing_if = "Option::is_none")]
489 pub root: Option<String>,
490 #[serde(rename = "type")]
491 pub kind: LibraryType,
492 #[serde(skip_serializing_if = "Option::is_none")]
493 pub crypt: Option<bool>,
494 #[serde(skip_serializing_if = "Option::is_none")]
495 pub settings: Option<ServerLibrarySettings>,
496 #[serde(skip_serializing_if = "Option::is_none")]
497 pub roles: Option<Vec<LibraryRole>>,
498 #[serde(default)]
499 #[serde(rename = "passwordProtected")]
500 pub password_protected: bool,
501
502 #[serde(default)]
503 pub hidden: bool,
504}
505
506impl From<ServerLibrary> for ServerLibraryForRead {
507 fn from(lib: ServerLibrary) -> Self {
508 ServerLibraryForRead {
509 id: lib.id,
510 name: lib.name,
511 source: Some(lib.source),
512 root: lib.root,
513 kind: lib.kind,
514 crypt: lib.crypt,
515 settings: Some(lib.settings),
516 roles: None,
517 password_protected: lib.password.is_some(),
518 hidden: lib.hidden,
519 }
520 }
521}
522
523impl ServerLibraryForRead {
524 pub fn with_roles(lib: ServerLibrary, roles: &[LibraryRole]) -> Self {
526 ServerLibraryForRead {
527 roles: Some(roles.to_vec()),
528 ..ServerLibraryForRead::from(lib)
529 }
530 }
531
532 pub fn is_virtual(&self) -> bool {
533 self.source.as_deref() == Some("virtual")
534 }
535
536 pub fn is_crypted(&self) -> bool {
538 self.crypt == Some(true)
539 }
540}
541
542#[derive(Debug, Serialize, Deserialize, Clone)]
544#[serde(rename_all = "camelCase")]
545pub struct LibrarySocketMessage {
546 pub action: ElementAction,
547 pub library: ServerLibraryForRead,
548}