Skip to main content

spoolframe_types/
browse.rs

1//! Sorting and filtering a library's items:
2//! what a client asks `Items` to order and keep, and what a library has
3//! to filter by.
4//!
5//! Every list here combines its values with OR, and the parts of an
6//! [`ItemFilter`] combine with AND: `{"genres": ["Drama", "Comedy"],
7//! "year_from": 1990}` keeps the dramas and the comedies from 1990 on.
8
9use serde::{Deserialize, Serialize};
10
11/// The most values one list of an [`ItemFilter`] holds. A longer list is
12/// refused, not cut: a filter cut short would keep items it should not.
13pub const MAX_FILTER_VALUES: usize = 64;
14
15/// The longest genre or content rating a filter names, in characters.
16pub const MAX_FILTER_TEXT: usize = 128;
17
18/// What `Items` orders a library by.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum SortKey {
22    /// The sort title: the title with a leading "The", "A" or "An" set
23    /// aside, as Plex's `titleSort` does, or the catalog's own sort title.
24    Title,
25    /// The day it came out. An item without one comes last both ways.
26    Released,
27    /// When the server's catalog got it: a show by its latest episode's.
28    Added,
29    /// When the session user last watched it, from their watch state: a
30    /// show by its latest episode. Never watched comes last both ways.
31    LastPlayed,
32    /// The critic rating, 0 to 10 (Plex's `rating`). An item without one
33    /// comes last both ways.
34    Rating,
35    /// The audience rating, 0 to 10 (Plex's `audienceRating`). An item
36    /// without one comes last both ways.
37    AudienceRating,
38    /// Its running time: a movie's. An item without one comes last both
39    /// ways.
40    Duration,
41    /// Its file's size: a movie's first version. Only a paired server's
42    /// library has it: Plex does not sort by it. An item without one
43    /// comes last both ways.
44    Size,
45    /// A key this build does not know: `InvalidInput`.
46    #[serde(other)]
47    Unknown,
48}
49
50impl SortKey {
51    /// Every key this build knows, in the order a client lists them.
52    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    /// Its name on the wire.
64    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    /// The key named `name` on the wire; `None` for one this build does
79    /// not know.
80    pub fn parse(name: &str) -> Option<SortKey> {
81        SortKey::ALL.into_iter().find(|k| k.as_str() == name)
82    }
83}
84
85/// How `Items` orders a library: by `key`, then by sort title A to Z,
86/// then by id, so that items equal by `key` keep one order and a page
87/// never repeats or skips one. The tiebreakers go A to Z both ways.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
89pub struct ItemSort {
90    pub key: SortKey,
91    /// Largest, newest or last first. Missing values stay last either way.
92    #[serde(default)]
93    pub descending: bool,
94}
95
96impl ItemSort {
97    /// The order `Items` gives without one: by title, A to Z.
98    pub const DEFAULT: ItemSort = ItemSort {
99        key: SortKey::Title,
100        descending: false,
101    };
102}
103
104/// The session user's watch state of an item. A movie or an episode is
105/// watched once marked or played to the end, in progress once played past
106/// its first minutes and not yet watched, unwatched otherwise. A show is
107/// watched when every episode the library has is, in progress when some
108/// episode is watched or in progress, unwatched when none is.
109#[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    /// A state this build does not know: `InvalidInput`.
116    #[serde(other)]
117    Unknown,
118}
119
120/// An item's picture size class, by its first version's video height.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
122pub enum Resolution {
123    /// 2160 lines or more.
124    #[serde(rename = "4k")]
125    Uhd,
126    /// 1080 lines.
127    #[serde(rename = "1080p")]
128    FullHd,
129    /// 720 lines.
130    #[serde(rename = "720p")]
131    Hd,
132    /// Fewer.
133    #[serde(rename = "sd")]
134    Sd,
135    /// A class this build does not know: `InvalidInput`.
136    #[serde(other, rename = "unknown")]
137    Unknown,
138}
139
140impl Resolution {
141    /// The class of a picture `height` lines tall. A 1080p film cropped to
142    /// 2.39:1 is 1920×800, so the classes go by the width when it says
143    /// more: what Plex's own classes do.
144    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    /// The class Plex names `videoResolution`: `4k`, `1080`, `720`, `576`,
166    /// `480`, `sd`.
167    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    /// Its name on the wire and in the store.
181    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    /// The class named `name` in the store; `None` for one this build
192    /// does not know.
193    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/// What an item's picture shows of brightness and colour, by its first
206/// version.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
208#[serde(rename_all = "snake_case")]
209pub enum DynamicRange {
210    /// Neither HDR nor Dolby Vision.
211    Sdr,
212    /// Any HDR: HDR10, HDR10+, HLG, or Dolby Vision. A filter for it keeps
213    /// Dolby Vision items too.
214    Hdr,
215    /// Dolby Vision, with or without an HDR10 base.
216    DolbyVision,
217    /// A range this build does not know: `InvalidInput`.
218    #[serde(other)]
219    Unknown,
220}
221
222/// Which items `Items` keeps. Every part is optional; an empty list or
223/// `None` keeps every item as far as that part goes. An item that has no
224/// value for a part a filter names (no year, no rating) is not kept.
225#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
226pub struct ItemFilter {
227    /// The session user's watch state of it; never another user's.
228    #[serde(default, skip_serializing_if = "Vec::is_empty")]
229    pub watched: Vec<WatchedState>,
230    /// Any of these genres, by the catalog's names, as
231    /// [`ItemFilterValues::genres`] lists them; case aside.
232    #[serde(default, skip_serializing_if = "Vec::is_empty")]
233    pub genres: Vec<String>,
234    /// Its year is this or later. A decade is `1990` to `1999`.
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub year_from: Option<u16>,
237    /// Its year is this or earlier.
238    #[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    /// Any of these age ratings, as the catalog has them ("PG-13",
245    /// "TV-MA"); case aside.
246    #[serde(default, skip_serializing_if = "Vec::is_empty")]
247    pub content_ratings: Vec<String>,
248}
249
250/// Why a sort or filter cannot be used.
251#[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    /// Whether this build can use it.
267    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    /// Whether it keeps every item.
277    pub fn is_empty(&self) -> bool {
278        *self == ItemFilter::default()
279    }
280
281    /// Whether this build can use it: no value it does not know, no list
282    /// past [`MAX_FILTER_VALUES`], no text past [`MAX_FILTER_TEXT`], and
283    /// years in order.
284    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/// A value a library has, and how many of its top-level items have it
322/// when that is cheap to say: a paired server's library always says, this
323/// server's own (read from Plex) only for its resolutions and ranges.
324#[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/// A part of an [`ItemFilter`].
332#[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    /// A part this build does not know.
342    #[serde(other)]
343    Unknown,
344}
345
346impl FilterPart {
347    /// Its name on the wire.
348    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    /// The parts it uses.
363    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/// What a library's items have to filter by (`ItemFilterValues`), each
388/// list with how many top-level items have each value. A value no item
389/// has is not listed.
390#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
391pub struct ItemFilterValues {
392    /// By name, case aside.
393    #[serde(default)]
394    pub genres: Vec<Counted<String>>,
395    /// Newest first.
396    #[serde(default)]
397    pub years: Vec<Counted<u16>>,
398    /// By name.
399    #[serde(default)]
400    pub content_ratings: Vec<Counted<String>>,
401    /// Largest first.
402    #[serde(default)]
403    pub resolutions: Vec<Counted<Resolution>>,
404    /// The ranges this library can be filtered by, of SDR, HDR and Dolby
405    /// Vision. An HDR count includes Dolby Vision. One left out is
406    /// `InvalidInput` in a filter: this server's own libraries cannot be
407    /// filtered by Dolby Vision, as Plex cannot.
408    #[serde(default)]
409    pub dynamic_ranges: Vec<Counted<DynamicRange>>,
410    /// The sort keys this library orders by, in [`SortKey::ALL`]'s order.
411    /// A key left out is `InvalidInput` for this library: this server's
412    /// own libraries have no `size`, as Plex does not sort by it.
413    #[serde(default)]
414    pub sorts: Vec<SortKey>,
415    /// The parts of a filter this library applies. A part left out is
416    /// `InvalidInput` for this library: a music library has no watch
417    /// state, a TV library no resolution.
418    #[serde(default)]
419    pub filters: Vec<FilterPart>,
420}
421
422impl ItemFilterValues {
423    /// Why this library cannot be ordered by `sort` or kept by `filter`,
424    /// if it cannot: a key, a part or a range it does not list.
425    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
456/// `title` as a sort title: a leading "The", "A" or "An" and the space
457/// after it set aside, as Plex's `titleSort` does. A title that is only
458/// the article stays as it is.
459pub 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}