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