1use serde::{Deserialize, Serialize};
10
11pub const MAX_FILTER_VALUES: usize = 64;
14
15pub const MAX_FILTER_TEXT: usize = 128;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum SortKey {
22 Title,
25 Released,
27 Added,
29 LastPlayed,
32 Rating,
35 AudienceRating,
38 Duration,
41 Size,
45 #[serde(other)]
47 Unknown,
48}
49
50impl SortKey {
51 pub const ALL: [SortKey; 8] = [
53 SortKey::Title,
54 SortKey::Released,
55 SortKey::Added,
56 SortKey::LastPlayed,
57 SortKey::Rating,
58 SortKey::AudienceRating,
59 SortKey::Duration,
60 SortKey::Size,
61 ];
62
63 pub fn as_str(self) -> &'static str {
65 match self {
66 SortKey::Title => "title",
67 SortKey::Released => "released",
68 SortKey::Added => "added",
69 SortKey::LastPlayed => "last_played",
70 SortKey::Rating => "rating",
71 SortKey::AudienceRating => "audience_rating",
72 SortKey::Duration => "duration",
73 SortKey::Size => "size",
74 SortKey::Unknown => "unknown",
75 }
76 }
77
78 pub fn parse(name: &str) -> Option<SortKey> {
81 SortKey::ALL.into_iter().find(|k| k.as_str() == name)
82 }
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
89pub struct ItemSort {
90 pub key: SortKey,
91 #[serde(default)]
93 pub descending: bool,
94}
95
96impl ItemSort {
97 pub const DEFAULT: ItemSort = ItemSort {
99 key: SortKey::Title,
100 descending: false,
101 };
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
110#[serde(rename_all = "snake_case")]
111pub enum WatchedState {
112 Unwatched,
113 InProgress,
114 Watched,
115 #[serde(other)]
117 Unknown,
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
122pub enum Resolution {
123 #[serde(rename = "4k")]
125 Uhd,
126 #[serde(rename = "1080p")]
128 FullHd,
129 #[serde(rename = "720p")]
131 Hd,
132 #[serde(rename = "sd")]
134 Sd,
135 #[serde(other, rename = "unknown")]
137 Unknown,
138}
139
140impl Resolution {
141 pub fn of(width: Option<u32>, height: Option<u32>) -> Option<Resolution> {
145 let by_height = |h: u32| match h {
146 h if h >= 1600 => Resolution::Uhd,
147 h if h >= 900 => Resolution::FullHd,
148 h if h >= 650 => Resolution::Hd,
149 _ => Resolution::Sd,
150 };
151 let by_width = |w: u32| match w {
152 w if w >= 3200 => Resolution::Uhd,
153 w if w >= 1800 => Resolution::FullHd,
154 w if w >= 1200 => Resolution::Hd,
155 _ => Resolution::Sd,
156 };
157 match (width, height) {
158 (Some(w), Some(h)) => Some(by_height(h).min(by_width(w))),
159 (None, Some(h)) => Some(by_height(h)),
160 (Some(w), None) => Some(by_width(w)),
161 (None, None) => None,
162 }
163 }
164
165 pub fn of_plex(name: &str) -> Option<Resolution> {
168 Some(match name.trim().to_ascii_lowercase().as_str() {
169 "4k" | "2160" | "2160p" => Resolution::Uhd,
170 "1080" | "1080p" => Resolution::FullHd,
171 "720" | "720p" => Resolution::Hd,
172 "" => return None,
173 other if other.trim_end_matches('p').parse::<u32>().is_ok() || other == "sd" => {
174 Resolution::Sd
175 }
176 _ => return None,
177 })
178 }
179
180 pub fn as_str(self) -> &'static str {
182 match self {
183 Resolution::Uhd => "4k",
184 Resolution::FullHd => "1080p",
185 Resolution::Hd => "720p",
186 Resolution::Sd => "sd",
187 Resolution::Unknown => "unknown",
188 }
189 }
190
191 pub fn parse(name: &str) -> Option<Resolution> {
194 [
195 Resolution::Uhd,
196 Resolution::FullHd,
197 Resolution::Hd,
198 Resolution::Sd,
199 ]
200 .into_iter()
201 .find(|r| r.as_str() == name)
202 }
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
208#[serde(rename_all = "snake_case")]
209pub enum DynamicRange {
210 Sdr,
212 Hdr,
215 DolbyVision,
217 #[serde(other)]
219 Unknown,
220}
221
222#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
226pub struct ItemFilter {
227 #[serde(default, skip_serializing_if = "Vec::is_empty")]
229 pub watched: Vec<WatchedState>,
230 #[serde(default, skip_serializing_if = "Vec::is_empty")]
233 pub genres: Vec<String>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub year_from: Option<u16>,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub year_to: Option<u16>,
240 #[serde(default, skip_serializing_if = "Vec::is_empty")]
241 pub resolutions: Vec<Resolution>,
242 #[serde(default, skip_serializing_if = "Vec::is_empty")]
243 pub dynamic_ranges: Vec<DynamicRange>,
244 #[serde(default, skip_serializing_if = "Vec::is_empty")]
247 pub content_ratings: Vec<String>,
248}
249
250#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
252pub enum BrowseError {
253 #[error("unknown sort key")]
254 UnknownSort,
255 #[error("unknown {0} in the filter")]
256 UnknownValue(&'static str),
257 #[error("{0} lists more than {MAX_FILTER_VALUES} values")]
258 TooMany(&'static str),
259 #[error("a {0} in the filter is longer than {MAX_FILTER_TEXT} characters")]
260 TooLong(&'static str),
261 #[error("year_from {from} is after year_to {to}")]
262 Years { from: u16, to: u16 },
263}
264
265impl ItemSort {
266 pub fn check(&self) -> Result<(), BrowseError> {
268 match self.key {
269 SortKey::Unknown => Err(BrowseError::UnknownSort),
270 _ => Ok(()),
271 }
272 }
273}
274
275impl ItemFilter {
276 pub fn is_empty(&self) -> bool {
278 *self == ItemFilter::default()
279 }
280
281 pub fn check(&self) -> Result<(), BrowseError> {
285 fn list<T>(name: &'static str, values: &[T]) -> Result<(), BrowseError> {
286 if values.len() > MAX_FILTER_VALUES {
287 return Err(BrowseError::TooMany(name));
288 }
289 Ok(())
290 }
291 fn texts(name: &'static str, values: &[String]) -> Result<(), BrowseError> {
292 list(name, values)?;
293 if values.iter().any(|v| v.chars().count() > MAX_FILTER_TEXT) {
294 return Err(BrowseError::TooLong(name));
295 }
296 Ok(())
297 }
298 list("watched", &self.watched)?;
299 if self.watched.contains(&WatchedState::Unknown) {
300 return Err(BrowseError::UnknownValue("watched state"));
301 }
302 texts("genres", &self.genres)?;
303 texts("content_ratings", &self.content_ratings)?;
304 list("resolutions", &self.resolutions)?;
305 if self.resolutions.contains(&Resolution::Unknown) {
306 return Err(BrowseError::UnknownValue("resolution"));
307 }
308 list("dynamic_ranges", &self.dynamic_ranges)?;
309 if self.dynamic_ranges.contains(&DynamicRange::Unknown) {
310 return Err(BrowseError::UnknownValue("dynamic range"));
311 }
312 if let (Some(from), Some(to)) = (self.year_from, self.year_to)
313 && from > to
314 {
315 return Err(BrowseError::Years { from, to });
316 }
317 Ok(())
318 }
319}
320
321#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
325pub struct Counted<T> {
326 pub value: T,
327 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub count: Option<u32>,
329}
330
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
333#[serde(rename_all = "snake_case")]
334pub enum FilterPart {
335 Watched,
336 Genres,
337 Years,
338 ContentRatings,
339 Resolutions,
340 DynamicRanges,
341 #[serde(other)]
343 Unknown,
344}
345
346impl FilterPart {
347 pub fn as_str(self) -> &'static str {
349 match self {
350 FilterPart::Watched => "watched",
351 FilterPart::Genres => "genres",
352 FilterPart::Years => "years",
353 FilterPart::ContentRatings => "content_ratings",
354 FilterPart::Resolutions => "resolutions",
355 FilterPart::DynamicRanges => "dynamic_ranges",
356 FilterPart::Unknown => "unknown",
357 }
358 }
359}
360
361impl ItemFilter {
362 pub fn parts(&self) -> Vec<FilterPart> {
364 let mut parts = Vec::new();
365 if !self.watched.is_empty() {
366 parts.push(FilterPart::Watched);
367 }
368 if !self.genres.is_empty() {
369 parts.push(FilterPart::Genres);
370 }
371 if self.year_from.is_some() || self.year_to.is_some() {
372 parts.push(FilterPart::Years);
373 }
374 if !self.content_ratings.is_empty() {
375 parts.push(FilterPart::ContentRatings);
376 }
377 if !self.resolutions.is_empty() {
378 parts.push(FilterPart::Resolutions);
379 }
380 if !self.dynamic_ranges.is_empty() {
381 parts.push(FilterPart::DynamicRanges);
382 }
383 parts
384 }
385}
386
387#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
391pub struct ItemFilterValues {
392 #[serde(default)]
394 pub genres: Vec<Counted<String>>,
395 #[serde(default)]
397 pub years: Vec<Counted<u16>>,
398 #[serde(default)]
400 pub content_ratings: Vec<Counted<String>>,
401 #[serde(default)]
403 pub resolutions: Vec<Counted<Resolution>>,
404 #[serde(default)]
409 pub dynamic_ranges: Vec<Counted<DynamicRange>>,
410 #[serde(default)]
414 pub sorts: Vec<SortKey>,
415 #[serde(default)]
419 pub filters: Vec<FilterPart>,
420}
421
422impl ItemFilterValues {
423 pub fn refuses(&self, sort: Option<&ItemSort>, filter: Option<&ItemFilter>) -> Option<String> {
426 if let Some(sort) = sort
427 && !self.sorts.contains(&sort.key)
428 {
429 return Some(format!(
430 "this library cannot be sorted by {}",
431 sort.key.as_str()
432 ));
433 }
434 let filter = filter?;
435 if let Some(part) = filter
436 .parts()
437 .into_iter()
438 .find(|p| !self.filters.contains(p))
439 {
440 return Some(format!(
441 "this library cannot be filtered by {}",
442 part.as_str()
443 ));
444 }
445 if let Some(range) = filter
446 .dynamic_ranges
447 .iter()
448 .find(|r| !self.dynamic_ranges.iter().any(|c| c.value == **r))
449 {
450 return Some(format!("this library cannot be filtered by {range:?}"));
451 }
452 None
453 }
454}
455
456pub fn sort_title(title: &str) -> &str {
460 let trimmed = title.trim_start();
461 for article in ["the ", "a ", "an "] {
462 if trimmed.len() > article.len()
463 && trimmed.is_char_boundary(article.len())
464 && trimmed[..article.len()].eq_ignore_ascii_case(article)
465 {
466 let rest = trimmed[article.len()..].trim_start();
467 if !rest.is_empty() {
468 return rest;
469 }
470 }
471 }
472 trimmed
473}
474
475#[cfg(test)]
476mod tests {
477 use super::*;
478
479 #[test]
480 fn a_sort_and_a_filter_are_snake_case_on_the_wire() {
481 let sort = ItemSort {
482 key: SortKey::LastPlayed,
483 descending: true,
484 };
485 assert_eq!(
486 serde_json::to_value(sort).unwrap(),
487 serde_json::json!({"key": "last_played", "descending": true})
488 );
489 let filter = ItemFilter {
490 watched: vec![WatchedState::InProgress],
491 resolutions: vec![Resolution::Uhd, Resolution::Sd],
492 dynamic_ranges: vec![DynamicRange::DolbyVision],
493 year_from: Some(1990),
494 ..ItemFilter::default()
495 };
496 assert_eq!(
497 serde_json::to_value(&filter).unwrap(),
498 serde_json::json!({
499 "watched": ["in_progress"],
500 "resolutions": ["4k", "sd"],
501 "dynamic_ranges": ["dolby_vision"],
502 "year_from": 1990,
503 })
504 );
505 }
506
507 #[test]
508 fn a_sort_without_a_direction_is_ascending() {
509 let sort: ItemSort = serde_json::from_value(serde_json::json!({"key": "size"})).unwrap();
510 assert_eq!(
511 sort,
512 ItemSort {
513 key: SortKey::Size,
514 descending: false
515 }
516 );
517 }
518
519 #[test]
520 fn values_from_a_newer_peer_read_as_unknown_and_are_refused() {
521 let sort: ItemSort =
522 serde_json::from_value(serde_json::json!({"key": "loudness"})).unwrap();
523 assert_eq!(sort.key, SortKey::Unknown);
524 assert_eq!(sort.check(), Err(BrowseError::UnknownSort));
525 let filter: ItemFilter = serde_json::from_value(serde_json::json!({
526 "resolutions": ["8k"],
527 }))
528 .unwrap();
529 assert_eq!(filter.check(), Err(BrowseError::UnknownValue("resolution")));
530 let filter: ItemFilter = serde_json::from_value(serde_json::json!({
531 "watched": ["abandoned"],
532 }))
533 .unwrap();
534 assert!(filter.check().is_err());
535 let filter: ItemFilter = serde_json::from_value(serde_json::json!({
536 "dynamic_ranges": ["hdr12"],
537 }))
538 .unwrap();
539 assert!(filter.check().is_err());
540 }
541
542 #[test]
543 fn years_out_of_order_and_long_lists_are_refused() {
544 let years = ItemFilter {
545 year_from: Some(2000),
546 year_to: Some(1990),
547 ..ItemFilter::default()
548 };
549 assert_eq!(
550 years.check(),
551 Err(BrowseError::Years {
552 from: 2000,
553 to: 1990
554 })
555 );
556 let many = ItemFilter {
557 genres: vec!["Drama".into(); MAX_FILTER_VALUES + 1],
558 ..ItemFilter::default()
559 };
560 assert_eq!(many.check(), Err(BrowseError::TooMany("genres")));
561 let long = ItemFilter {
562 content_ratings: vec!["x".repeat(MAX_FILTER_TEXT + 1)],
563 ..ItemFilter::default()
564 };
565 assert_eq!(long.check(), Err(BrowseError::TooLong("content_ratings")));
566 let decade = ItemFilter {
567 year_from: Some(1990),
568 year_to: Some(1999),
569 ..ItemFilter::default()
570 };
571 assert_eq!(decade.check(), Ok(()));
572 }
573
574 #[test]
575 fn an_empty_filter_keeps_everything_and_reads_from_nothing() {
576 let filter: ItemFilter = serde_json::from_value(serde_json::json!({})).unwrap();
577 assert!(filter.is_empty());
578 assert_eq!(
579 serde_json::to_value(&filter).unwrap(),
580 serde_json::json!({})
581 );
582 }
583
584 #[test]
585 fn the_sort_title_sets_a_leading_article_aside() {
586 assert_eq!(sort_title("The Matrix"), "Matrix");
587 assert_eq!(sort_title("a Beautiful Mind"), "Beautiful Mind");
588 assert_eq!(sort_title("An Education"), "Education");
589 assert_eq!(sort_title("Theremin"), "Theremin");
590 assert_eq!(sort_title("Anatomy"), "Anatomy");
591 assert_eq!(sort_title("The"), "The");
592 assert_eq!(sort_title("Amélie"), "Amélie");
593 assert_eq!(sort_title("A"), "A");
594 }
595
596 #[test]
597 fn resolution_classes_go_by_height_and_cropped_width() {
598 assert_eq!(
599 Resolution::of(Some(3840), Some(2160)),
600 Some(Resolution::Uhd)
601 );
602 assert_eq!(
603 Resolution::of(Some(3840), Some(1600)),
604 Some(Resolution::Uhd)
605 );
606 assert_eq!(
607 Resolution::of(Some(1920), Some(800)),
608 Some(Resolution::FullHd)
609 );
610 assert_eq!(Resolution::of(Some(1280), Some(536)), Some(Resolution::Hd));
611 assert_eq!(Resolution::of(Some(720), Some(576)), Some(Resolution::Sd));
612 assert_eq!(Resolution::of(None, None), None);
613 assert_eq!(Resolution::of_plex("4k"), Some(Resolution::Uhd));
614 assert_eq!(Resolution::of_plex("1080"), Some(Resolution::FullHd));
615 assert_eq!(Resolution::of_plex("720"), Some(Resolution::Hd));
616 assert_eq!(Resolution::of_plex("480"), Some(Resolution::Sd));
617 assert_eq!(Resolution::of_plex("sd"), Some(Resolution::Sd));
618 assert_eq!(Resolution::of_plex(""), None);
619 assert_eq!(Resolution::parse("1080p"), Some(Resolution::FullHd));
620 }
621}