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, Default)]
289pub struct ServerLibraryForAdd {
290 pub name: String,
291 pub source: String,
294 pub root: Option<String>,
296 pub settings: ServerLibrarySettings,
297 #[serde(rename = "type")]
298 pub kind: LibraryType,
299 pub crypt: Option<bool>,
300 pub credentials: Option<String>,
301 pub plugin: Option<String>,
302 pub password: Option<String>,
304}
305
306#[derive(Debug, Serialize, Deserialize, Clone, Default)]
308pub struct ServerLibraryForUpdate {
309 #[serde(skip_serializing_if = "Option::is_none")]
310 pub name: Option<String>,
311 #[serde(skip_serializing_if = "Option::is_none")]
312 pub source: Option<String>,
313 #[serde(skip_serializing_if = "Option::is_none")]
314 pub root: Option<String>,
315 #[serde(skip_serializing_if = "Option::is_none")]
317 pub settings: Option<ServerLibrarySettingsPatch>,
318 #[serde(skip_serializing_if = "Option::is_none")]
319 pub credentials: Option<String>,
320 #[serde(skip_serializing_if = "Option::is_none")]
321 pub plugin: Option<String>,
322 #[serde(default, skip_serializing, deserialize_with = "refuse_password_update")]
325 pub password: Option<()>,
326}
327
328fn refuse_password_update<'de, D>(deserializer: D) -> Result<Option<()>, D::Error>
329where
330 D: serde::Deserializer<'de>,
331{
332 serde::de::IgnoredAny::deserialize(deserializer)?;
333 Err(<D::Error as serde::de::Error>::custom(
334 "password changes must use the library encryption endpoint",
335 ))
336}
337
338#[derive(Debug, Serialize, Deserialize, Clone)]
340#[serde(rename_all = "camelCase")]
341pub struct LibraryEncryptionRequest {
342 pub password: String,
343}
344
345#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
349#[serde(rename_all = "camelCase")]
350pub struct LibraryEncryptionStatus {
351 pub phase: String,
354 pub processed_items: u64,
355 pub total_items: u64,
356 #[serde(skip_serializing_if = "Option::is_none")]
357 pub last_error: Option<String>,
358 pub password_protected: bool,
359 #[serde(skip_serializing_if = "Option::is_none")]
361 pub target_password_protected: Option<bool>,
362}
363
364#[derive(Debug, Serialize, Deserialize, Clone)]
365#[serde(rename_all = "camelCase")]
366pub struct LibraryMessage {
367 pub action: ElementAction,
368 pub library: ServerLibrary,
369}
370
371#[derive(Debug, Serialize, Deserialize, Clone)]
372#[serde(rename_all = "camelCase")]
373pub struct LibraryStatusMessage {
374 pub message: String,
375 pub library: String,
376}
377
378#[cfg(test)]
379mod tests {
380 use std::str::FromStr;
381
382 use serde_json::{json, Value};
383
384 use super::{
385 LibraryRole, LibraryType, ServerLibrary, ServerLibraryForRead, ServerLibrarySettings,
386 ServerLibrarySettingsPatch, UserMapping,
387 };
388
389 fn patch(value: Value) -> ServerLibrarySettingsPatch {
390 serde_json::from_value(value).unwrap()
391 }
392
393 fn full_settings() -> ServerLibrarySettings {
396 ServerLibrarySettings {
397 face_threshold: Some(0.5),
398 ignore_groups: Some(true),
399 preduction_model: Some("model".to_string()),
400 embeddings: Some(true),
401 embeddings_paused: Some(true),
402 map_progress: Some(vec![UserMapping {
403 from: "user-a".to_string(),
404 to: "user-b".to_string(),
405 }]),
406 data_path: Some("/data".to_string()),
407 epg_url: Some("http://epg".to_string()),
408 max_streams: Some(2),
409 }
410 }
411
412 #[test]
413 fn settings_patch_keeps_what_it_does_not_name() {
414 let mut settings = full_settings();
415 settings.apply(patch(json!({ "maxStreams": 4, "epgUrl": null })));
416
417 let mut expected = serde_json::to_value(full_settings()).unwrap();
418 expected["maxStreams"] = json!(4);
419 expected.as_object_mut().unwrap().remove("epgUrl");
420 assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
421
422 settings.apply(patch(json!({})));
423 assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
424 }
425
426 #[test]
427 fn every_setting_can_be_patched() {
428 let full = serde_json::to_value(full_settings()).unwrap();
431 let mut settings = ServerLibrarySettings::default();
432 settings.apply(patch(full.clone()));
433 let mut expected = full.clone();
434 expected.as_object_mut().unwrap().remove("embeddingsPaused");
435 assert_eq!(serde_json::to_value(&settings).unwrap(), expected);
436
437 let mut cleared = full.clone();
438 for value in cleared.as_object_mut().unwrap().values_mut() {
439 *value = Value::Null;
440 }
441 let mut settings = full_settings();
442 settings.apply(patch(cleared));
443 assert_eq!(
444 serde_json::to_value(&settings).unwrap(),
445 json!({ "embeddingsPaused": true })
446 );
447 }
448
449 #[test]
450 fn settings_patch_serializes_null_and_values_and_skips_missing() {
451 let patch = ServerLibrarySettingsPatch {
452 max_streams: Some(Some(3)),
453 epg_url: Some(None),
454 ..Default::default()
455 };
456 assert_eq!(
457 serde_json::to_value(&patch).unwrap(),
458 json!({ "maxStreams": 3, "epgUrl": null })
459 );
460 }
461
462 #[test]
463 fn settings_patch_refuses_unknown_settings() {
464 for value in [
465 json!({ "faceTreshold": 0.5 }),
466 json!({ "faceTreshold": null }),
467 ] {
468 let error = serde_json::from_value::<ServerLibrarySettingsPatch>(value).unwrap_err();
469 assert!(error.to_string().contains("faceTreshold"), "{error}");
470 }
471 assert!(serde_json::from_value::<ServerLibrarySettingsPatch>(
472 json!({ "maxStreams": "two" })
473 )
474 .is_err());
475 }
476
477 #[test]
478 fn settings_patch_from_a_client_cannot_change_the_pause() {
479 for sent in [json!(true), json!(false), Value::Null] {
480 let from_client = patch(json!({ "embeddingsPaused": sent }));
481 assert_eq!(from_client.embeddings_paused, None);
482 }
483
484 let mut settings = ServerLibrarySettings::default();
486 settings.apply(ServerLibrarySettingsPatch {
487 embeddings_paused: Some(Some(true)),
488 ..Default::default()
489 });
490 assert_eq!(settings.embeddings_paused, Some(true));
491 settings.apply(ServerLibrarySettingsPatch {
492 embeddings_paused: Some(None),
493 ..Default::default()
494 });
495 assert_eq!(settings.embeddings_paused, None);
496 }
497
498 #[test]
499 fn settings_patch_checks_only_the_values_it_sets() {
500 for refused in [
501 json!({ "faceThreshold": 0 }),
502 json!({ "faceThreshold": -0.2 }),
503 json!({ "faceThreshold": 1.5 }),
504 json!({ "maxStreams": 0 }),
505 ] {
506 assert!(patch(refused.clone()).validate().is_err(), "{refused}");
507 }
508 for accepted in [
509 json!({}),
510 json!({ "faceThreshold": 0.4, "maxStreams": 1 }),
511 json!({ "faceThreshold": 1 }),
512 json!({ "faceThreshold": null, "maxStreams": null }),
513 ] {
514 assert!(patch(accepted.clone()).validate().is_ok(), "{accepted}");
515 }
516 }
517
518 #[test]
519 fn library_for_read_keeps_the_hidden_flag() {
520 let library = ServerLibrary {
521 id: "lib".into(),
522 source: "PathProvider".into(),
523 password: Some("secret".into()),
524 hidden: true,
525 ..Default::default()
526 };
527 let read = ServerLibraryForRead::from(library.clone());
528 assert!(read.hidden);
529 assert!(read.password_protected);
530 assert_eq!(read.roles, None);
531
532 let with_roles = ServerLibraryForRead::with_roles(library, &[LibraryRole::Read]);
533 assert!(with_roles.hidden);
534 assert_eq!(with_roles.roles, Some(vec![LibraryRole::Read]));
535
536 let visible = ServerLibraryForRead::from(ServerLibrary::default());
537 assert!(!visible.hidden);
538 }
539
540 #[test]
541 fn library_type_books_serde_roundtrip() {
542 let parsed: LibraryType = serde_json::from_str("\"books\"").unwrap();
543 assert_eq!(parsed, LibraryType::Books);
544
545 let serialized = serde_json::to_string(&LibraryType::Books).unwrap();
546 assert_eq!(serialized, "\"books\"");
547 }
548
549 #[test]
550 fn library_type_books_strum_roundtrip() {
551 let parsed = LibraryType::from_str("books").unwrap();
552 assert_eq!(parsed, LibraryType::Books);
553 assert_eq!(LibraryType::Books.to_string(), "books");
554 }
555}
556
557#[derive(Debug, Serialize, Deserialize, Clone, Default)]
560pub struct ServerLibraryForRead {
561 pub id: String,
562 pub name: String,
563 #[serde(skip_serializing_if = "Option::is_none")]
564 pub source: Option<String>,
565 #[serde(skip_serializing_if = "Option::is_none")]
566 pub root: Option<String>,
567 #[serde(rename = "type")]
568 pub kind: LibraryType,
569 #[serde(skip_serializing_if = "Option::is_none")]
570 pub crypt: Option<bool>,
571 #[serde(skip_serializing_if = "Option::is_none")]
572 pub settings: Option<ServerLibrarySettings>,
573 #[serde(skip_serializing_if = "Option::is_none")]
574 pub roles: Option<Vec<LibraryRole>>,
575 #[serde(default)]
576 #[serde(rename = "passwordProtected")]
577 pub password_protected: bool,
578
579 #[serde(default)]
580 pub hidden: bool,
581}
582
583impl From<ServerLibrary> for ServerLibraryForRead {
584 fn from(lib: ServerLibrary) -> Self {
585 ServerLibraryForRead {
586 id: lib.id,
587 name: lib.name,
588 source: Some(lib.source),
589 root: lib.root,
590 kind: lib.kind,
591 crypt: lib.crypt,
592 settings: Some(lib.settings),
593 roles: None,
594 password_protected: lib.password.is_some(),
595 hidden: lib.hidden,
596 }
597 }
598}
599
600impl ServerLibraryForRead {
601 pub fn with_roles(lib: ServerLibrary, roles: &[LibraryRole]) -> Self {
603 ServerLibraryForRead {
604 roles: Some(roles.to_vec()),
605 ..ServerLibraryForRead::from(lib)
606 }
607 }
608
609 pub fn is_virtual(&self) -> bool {
610 self.source.as_deref() == Some("virtual")
611 }
612
613 pub fn is_crypted(&self) -> bool {
615 self.crypt == Some(true)
616 }
617}
618
619#[derive(Debug, Serialize, Deserialize, Clone)]
621#[serde(rename_all = "camelCase")]
622pub struct LibrarySocketMessage {
623 pub action: ElementAction,
624 pub library: ServerLibraryForRead,
625}