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#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
21#[serde(rename_all = "snake_case")]
22pub enum SortKey {
23    /// The sort title: the title with a leading "The", "A" or "An" set
24    /// aside, as Plex's `titleSort` does, or the catalog's own sort title.
25    Title,
26    /// The day it came out. An item without one comes last both ways.
27    Released,
28    /// When the server's catalog got it: a show by its latest episode's.
29    Added,
30    /// When the session user last watched it, from their watch state: a
31    /// show by its latest episode. Never watched comes last both ways.
32    LastPlayed,
33    /// The critic rating, 0 to 10 (Plex's `rating`). An item without one
34    /// comes last both ways.
35    Rating,
36    /// The audience rating, 0 to 10 (Plex's `audienceRating`). An item
37    /// without one comes last both ways.
38    AudienceRating,
39    /// Its running time: a movie's. An item without one comes last both
40    /// ways.
41    Duration,
42    /// Its file's size: a movie's first version. Only a paired server's
43    /// library has it: Plex does not sort by it. An item without one
44    /// comes last both ways.
45    Size,
46    /// A key this build does not know: `InvalidInput`.
47    #[serde(other)]
48    Unknown,
49}
50
51impl SortKey {
52    /// Every key this build knows, in the order a client lists them.
53    pub const ALL: [SortKey; 8] = [
54        SortKey::Title,
55        SortKey::Released,
56        SortKey::Added,
57        SortKey::LastPlayed,
58        SortKey::Rating,
59        SortKey::AudienceRating,
60        SortKey::Duration,
61        SortKey::Size,
62    ];
63
64    /// Its name on the wire.
65    pub fn as_str(self) -> &'static str {
66        match self {
67            SortKey::Title => "title",
68            SortKey::Released => "released",
69            SortKey::Added => "added",
70            SortKey::LastPlayed => "last_played",
71            SortKey::Rating => "rating",
72            SortKey::AudienceRating => "audience_rating",
73            SortKey::Duration => "duration",
74            SortKey::Size => "size",
75            SortKey::Unknown => "unknown",
76        }
77    }
78
79    /// The key named `name` on the wire; `None` for one this build does
80    /// not know.
81    pub fn parse(name: &str) -> Option<SortKey> {
82        SortKey::ALL.into_iter().find(|k| k.as_str() == name)
83    }
84}
85
86/// How `Items` orders a library: by `key`, then by sort title A to Z,
87/// then by id, so that items equal by `key` keep one order and a page
88/// never repeats or skips one. The tiebreakers go A to Z both ways.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
90#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
91pub struct ItemSort {
92    pub key: SortKey,
93    /// Largest, newest or last first. Missing values stay last either way.
94    #[serde(default)]
95    pub descending: bool,
96}
97
98impl ItemSort {
99    /// The order `Items` gives without one: by title, A to Z.
100    pub const DEFAULT: ItemSort = ItemSort {
101        key: SortKey::Title,
102        descending: false,
103    };
104}
105
106/// The session user's watch state of an item. A movie or an episode is
107/// watched once marked or played to the end, in progress once played past
108/// its first minutes and not yet watched, unwatched otherwise. A show is
109/// watched when every episode the library has is, in progress when some
110/// episode is watched or in progress, unwatched when none is.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
112#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
113#[serde(rename_all = "snake_case")]
114pub enum WatchedState {
115    Unwatched,
116    InProgress,
117    Watched,
118    /// A state this build does not know: `InvalidInput`.
119    #[serde(other)]
120    Unknown,
121}
122
123/// An item's picture size class, by its first version's video height.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
125#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
126pub enum Resolution {
127    /// 2160 lines or more.
128    #[serde(rename = "4k")]
129    Uhd,
130    /// 1080 lines.
131    #[serde(rename = "1080p")]
132    FullHd,
133    /// 720 lines.
134    #[serde(rename = "720p")]
135    Hd,
136    /// Fewer.
137    #[serde(rename = "sd")]
138    Sd,
139    /// A class this build does not know: `InvalidInput`.
140    #[serde(other, rename = "unknown")]
141    Unknown,
142}
143
144impl Resolution {
145    /// The class of a picture `height` lines tall. A 1080p film cropped to
146    /// 2.39:1 is 1920×800, so the classes go by the width when it says
147    /// more: what Plex's own classes do.
148    pub fn of(width: Option<u32>, height: Option<u32>) -> Option<Resolution> {
149        let by_height = |h: u32| match h {
150            h if h >= 1600 => Resolution::Uhd,
151            h if h >= 900 => Resolution::FullHd,
152            h if h >= 650 => Resolution::Hd,
153            _ => Resolution::Sd,
154        };
155        let by_width = |w: u32| match w {
156            w if w >= 3200 => Resolution::Uhd,
157            w if w >= 1800 => Resolution::FullHd,
158            w if w >= 1200 => Resolution::Hd,
159            _ => Resolution::Sd,
160        };
161        match (width, height) {
162            (Some(w), Some(h)) => Some(by_height(h).min(by_width(w))),
163            (None, Some(h)) => Some(by_height(h)),
164            (Some(w), None) => Some(by_width(w)),
165            (None, None) => None,
166        }
167    }
168
169    /// The class Plex names `videoResolution`: `4k`, `1080`, `720`, `576`,
170    /// `480`, `sd`.
171    pub fn of_plex(name: &str) -> Option<Resolution> {
172        Some(match name.trim().to_ascii_lowercase().as_str() {
173            "4k" | "2160" | "2160p" => Resolution::Uhd,
174            "1080" | "1080p" => Resolution::FullHd,
175            "720" | "720p" => Resolution::Hd,
176            "" => return None,
177            other if other.trim_end_matches('p').parse::<u32>().is_ok() || other == "sd" => {
178                Resolution::Sd
179            }
180            _ => return None,
181        })
182    }
183
184    /// Its name on the wire.
185    pub fn as_str(self) -> &'static str {
186        match self {
187            Resolution::Uhd => "4k",
188            Resolution::FullHd => "1080p",
189            Resolution::Hd => "720p",
190            Resolution::Sd => "sd",
191            Resolution::Unknown => "unknown",
192        }
193    }
194
195    /// The class named `name` on the wire; `None` for one this build
196    /// does not know.
197    pub fn parse(name: &str) -> Option<Resolution> {
198        [
199            Resolution::Uhd,
200            Resolution::FullHd,
201            Resolution::Hd,
202            Resolution::Sd,
203        ]
204        .into_iter()
205        .find(|r| r.as_str() == name)
206    }
207}
208
209/// What an item's picture shows of brightness and colour, by its first
210/// version.
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
212#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
213#[serde(rename_all = "snake_case")]
214pub enum DynamicRange {
215    /// Neither HDR nor Dolby Vision.
216    Sdr,
217    /// Any HDR: HDR10, HDR10+, HLG, or Dolby Vision. A filter for it keeps
218    /// Dolby Vision items too.
219    Hdr,
220    /// Dolby Vision, with or without an HDR10 base.
221    DolbyVision,
222    /// A range this build does not know: `InvalidInput`.
223    #[serde(other)]
224    Unknown,
225}
226
227/// Which items `Items` keeps. Every part is optional; an empty list or
228/// `None` keeps every item as far as that part goes. An item that has no
229/// value for a part a filter names (no year, no rating) is not kept.
230#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
231#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
232pub struct ItemFilter {
233    /// The session user's watch state of it; never another user's.
234    #[serde(default, skip_serializing_if = "Vec::is_empty")]
235    pub watched: Vec<WatchedState>,
236    /// Any of these genres, by the catalog's names, as
237    /// [`ItemFilterValues::genres`] lists them; case aside.
238    #[serde(default, skip_serializing_if = "Vec::is_empty")]
239    pub genres: Vec<String>,
240    /// Its year is this or later. A decade is `1990` to `1999`.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub year_from: Option<u16>,
243    /// Its year is this or earlier.
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    pub year_to: Option<u16>,
246    #[serde(default, skip_serializing_if = "Vec::is_empty")]
247    pub resolutions: Vec<Resolution>,
248    #[serde(default, skip_serializing_if = "Vec::is_empty")]
249    pub dynamic_ranges: Vec<DynamicRange>,
250    /// Any of these age ratings, as the catalog has them ("PG-13",
251    /// "TV-MA"); case aside.
252    #[serde(default, skip_serializing_if = "Vec::is_empty")]
253    pub content_ratings: Vec<String>,
254}
255
256/// Why a sort or filter cannot be used.
257#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
258pub enum BrowseError {
259    #[error("unknown sort key")]
260    UnknownSort,
261    #[error("unknown {0} in the filter")]
262    UnknownValue(&'static str),
263    #[error("{0} lists more than {MAX_FILTER_VALUES} values")]
264    TooMany(&'static str),
265    #[error("a {0} in the filter is longer than {MAX_FILTER_TEXT} characters")]
266    TooLong(&'static str),
267    #[error("year_from {from} is after year_to {to}")]
268    Years { from: u16, to: u16 },
269}
270
271impl ItemSort {
272    /// Whether this build can use it.
273    pub fn check(&self) -> Result<(), BrowseError> {
274        match self.key {
275            SortKey::Unknown => Err(BrowseError::UnknownSort),
276            _ => Ok(()),
277        }
278    }
279}
280
281impl ItemFilter {
282    /// Whether it keeps every item.
283    pub fn is_empty(&self) -> bool {
284        *self == ItemFilter::default()
285    }
286
287    /// Whether this build can use it: no value it does not know, no list
288    /// past [`MAX_FILTER_VALUES`], no text past [`MAX_FILTER_TEXT`], and
289    /// years in order.
290    pub fn check(&self) -> Result<(), BrowseError> {
291        fn list<T>(name: &'static str, values: &[T]) -> Result<(), BrowseError> {
292            if values.len() > MAX_FILTER_VALUES {
293                return Err(BrowseError::TooMany(name));
294            }
295            Ok(())
296        }
297        fn texts(name: &'static str, values: &[String]) -> Result<(), BrowseError> {
298            list(name, values)?;
299            if values.iter().any(|v| v.chars().count() > MAX_FILTER_TEXT) {
300                return Err(BrowseError::TooLong(name));
301            }
302            Ok(())
303        }
304        list("watched", &self.watched)?;
305        if self.watched.contains(&WatchedState::Unknown) {
306            return Err(BrowseError::UnknownValue("watched state"));
307        }
308        texts("genres", &self.genres)?;
309        texts("content_ratings", &self.content_ratings)?;
310        list("resolutions", &self.resolutions)?;
311        if self.resolutions.contains(&Resolution::Unknown) {
312            return Err(BrowseError::UnknownValue("resolution"));
313        }
314        list("dynamic_ranges", &self.dynamic_ranges)?;
315        if self.dynamic_ranges.contains(&DynamicRange::Unknown) {
316            return Err(BrowseError::UnknownValue("dynamic range"));
317        }
318        if let (Some(from), Some(to)) = (self.year_from, self.year_to)
319            && from > to
320        {
321            return Err(BrowseError::Years { from, to });
322        }
323        Ok(())
324    }
325}
326
327/// A value a library has, and how many of its top-level items have it
328/// when that is cheap to say: a paired server's library always says, this
329/// server's own (read from Plex) only for its resolutions and ranges.
330#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
331pub struct Counted<T> {
332    pub value: T,
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub count: Option<u32>,
335}
336
337/// A part of an [`ItemFilter`].
338#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
339#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
340#[serde(rename_all = "snake_case")]
341pub enum FilterPart {
342    Watched,
343    Genres,
344    Years,
345    ContentRatings,
346    Resolutions,
347    DynamicRanges,
348    /// A part this build does not know.
349    #[serde(other)]
350    Unknown,
351}
352
353impl FilterPart {
354    /// Its name on the wire.
355    pub fn as_str(self) -> &'static str {
356        match self {
357            FilterPart::Watched => "watched",
358            FilterPart::Genres => "genres",
359            FilterPart::Years => "years",
360            FilterPart::ContentRatings => "content_ratings",
361            FilterPart::Resolutions => "resolutions",
362            FilterPart::DynamicRanges => "dynamic_ranges",
363            FilterPart::Unknown => "unknown",
364        }
365    }
366}
367
368impl ItemFilter {
369    /// The parts it uses.
370    pub fn parts(&self) -> Vec<FilterPart> {
371        let mut parts = Vec::new();
372        if !self.watched.is_empty() {
373            parts.push(FilterPart::Watched);
374        }
375        if !self.genres.is_empty() {
376            parts.push(FilterPart::Genres);
377        }
378        if self.year_from.is_some() || self.year_to.is_some() {
379            parts.push(FilterPart::Years);
380        }
381        if !self.content_ratings.is_empty() {
382            parts.push(FilterPart::ContentRatings);
383        }
384        if !self.resolutions.is_empty() {
385            parts.push(FilterPart::Resolutions);
386        }
387        if !self.dynamic_ranges.is_empty() {
388            parts.push(FilterPart::DynamicRanges);
389        }
390        parts
391    }
392}
393
394/// What a library's items have to filter by (`ItemFilterValues`), each
395/// list with how many top-level items have each value. A value no item
396/// has is not listed.
397#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
398pub struct ItemFilterValues {
399    /// By name, case aside.
400    #[serde(default)]
401    pub genres: Vec<Counted<String>>,
402    /// Newest first.
403    #[serde(default)]
404    pub years: Vec<Counted<u16>>,
405    /// By name.
406    #[serde(default)]
407    pub content_ratings: Vec<Counted<String>>,
408    /// Largest first.
409    #[serde(default)]
410    pub resolutions: Vec<Counted<Resolution>>,
411    /// The ranges this library can be filtered by, of SDR, HDR and Dolby
412    /// Vision. An HDR count includes Dolby Vision. One left out is
413    /// `InvalidInput` in a filter: this server's own libraries cannot be
414    /// filtered by Dolby Vision, as Plex cannot.
415    #[serde(default)]
416    pub dynamic_ranges: Vec<Counted<DynamicRange>>,
417    /// The sort keys this library orders by, in [`SortKey::ALL`]'s order.
418    /// A key left out is `InvalidInput` for this library: this server's
419    /// own libraries have no `size`, as Plex does not sort by it.
420    #[serde(default)]
421    pub sorts: Vec<SortKey>,
422    /// The parts of a filter this library applies. A part left out is
423    /// `InvalidInput` for this library: a music library has no watch
424    /// state, a TV library no resolution.
425    #[serde(default)]
426    pub filters: Vec<FilterPart>,
427}
428
429impl ItemFilterValues {
430    /// Why this library cannot be ordered by `sort` or kept by `filter`,
431    /// if it cannot: a key, a part or a range it does not list.
432    pub fn refuses(&self, sort: Option<&ItemSort>, filter: Option<&ItemFilter>) -> Option<String> {
433        if let Some(sort) = sort
434            && !self.sorts.contains(&sort.key)
435        {
436            return Some(format!(
437                "this library cannot be sorted by {}",
438                sort.key.as_str()
439            ));
440        }
441        let filter = filter?;
442        if let Some(part) = filter
443            .parts()
444            .into_iter()
445            .find(|p| !self.filters.contains(p))
446        {
447            return Some(format!(
448                "this library cannot be filtered by {}",
449                part.as_str()
450            ));
451        }
452        if let Some(range) = filter
453            .dynamic_ranges
454            .iter()
455            .find(|r| !self.dynamic_ranges.iter().any(|c| c.value == **r))
456        {
457            return Some(format!("this library cannot be filtered by {range:?}"));
458        }
459        None
460    }
461}
462
463impl ItemFilterValues {
464    /// The keys a Sort menu lists: the library's, in its order, each
465    /// once, none this build does not know.
466    pub fn sort_keys(&self) -> Vec<SortKey> {
467        let mut keys: Vec<SortKey> = Vec::new();
468        for &key in &self.sorts {
469            if key != SortKey::Unknown && !keys.contains(&key) {
470                keys.push(key);
471            }
472        }
473        keys
474    }
475
476    /// The decades the library has, newest first, for the year filter:
477    /// 1990 for 1990 to 1999.
478    pub fn decades(&self) -> Vec<u16> {
479        let mut decades: Vec<u16> = self.years.iter().map(|y| y.value / 10 * 10).collect();
480        decades.sort_unstable_by(|a, b| b.cmp(a));
481        decades.dedup();
482        decades
483    }
484
485    /// A saved `sort` and `filter` as this library can use them now: a
486    /// sort key it no longer lists goes back to [`ItemSort::DEFAULT`], a
487    /// part it no longer filters by is cleared, and a resolution or range
488    /// it does not list is dropped (the server would refuse it, where a
489    /// genre it does not list only keeps nothing). Values this build does
490    /// not know go too.
491    pub fn sanitize(&self, sort: ItemSort, filter: ItemFilter) -> ItemQuery {
492        let sort = if sort.key != SortKey::Unknown && self.sorts.contains(&sort.key) {
493            sort
494        } else {
495            ItemSort::DEFAULT
496        };
497        let offers = |part| self.filters.contains(&part);
498        let mut filter = filter;
499        if !offers(FilterPart::Watched) {
500            filter.watched.clear();
501        }
502        filter.watched.retain(|w| *w != WatchedState::Unknown);
503        if !offers(FilterPart::Genres) {
504            filter.genres.clear();
505        }
506        if !offers(FilterPart::Years) {
507            filter.year_from = None;
508            filter.year_to = None;
509        }
510        if !offers(FilterPart::ContentRatings) {
511            filter.content_ratings.clear();
512        }
513        if offers(FilterPart::Resolutions) {
514            filter
515                .resolutions
516                .retain(|r| self.resolutions.iter().any(|c| c.value == *r));
517        } else {
518            filter.resolutions.clear();
519        }
520        if offers(FilterPart::DynamicRanges) {
521            filter
522                .dynamic_ranges
523                .retain(|r| self.dynamic_ranges.iter().any(|c| c.value == *r));
524        } else {
525            filter.dynamic_ranges.clear();
526        }
527        ItemQuery { sort, filter }
528    }
529}
530
531/// One value a filter keeps items by, as a check row or a chip names it.
532#[derive(Debug, Clone, PartialEq, Eq, Hash)]
533pub enum FilterValue {
534    Watched(WatchedState),
535    Genre(String),
536    ContentRating(String),
537    Resolution(Resolution),
538    DynamicRange(DynamicRange),
539}
540
541/// What the user chose for one library: its order and what it keeps.
542/// What an app saves per library, and asks `Items` with
543/// ([`ItemQuery::to_request`]).
544#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
545#[serde(default)]
546pub struct ItemQuery {
547    pub sort: ItemSort,
548    pub filter: ItemFilter,
549}
550
551impl Default for ItemQuery {
552    fn default() -> Self {
553        Self {
554            sort: ItemSort::DEFAULT,
555            filter: ItemFilter::default(),
556        }
557    }
558}
559
560impl ItemQuery {
561    /// The library as `Items` gives it with neither: title A to Z, every
562    /// item.
563    pub fn is_default(&self) -> bool {
564        *self == ItemQuery::default()
565    }
566
567    /// What to ask `Items` with: the default order and an empty filter
568    /// are left out, as the server's own, so the plain listing stays the
569    /// one a cache keeps.
570    pub fn to_request(&self) -> (Option<ItemSort>, Option<ItemFilter>) {
571        let sort = (self.sort != ItemSort::DEFAULT).then_some(self.sort);
572        let filter = (!self.filter.is_empty()).then(|| self.filter.clone());
573        (sort, filter)
574    }
575
576    /// Ordered by `key`: picked again, the other way round; else title
577    /// A to Z first, any other key largest, newest or last first.
578    pub fn sort_by(&mut self, key: SortKey) {
579        self.sort = if self.sort.key == key {
580            ItemSort {
581                key,
582                descending: !self.sort.descending,
583            }
584        } else {
585            ItemSort {
586                key,
587                descending: key != SortKey::Title,
588            }
589        };
590    }
591
592    /// Whether it keeps items with `value`; names case aside.
593    pub fn has(&self, value: &FilterValue) -> bool {
594        let named =
595            |names: &[String], name: &str| names.iter().any(|n| n.eq_ignore_ascii_case(name));
596        let filter = &self.filter;
597        match value {
598            FilterValue::Watched(state) => filter.watched.contains(state),
599            FilterValue::Genre(name) => named(&filter.genres, name),
600            FilterValue::ContentRating(name) => named(&filter.content_ratings, name),
601            FilterValue::Resolution(r) => filter.resolutions.contains(r),
602            FilterValue::DynamicRange(r) => filter.dynamic_ranges.contains(r),
603        }
604    }
605
606    /// Keeps items with `value` too, or no longer if it did.
607    pub fn toggle(&mut self, value: &FilterValue) {
608        fn flip<T: PartialEq + Clone>(list: &mut Vec<T>, value: &T, same: impl Fn(&T, &T) -> bool) {
609            let before = list.len();
610            list.retain(|v| !same(v, value));
611            if list.len() == before {
612                list.push(value.clone());
613            }
614        }
615        let names = |a: &String, b: &String| a.eq_ignore_ascii_case(b);
616        let filter = &mut self.filter;
617        match value {
618            FilterValue::Watched(s) => flip(&mut filter.watched, s, PartialEq::eq),
619            FilterValue::Genre(name) => flip(&mut filter.genres, name, names),
620            FilterValue::ContentRating(name) => flip(&mut filter.content_ratings, name, names),
621            FilterValue::Resolution(r) => flip(&mut filter.resolutions, r, PartialEq::eq),
622            FilterValue::DynamicRange(r) => flip(&mut filter.dynamic_ranges, r, PartialEq::eq),
623        }
624    }
625
626    /// From `from` to `to`, either open. A To before the From is moved up
627    /// to it, so the range is never back to front (which `Items`
628    /// refuses).
629    pub fn set_years(&mut self, from: Option<u16>, to: Option<u16>) {
630        self.filter.year_from = from;
631        self.filter.year_to = match (from, to) {
632            (Some(from), Some(to)) if to < from => Some(from),
633            _ => to,
634        };
635    }
636
637    /// Without `part`: the other parts and the sort stay.
638    pub fn reset(&mut self, part: FilterPart) {
639        let filter = &mut self.filter;
640        match part {
641            FilterPart::Watched => filter.watched.clear(),
642            FilterPart::Genres => filter.genres.clear(),
643            FilterPart::Years => {
644                filter.year_from = None;
645                filter.year_to = None;
646            }
647            FilterPart::ContentRatings => filter.content_ratings.clear(),
648            FilterPart::Resolutions => filter.resolutions.clear(),
649            FilterPart::DynamicRanges => filter.dynamic_ranges.clear(),
650            FilterPart::Unknown => {}
651        }
652    }
653}
654
655/// `title` as a sort title: a leading "The", "A" or "An" and the space
656/// after it set aside, as Plex's `titleSort` does. A title that is only
657/// the article stays as it is.
658pub fn sort_title(title: &str) -> &str {
659    let trimmed = title.trim_start();
660    for article in ["the ", "a ", "an "] {
661        if trimmed.len() > article.len()
662            && trimmed.is_char_boundary(article.len())
663            && trimmed[..article.len()].eq_ignore_ascii_case(article)
664        {
665            let rest = trimmed[article.len()..].trim_start();
666            if !rest.is_empty() {
667                return rest;
668            }
669        }
670    }
671    trimmed
672}
673
674#[cfg(test)]
675mod tests {
676    use super::*;
677
678    fn values() -> ItemFilterValues {
679        ItemFilterValues {
680            resolutions: vec![Counted {
681                value: Resolution::Uhd,
682                count: None,
683            }],
684            dynamic_ranges: vec![Counted {
685                value: DynamicRange::Hdr,
686                count: None,
687            }],
688            sorts: vec![
689                SortKey::Title,
690                SortKey::Added,
691                SortKey::Added,
692                SortKey::Unknown,
693            ],
694            filters: vec![
695                FilterPart::Genres,
696                FilterPart::Resolutions,
697                FilterPart::DynamicRanges,
698            ],
699            ..ItemFilterValues::default()
700        }
701    }
702
703    #[test]
704    fn nothing_chosen_asks_the_plain_listing() {
705        assert!(ItemQuery::default().is_default());
706        assert_eq!(ItemQuery::default().to_request(), (None, None));
707    }
708
709    #[test]
710    fn a_sort_alone_asks_for_that_order_and_no_filter() {
711        let mut query = ItemQuery::default();
712        query.sort_by(SortKey::Added);
713        let added = ItemSort {
714            key: SortKey::Added,
715            descending: true,
716        };
717        assert_eq!(query.to_request(), (Some(added), None));
718        query.sort_by(SortKey::Added);
719        assert!(!query.sort.descending, "picked again, the other way round");
720    }
721
722    #[test]
723    fn a_value_toggles_in_and_out_case_aside() {
724        let mut query = ItemQuery::default();
725        query.toggle(&FilterValue::Genre("Drama".into()));
726        assert!(query.has(&FilterValue::Genre("drama".into())));
727        query.toggle(&FilterValue::Genre("DRAMA".into()));
728        assert!(query.is_default());
729    }
730
731    #[test]
732    fn a_year_range_is_never_back_to_front() {
733        let mut query = ItemQuery::default();
734        query.set_years(Some(2000), Some(1990));
735        assert_eq!(
736            (query.filter.year_from, query.filter.year_to),
737            (Some(2000), Some(2000))
738        );
739        assert!(query.filter.check().is_ok());
740        query.set_years(None, Some(1990));
741        assert_eq!(
742            (query.filter.year_from, query.filter.year_to),
743            (None, Some(1990))
744        );
745    }
746
747    #[test]
748    fn a_saved_choice_keeps_only_what_the_library_still_offers() {
749        let saved = ItemFilter {
750            watched: vec![WatchedState::Watched],
751            genres: vec!["Drama".into()],
752            resolutions: vec![Resolution::Uhd, Resolution::Sd],
753            dynamic_ranges: vec![DynamicRange::DolbyVision],
754            year_from: Some(1990),
755            ..ItemFilter::default()
756        };
757        let rating = ItemSort {
758            key: SortKey::Rating,
759            descending: true,
760        };
761        let query = values().sanitize(rating, saved);
762        assert_eq!(query.sort, ItemSort::DEFAULT);
763        assert_eq!(
764            query.filter,
765            ItemFilter {
766                genres: vec!["Drama".into()],
767                resolutions: vec![Resolution::Uhd],
768                ..ItemFilter::default()
769            }
770        );
771        assert_eq!(
772            values().refuses(Some(&query.sort), Some(&query.filter)),
773            None
774        );
775    }
776
777    #[test]
778    fn decades_are_the_librarys_years_newest_first() {
779        let values = ItemFilterValues {
780            years: [1994, 2023, 1999, 2020]
781                .map(|value| Counted { value, count: None })
782                .to_vec(),
783            ..ItemFilterValues::default()
784        };
785        assert_eq!(values.decades(), [2020, 1990]);
786    }
787
788    #[test]
789    fn the_sort_menu_lists_the_librarys_known_keys_once() {
790        assert_eq!(values().sort_keys(), [SortKey::Title, SortKey::Added]);
791    }
792
793    #[test]
794    fn a_sort_and_a_filter_are_snake_case_on_the_wire() {
795        let sort = ItemSort {
796            key: SortKey::LastPlayed,
797            descending: true,
798        };
799        assert_eq!(
800            serde_json::to_value(sort).unwrap(),
801            serde_json::json!({"key": "last_played", "descending": true})
802        );
803        let filter = ItemFilter {
804            watched: vec![WatchedState::InProgress],
805            resolutions: vec![Resolution::Uhd, Resolution::Sd],
806            dynamic_ranges: vec![DynamicRange::DolbyVision],
807            year_from: Some(1990),
808            ..ItemFilter::default()
809        };
810        assert_eq!(
811            serde_json::to_value(&filter).unwrap(),
812            serde_json::json!({
813                "watched": ["in_progress"],
814                "resolutions": ["4k", "sd"],
815                "dynamic_ranges": ["dolby_vision"],
816                "year_from": 1990,
817            })
818        );
819    }
820
821    #[test]
822    fn a_sort_without_a_direction_is_ascending() {
823        let sort: ItemSort = serde_json::from_value(serde_json::json!({"key": "size"})).unwrap();
824        assert_eq!(
825            sort,
826            ItemSort {
827                key: SortKey::Size,
828                descending: false
829            }
830        );
831    }
832
833    #[test]
834    fn values_from_a_newer_peer_read_as_unknown_and_are_refused() {
835        let sort: ItemSort =
836            serde_json::from_value(serde_json::json!({"key": "loudness"})).unwrap();
837        assert_eq!(sort.key, SortKey::Unknown);
838        assert_eq!(sort.check(), Err(BrowseError::UnknownSort));
839        let filter: ItemFilter = serde_json::from_value(serde_json::json!({
840            "resolutions": ["8k"],
841        }))
842        .unwrap();
843        assert_eq!(filter.check(), Err(BrowseError::UnknownValue("resolution")));
844        let filter: ItemFilter = serde_json::from_value(serde_json::json!({
845            "watched": ["abandoned"],
846        }))
847        .unwrap();
848        assert!(filter.check().is_err());
849        let filter: ItemFilter = serde_json::from_value(serde_json::json!({
850            "dynamic_ranges": ["hdr12"],
851        }))
852        .unwrap();
853        assert!(filter.check().is_err());
854    }
855
856    #[test]
857    fn years_out_of_order_and_long_lists_are_refused() {
858        let years = ItemFilter {
859            year_from: Some(2000),
860            year_to: Some(1990),
861            ..ItemFilter::default()
862        };
863        assert_eq!(
864            years.check(),
865            Err(BrowseError::Years {
866                from: 2000,
867                to: 1990
868            })
869        );
870        let many = ItemFilter {
871            genres: vec!["Drama".into(); MAX_FILTER_VALUES + 1],
872            ..ItemFilter::default()
873        };
874        assert_eq!(many.check(), Err(BrowseError::TooMany("genres")));
875        let long = ItemFilter {
876            content_ratings: vec!["x".repeat(MAX_FILTER_TEXT + 1)],
877            ..ItemFilter::default()
878        };
879        assert_eq!(long.check(), Err(BrowseError::TooLong("content_ratings")));
880        let decade = ItemFilter {
881            year_from: Some(1990),
882            year_to: Some(1999),
883            ..ItemFilter::default()
884        };
885        assert_eq!(decade.check(), Ok(()));
886    }
887
888    #[test]
889    fn an_empty_filter_keeps_everything_and_reads_from_nothing() {
890        let filter: ItemFilter = serde_json::from_value(serde_json::json!({})).unwrap();
891        assert!(filter.is_empty());
892        assert_eq!(
893            serde_json::to_value(&filter).unwrap(),
894            serde_json::json!({})
895        );
896    }
897
898    #[test]
899    fn the_sort_title_sets_a_leading_article_aside() {
900        assert_eq!(sort_title("The Matrix"), "Matrix");
901        assert_eq!(sort_title("a Beautiful Mind"), "Beautiful Mind");
902        assert_eq!(sort_title("An Education"), "Education");
903        assert_eq!(sort_title("Theremin"), "Theremin");
904        assert_eq!(sort_title("Anatomy"), "Anatomy");
905        assert_eq!(sort_title("The"), "The");
906        assert_eq!(sort_title("Amélie"), "Amélie");
907        assert_eq!(sort_title("A"), "A");
908    }
909
910    #[test]
911    fn resolution_classes_go_by_height_and_cropped_width() {
912        assert_eq!(
913            Resolution::of(Some(3840), Some(2160)),
914            Some(Resolution::Uhd)
915        );
916        assert_eq!(
917            Resolution::of(Some(3840), Some(1600)),
918            Some(Resolution::Uhd)
919        );
920        assert_eq!(
921            Resolution::of(Some(1920), Some(800)),
922            Some(Resolution::FullHd)
923        );
924        assert_eq!(Resolution::of(Some(1280), Some(536)), Some(Resolution::Hd));
925        assert_eq!(Resolution::of(Some(720), Some(576)), Some(Resolution::Sd));
926        assert_eq!(Resolution::of(None, None), None);
927        assert_eq!(Resolution::of_plex("4k"), Some(Resolution::Uhd));
928        assert_eq!(Resolution::of_plex("1080"), Some(Resolution::FullHd));
929        assert_eq!(Resolution::of_plex("720"), Some(Resolution::Hd));
930        assert_eq!(Resolution::of_plex("480"), Some(Resolution::Sd));
931        assert_eq!(Resolution::of_plex("sd"), Some(Resolution::Sd));
932        assert_eq!(Resolution::of_plex(""), None);
933        assert_eq!(Resolution::parse("1080p"), Some(Resolution::FullHd));
934    }
935}