Skip to main content

spoolframe_protocol/
search_rank.rs

1//! How a search's results are ranked and grouped once what matched is
2//! known (P3-09): the year taken off the query, the top match, quiet
3//! episodes left out of `All`, each group cut to the limit, and the scopes
4//! counted.
5//!
6//! One implementation for the two places that answer a search: the
7//! server, over what its catalogs found, and the SDK with no server, over
8//! what is on the device (`Client::search_offline`). Each finds the
9//! matches its own way; the same rules then make the same
10//! [`SearchResults`] of them, so a search screen works unchanged on
11//! either.
12
13use std::collections::{HashMap, HashSet};
14use std::time::{SystemTime, UNIX_EPOCH};
15
16use spoolframe_types::{Item, MediaId, Person, SearchKind, SearchScope};
17
18use crate::search::{SearchCounts, SearchGroup, SearchRequest, SearchResults, TopResult};
19
20/// How many episodes `All` shows: episodes are quiet there, and come last.
21pub const QUIET_EPISODES: usize = 3;
22
23/// How many items "also matching without the year" offers.
24pub const WITHOUT_YEAR: usize = 3;
25
26/// Every kind of item a search finds: the kinds counted in a scope.
27pub const MEDIA: [SearchKind; 6] = [
28    SearchKind::Shows,
29    SearchKind::Movies,
30    SearchKind::Artists,
31    SearchKind::Albums,
32    SearchKind::Tracks,
33    SearchKind::Episodes,
34];
35
36const MUSIC: [SearchKind; 3] = [SearchKind::Artists, SearchKind::Albums, SearchKind::Tracks];
37
38/// A query as typed, split into the text to search for and a year.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Parsed {
41    pub text: String,
42    pub year: Option<u16>,
43}
44
45/// `query`, with a year at its end taken off as a filter: "dune 2021".
46/// Only a year from 1900 to next year counts, and only after some text,
47/// so "Blade Runner 2049" and "1917" are searched as they are.
48pub fn parse(query: &str, this_year: u16) -> Parsed {
49    let query = query.trim();
50    if let Some((text, last)) = query.rsplit_once(char::is_whitespace) {
51        let text = text.trim_end();
52        let year = (last.len() == 4 && last.bytes().all(|b| b.is_ascii_digit()))
53            .then(|| last.parse::<u16>().ok())
54            .flatten()
55            .filter(|y| (1900..=this_year.saturating_add(1)).contains(y));
56        if let Some(year) = year.filter(|_| !text.is_empty()) {
57            return Parsed {
58                text: text.to_owned(),
59                year: Some(year),
60            };
61        }
62    }
63    Parsed {
64        text: query.to_owned(),
65        year: None,
66    }
67}
68
69/// The year now, near enough for [`parse`]: an average Gregorian year
70/// from the epoch is off by at most a day at a year's turn, which next
71/// year's being allowed covers.
72pub fn this_year() -> u16 {
73    let secs = SystemTime::now()
74        .duration_since(UNIX_EPOCH)
75        .map(|d| d.as_secs())
76        .unwrap_or_default();
77    u16::try_from(1970 + secs / 31_556_952).unwrap_or(u16::MAX)
78}
79
80/// What matched of one kind, best first as the finder has them: at most
81/// one more than the request's limit, and how many there are in all.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct Matched {
84    pub kind: SearchKind,
85    /// Empty for [`SearchKind::People`].
86    pub items: Vec<Item>,
87    /// Only for [`SearchKind::People`].
88    pub people: Vec<Person>,
89    /// How many there are, at least as many as are here. For people it
90    /// is only as many as were returned.
91    pub total: u32,
92}
93
94/// The rules, with how a title is compared to the query: the server
95/// compares as Plex sorts ([`normalized`]); the SDK with no server folds
96/// accents and punctuation as well, as it matches.
97#[derive(Debug, Clone, Copy)]
98pub struct Ranker {
99    normalize: fn(&str) -> String,
100}
101
102impl Default for Ranker {
103    /// Titles compared [`normalized`]: the server's.
104    fn default() -> Self {
105        Self::new(normalized)
106    }
107}
108
109impl Ranker {
110    /// Titles and the query compared after `normalize`, which drops a
111    /// leading article as [`normalized`] does.
112    pub fn new(normalize: fn(&str) -> String) -> Self {
113        Self { normalize }
114    }
115
116    /// What a client is shown of `found`, the matches for `query` (its
117    /// text and the year taken off it). `totals` has each kind's count,
118    /// the other scopes' too when they were counted. In `All`, an episode
119    /// whose show is listed in the shows group (or any of that show's
120    /// other copies, `copies`) is quiet: counted in `hidden`, not listed.
121    /// One whose show is the top match is listed. A group with no item is
122    /// left out, but for a "See all".
123    pub fn group(
124        &self,
125        request: &SearchRequest,
126        query: &Parsed,
127        mut found: Vec<Matched>,
128        totals: &HashMap<SearchKind, u32>,
129        without_year: Vec<Item>,
130        copies: &HashMap<MediaId, Vec<MediaId>>,
131    ) -> SearchResults {
132        let year = query.year;
133        let limit = usize::try_from(request.limit).unwrap_or(usize::MAX);
134        let see_all = request.kind.is_some();
135        let quiet = !see_all && request.scope == SearchScope::All;
136        let text = (self.normalize)(&query.text);
137        found.sort_by_key(|g| g.kind);
138
139        let top = match see_all {
140            true => None,
141            false => self.top(&found, &text),
142        };
143        let top_item = match &top {
144            Some(TopResult::Item(item)) => Some(item.id()),
145            _ => None,
146        };
147        let top_person = match &top {
148            Some(TopResult::Person(person)) => Some(&person.id),
149            _ => None,
150        };
151        // The shows the shows group lists, with their other copies: what a
152        // show's own episodes are under in `All`. The top match is in no
153        // group, so its episodes are listed.
154        let shows: HashSet<MediaId> = found
155            .iter()
156            .filter(|g| g.kind == SearchKind::Shows)
157            .flat_map(|g| self.listed(&g.items, top_item, &text, limit))
158            .flat_map(|id| {
159                let more = copies.get(id).cloned().unwrap_or_default();
160                std::iter::once(id.clone()).chain(more)
161            })
162            .collect();
163
164        let mut groups = Vec::new();
165        for Matched {
166            kind,
167            mut items,
168            mut people,
169            total,
170        } in found
171        {
172            let before = items.len() + people.len();
173            items.retain(|i| Some(i.id()) != top_item);
174            people.retain(|p| Some(&p.id) != top_person);
175            let removed = before - items.len() - people.len();
176            let mut hidden = 0;
177            if quiet && kind == SearchKind::Episodes {
178                let before = items.len();
179                items.retain(|i| !matches!(i, Item::Episode(e) if shows.contains(&e.show_id)));
180                hidden = before - items.len();
181            }
182            // Stable: within a tier, the finder's order.
183            items.sort_by_cached_key(|i| self.tier(i, &text));
184            let cap = match quiet && kind == SearchKind::Episodes {
185                true => limit.min(QUIET_EPISODES),
186                false => limit,
187            };
188            items.truncate(cap);
189            people.truncate(cap);
190            let shown = items.len() + people.len();
191            let available = usize::try_from(total)
192                .unwrap_or(usize::MAX)
193                .saturating_sub(removed + hidden);
194            // A group is shown only with something in it; "See all" is
195            // its group, empty or not.
196            if shown == 0 && !see_all {
197                continue;
198            }
199            let more = available > shown;
200            let total = match kind {
201                SearchKind::People if more => None,
202                _ => Some(total),
203            };
204            groups.push(SearchGroup {
205                kind,
206                items,
207                people,
208                more,
209                total,
210                hidden: u32::try_from(hidden).unwrap_or(u32::MAX),
211            });
212        }
213
214        SearchResults {
215            top,
216            groups,
217            counts: counts(totals),
218            year,
219            without_year,
220        }
221    }
222
223    /// The ids a group of `items` lists, as [`Self::group`] makes it with
224    /// nothing hidden: the top match left out, best first (stable within a
225    /// tier), at most `cap`.
226    fn listed<'a>(
227        &self,
228        items: &'a [Item],
229        top: Option<&MediaId>,
230        text: &str,
231        cap: usize,
232    ) -> Vec<&'a MediaId> {
233        let mut kept: Vec<&Item> = items.iter().filter(|i| Some(i.id()) != top).collect();
234        kept.sort_by_cached_key(|i| self.tier(i, text));
235        kept.into_iter().take(cap).map(Item::id).collect()
236    }
237
238    /// Up to [`WITHOUT_YEAR`] of `any_year` that are not of `year` and not
239    /// already `found`, best first.
240    pub fn without_year(
241        &self,
242        text: &str,
243        year: u16,
244        found: &[Matched],
245        mut any_year: Vec<Matched>,
246    ) -> Vec<Item> {
247        let matched: HashSet<&MediaId> =
248            found.iter().flat_map(|g| &g.items).map(Item::id).collect();
249        any_year.sort_by_key(|g| g.kind);
250        let others = any_year
251            .iter()
252            .flat_map(|g| &g.items)
253            .filter(|i| year_of(i) != Some(year) && !matched.contains(i.id()));
254        let mut ranked: Vec<_> = others.enumerate().collect();
255        let text = (self.normalize)(text);
256        ranked.sort_by_cached_key(|&(at, item)| (self.tier(item, &text), at));
257        ranked
258            .into_iter()
259            .take(WITHOUT_YEAR)
260            .map(|(_, item)| item.clone())
261            .collect()
262    }
263
264    /// The top match of `found`: the best item, unless a person's name
265    /// matches better than its title does (or no item is found). On a tie
266    /// the item wins: a person is shown in the top spot only when the
267    /// query is more surely them, as an exact "keanu reeves" over titles
268    /// that only start with it.
269    fn top(&self, found: &[Matched], text: &str) -> Option<TopResult> {
270        let item = self.best(found.iter().flat_map(|g| &g.items), text);
271        let person = found
272            .iter()
273            .flat_map(|g| &g.people)
274            .enumerate()
275            .min_by_key(|&(at, person)| (self.tier_of(&person.name, text), at))
276            .map(|(_, person)| person);
277        match (item, person) {
278            (Some(item), Some(person))
279                if self.tier_of(&person.name, text) < self.tier(item, text) =>
280            {
281                Some(TopResult::Person(person.clone()))
282            }
283            (Some(item), _) => Some(TopResult::Item(item.clone())),
284            (None, Some(person)) => Some(TopResult::Person(person.clone())),
285            (None, None) => None,
286        }
287    }
288
289    /// The best match among `items`: by [`Self::tier`], then the order
290    /// they come in. They come in the groups' order, so on a tie a show
291    /// beats a movie, and its own episodes, which are last.
292    fn best<'a>(&self, items: impl Iterator<Item = &'a Item>, text: &str) -> Option<&'a Item> {
293        items
294            .enumerate()
295            .min_by_key(|&(at, item)| (self.tier(item, text), at))
296            .map(|(_, item)| item)
297    }
298
299    /// [`Self::tier_of`] the item's title.
300    fn tier(&self, item: &Item, text: &str) -> u8 {
301        self.tier_of(item.title(), text)
302    }
303
304    /// 0 for a title that is the query, 1 for one that starts with it, 2
305    /// for the rest. `text` is normalized already.
306    pub fn tier_of(&self, title: &str, text: &str) -> u8 {
307        let title = (self.normalize)(title);
308        if title == text {
309            0
310        } else if title.starts_with(text) {
311            1
312        } else {
313            2
314        }
315    }
316}
317
318/// Each scope's count, from each kind's total. A scope is counted only
319/// when every kind in it is.
320pub fn counts(totals: &HashMap<SearchKind, u32>) -> SearchCounts {
321    let of = |kind| totals.get(&kind).copied();
322    let sum = |kinds: &[SearchKind]| kinds.iter().map(|&k| of(k)).sum::<Option<u32>>();
323    SearchCounts {
324        all: sum(&MEDIA).map(|media| media.saturating_add(of(SearchKind::People).unwrap_or(0))),
325        movies: of(SearchKind::Movies),
326        shows: of(SearchKind::Shows),
327        episodes: of(SearchKind::Episodes),
328        music: sum(&MUSIC),
329    }
330}
331
332/// `s` as the server compares titles: lower case, single spaces, and
333/// without a leading English article, as Plex sorts them, so "cure" is
334/// the exact title of "The Cure".
335pub fn normalized(s: &str) -> String {
336    let s = s
337        .split_whitespace()
338        .collect::<Vec<_>>()
339        .join(" ")
340        .to_lowercase();
341    strip_article(&s).to_owned()
342}
343
344/// `s`, lower case with single spaces, without a leading "the ", "a " or
345/// "an ".
346pub fn strip_article(s: &str) -> &str {
347    ["the ", "a ", "an "]
348        .iter()
349        .find_map(|article| s.strip_prefix(article))
350        .unwrap_or(s)
351}
352
353/// The year a film, show or album came out; `None` for the others.
354pub fn year_of(item: &Item) -> Option<u16> {
355    match item {
356        Item::Movie(v) => v.year,
357        Item::Show(v) => v.year,
358        Item::Album(v) => v.year,
359        _ => None,
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    /// A ranker folds as its finder matches: with accents folded, "amelie"
368    /// is the exact title of "Amélie"; the server's leaves the accent.
369    #[test]
370    fn a_ranker_compares_titles_as_its_normalize_says() {
371        fn ascii(s: &str) -> String {
372            normalized(&s.replace('é', "e"))
373        }
374        let amelie = "Amélie";
375        assert_eq!(Ranker::default().tier_of(amelie, "amelie"), 2);
376        assert_eq!(Ranker::new(ascii).tier_of(amelie, "amelie"), 0);
377    }
378
379    #[test]
380    fn only_a_leading_article_is_dropped() {
381        assert_eq!(normalized("The  Cure"), "cure");
382        assert_eq!(normalized("Theory"), "theory");
383        assert_eq!(normalized("Cure for the Itch"), "cure for the itch");
384    }
385}