Skip to main content

spoolframe_protocol/
search_view.rs

1//! What a client shows of a search and of a title's copies, worked out
2//! once: the "Play from" choices, one server's results, "See all 23" and
3//! "3 from Severance are under the show".
4
5use spoolframe_types::{Item, LibraryServer, MediaId, SearchKind};
6
7use crate::search::{Copies, SearchCounts, SearchGroup, SearchResult, SearchResults, TopResult};
8
9/// One copy of a title, as the Play from list shows it
10/// ([`Copies::choices`]).
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct PlayFromChoice {
13    /// The copy's paired server; `None` for the user's own.
14    pub server: Option<LibraryServer>,
15    /// The copy's id: what plays when it is picked.
16    pub id: MediaId,
17    /// The copy that plays now.
18    pub playing: bool,
19    /// It can play now: the user's own server's, or a paired one online.
20    /// One offline is shown greyed, browsed and not played.
21    pub playable: bool,
22}
23
24impl Copies {
25    /// Every copy of `item`'s title (these are its copies): the user's
26    /// own server's first, then in the protocol's order. None for a
27    /// title on one server, which has nothing to choose.
28    pub fn choices(&self, item: &MediaId) -> Vec<PlayFromChoice> {
29        if self.also_on.is_empty() {
30            return Vec::new();
31        }
32        let copies = std::iter::once((self.origin.as_ref(), item))
33            .chain(self.also_on.iter().map(|c| (c.server.as_ref(), &c.id)));
34        let mut choices: Vec<PlayFromChoice> = copies
35            .map(|(server, id)| PlayFromChoice {
36                server: server.cloned(),
37                id: id.clone(),
38                playing: *id == self.play_from,
39                playable: server.is_none_or(|s| s.online),
40            })
41            .collect();
42        // Stable: the paired servers stay in the protocol's order.
43        choices.sort_by_key(|c| c.server.is_some());
44        choices
45    }
46}
47
48/// Episodes left out of a search because their show is in it
49/// ([`SearchResults::hidden_under`]).
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct HiddenUnder {
52    pub count: u32,
53    /// The titles of the shows found, which hold them; empty when the
54    /// shows were not returned.
55    pub shows: Vec<String>,
56}
57
58impl<T> SearchResults<T> {
59    fn group(&self, kind: SearchKind) -> Option<&SearchGroup<T>> {
60        self.groups.iter().find(|g| g.kind == kind)
61    }
62
63    /// The number "See all" names for `kind`'s group: its own total, else
64    /// its scope's count. `None` when the group has no more to show, or
65    /// nothing says how many: then a plain "See all".
66    pub fn see_all_count(&self, kind: SearchKind) -> Option<u32> {
67        let group = self.group(kind).filter(|g| g.more)?;
68        group
69            .total
70            .or_else(|| kind.scope().and_then(|scope| self.counts.of(scope)))
71    }
72}
73
74impl SearchResults<SearchResult> {
75    /// The episodes `kind`'s group left under their show, with the shows'
76    /// titles (the top match's too); `None` when none were.
77    pub fn hidden_under(&self, kind: SearchKind) -> Option<HiddenUnder> {
78        let count = self.group(kind).map(|g| g.hidden).filter(|n| *n > 0)?;
79        let mut shows: Vec<String> = self
80            .group(SearchKind::Shows)
81            .map(|g| g.items.iter().map(|r| r.item.title().to_owned()).collect())
82            .unwrap_or_default();
83        if let Some(TopResult::Item(top)) = &self.top
84            && let Item::Show(show) = &top.item
85            && !shows.contains(&show.title)
86        {
87            shows.push(show.title.clone());
88        }
89        Some(HiddenUnder { count, shows })
90    }
91
92    /// Only the hits from paired server `origin` (its server id), or the
93    /// user's own with `None`, for a server's chip. People are the user's
94    /// own server's, so only it keeps them. The counts are what is left:
95    /// `all` counts the people kept too. A group's total is its items
96    /// left when it had no more to show, else not known. Episodes hidden
97    /// under their show stay hidden only while a show is left to hold
98    /// them.
99    pub fn only_from(self, origin: Option<&str>) -> Self {
100        let keep = |hit: &SearchResult| hit.origin() == origin;
101        let people = origin.is_none();
102        let top = match self.top {
103            Some(TopResult::Item(hit)) if keep(&hit) => Some(TopResult::Item(hit)),
104            Some(TopResult::Person(person)) if people => Some(TopResult::Person(person)),
105            _ => None,
106        };
107        let top_is_show =
108            matches!(&top, Some(TopResult::Item(hit)) if matches!(hit.item, Item::Show(_)));
109        let shows_left = top_is_show
110            || self
111                .groups
112                .iter()
113                .any(|g| g.kind == SearchKind::Shows && g.items.iter().any(keep));
114        let groups: Vec<_> = self
115            .groups
116            .into_iter()
117            .map(|g| {
118                let items: Vec<SearchResult> = g.items.into_iter().filter(keep).collect();
119                let people = if people { g.people } else { Vec::new() };
120                let hidden = if shows_left { g.hidden } else { 0 };
121                SearchGroup {
122                    kind: g.kind,
123                    total: None,
124                    items,
125                    people,
126                    more: g.more,
127                    hidden,
128                }
129            })
130            .collect();
131        // The top match counted once: a top person the SDK also lists in
132        // People is counted there.
133        let top_kind = match &top {
134            Some(TopResult::Item(hit)) => kind_of(&hit.item),
135            Some(TopResult::Person(_)) => Some(SearchKind::People),
136            None => None,
137        };
138        let top_listed = matches!(&top, Some(TopResult::Person(person))
139            if groups.iter().any(|g| g.kind == SearchKind::People
140                && g.people.iter().any(|p| p.id == person.id)));
141        let unlisted = top_kind.filter(|_| !top_listed);
142        let top_unlisted = |kind: SearchKind| unlisted == Some(kind);
143        let groups: Vec<_> = groups
144            .into_iter()
145            .map(|g| {
146                let shown = (g.items.len() + g.people.len()) as u32;
147                SearchGroup {
148                    total: (!g.more).then_some(shown + u32::from(top_unlisted(g.kind)) + g.hidden),
149                    ..g
150                }
151            })
152            .collect();
153        let count = |kinds: &[SearchKind]| -> u32 {
154            let listed: usize = groups
155                .iter()
156                .filter(|g| kinds.contains(&g.kind))
157                .map(|g| g.items.len() + g.people.len() + g.hidden as usize)
158                .sum();
159            listed as u32 + kinds.iter().filter(|k| top_unlisted(**k)).count() as u32
160        };
161        let movies = count(&[SearchKind::Movies]);
162        let shows = count(&[SearchKind::Shows]);
163        let episodes = count(&[SearchKind::Episodes]);
164        let music = count(&[SearchKind::Artists, SearchKind::Albums, SearchKind::Tracks]);
165        let persons = count(&[SearchKind::People]);
166        SearchResults {
167            counts: SearchCounts {
168                all: Some(movies + shows + episodes + music + persons),
169                movies: Some(movies),
170                shows: Some(shows),
171                episodes: Some(episodes),
172                music: Some(music),
173            },
174            top,
175            groups,
176            year: self.year,
177            without_year: self.without_year.into_iter().filter(keep).collect(),
178        }
179    }
180}
181
182/// The group an item is listed in.
183fn kind_of(item: &Item) -> Option<SearchKind> {
184    Some(match item {
185        Item::Movie(_) => SearchKind::Movies,
186        Item::Show(_) => SearchKind::Shows,
187        Item::Episode(_) => SearchKind::Episodes,
188        Item::Artist(_) => SearchKind::Artists,
189        Item::Album(_) => SearchKind::Albums,
190        Item::Track(_) => SearchKind::Tracks,
191        Item::Season(_) => return None,
192    })
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use crate::search::TitleCopy;
199    use spoolframe_types::{MediaKind, Movie, Namespace, PlaybackState, Show};
200
201    fn server(id: &str, online: bool) -> LibraryServer {
202        LibraryServer {
203            server_id: id.into(),
204            name: id.to_uppercase(),
205            online,
206        }
207    }
208
209    fn own(key: &str) -> MediaId {
210        MediaId::new(Namespace::Plex, MediaKind::Movie, key).unwrap()
211    }
212
213    fn fed(origin: &str, key: &str) -> MediaId {
214        MediaId::federated(origin, &own(key)).unwrap()
215    }
216
217    fn copy(origin: &str, online: bool) -> TitleCopy {
218        TitleCopy {
219            id: fed(origin, "9"),
220            server: Some(server(origin, online)),
221        }
222    }
223
224    fn heat_copies(play_from: MediaId) -> Copies {
225        Copies {
226            origin: None,
227            also_on: vec![copy("bob", true)],
228            play_from,
229        }
230    }
231
232    #[test]
233    fn this_servers_copy_is_listed_first_and_the_one_that_plays_is_picked() {
234        let listed: Vec<_> = heat_copies(fed("bob", "9"))
235            .choices(&own("3"))
236            .iter()
237            .map(|c| (c.server.as_ref().map(|s| s.server_id.clone()), c.playing))
238            .collect();
239        assert_eq!(listed, [(None, false), (Some("bob".into()), true)]);
240    }
241
242    #[test]
243    fn this_servers_copy_comes_first_from_a_paired_items_page_too() {
244        let copies = Copies {
245            origin: Some(server("bob", true)),
246            also_on: vec![
247                copy("sb", true),
248                TitleCopy {
249                    id: own("3"),
250                    server: None,
251                },
252            ],
253            play_from: fed("bob", "9"),
254        };
255        let ids: Vec<_> = copies
256            .choices(&fed("bob", "9"))
257            .into_iter()
258            .map(|c| c.id)
259            .collect();
260        // Home first, then the protocol's order: the item's own, then sb's.
261        assert_eq!(ids, [own("3"), fed("bob", "9"), fed("sb", "9")]);
262    }
263
264    #[test]
265    fn a_title_on_one_server_has_no_play_from_choice() {
266        let copies = Copies {
267            origin: Some(server("bob", true)),
268            also_on: Vec::new(),
269            play_from: fed("bob", "11"),
270        };
271        assert!(copies.choices(&fed("bob", "11")).is_empty());
272    }
273
274    #[test]
275    fn a_copy_on_an_offline_server_cannot_be_played() {
276        let copies = Copies {
277            origin: None,
278            also_on: vec![copy("bob", false)],
279            play_from: own("3"),
280        };
281        let playable: Vec<_> = copies
282            .choices(&own("3"))
283            .iter()
284            .map(|c| c.playable)
285            .collect();
286        assert_eq!(playable, [true, false]);
287    }
288
289    fn movie(id: MediaId, title: &str) -> Item {
290        Item::Movie(Movie {
291            id,
292            title: title.into(),
293            year: None,
294            release_date: None,
295            summary: None,
296            content_rating: None,
297            duration: None,
298            cast: Vec::new(),
299            artwork: Vec::new(),
300            playback: PlaybackState::default(),
301        })
302    }
303
304    fn show(title: &str) -> Item {
305        Item::Show(Show {
306            id: MediaId::new(Namespace::Plex, MediaKind::Show, title).unwrap(),
307            title: title.into(),
308            year: None,
309            summary: None,
310            content_rating: None,
311            season_count: None,
312            genres: Vec::new(),
313            last_aired: None,
314            cast: Vec::new(),
315            artwork: Vec::new(),
316        })
317    }
318
319    fn hit(item: Item, origin: Option<&str>) -> SearchResult {
320        crate::SearchHit {
321            play_from: item.id().clone(),
322            origin: origin.map(|o| server(o, true)),
323            also_on: Vec::new(),
324            item,
325        }
326        .into()
327    }
328
329    fn group<T>(kind: SearchKind, items: Vec<T>) -> SearchGroup<T> {
330        SearchGroup {
331            kind,
332            items,
333            people: Vec::new(),
334            more: false,
335            total: None,
336            hidden: 0,
337        }
338    }
339
340    #[test]
341    fn one_servers_hits_are_counted_as_shown() {
342        let results = SearchResults {
343            top: Some(TopResult::Item(hit(
344                movie(fed("sa", "1"), "Alien"),
345                Some("sa"),
346            ))),
347            groups: vec![group(
348                SearchKind::Movies,
349                vec![
350                    hit(movie(own("2"), "Aliens"), None),
351                    hit(movie(fed("sa", "3"), "Alien 3"), Some("sa")),
352                ],
353            )],
354            counts: SearchCounts {
355                all: Some(40),
356                movies: Some(40),
357                ..SearchCounts::default()
358            },
359            ..SearchResults::default()
360        };
361        let sa = results.clone().only_from(Some("sa"));
362        assert!(sa.top.is_some());
363        assert_eq!(sa.groups[0].items.len(), 1);
364        assert_eq!((sa.counts.movies, sa.counts.all), (Some(2), Some(2)));
365        // The group had no more: what is left is all of it, top included.
366        assert_eq!(sa.groups[0].total, Some(2));
367        let home = results.clone().only_from(None);
368        assert!(home.top.is_none());
369        assert_eq!(home.counts.movies, Some(1));
370    }
371
372    fn person() -> spoolframe_types::Person {
373        spoolframe_types::Person {
374            id: spoolframe_types::PersonId::new(Namespace::Plex, "actor-1").unwrap(),
375            name: "Sigourney Weaver".into(),
376            role: spoolframe_types::PersonRole::Actor,
377            count: Some(3),
378        }
379    }
380
381    #[test]
382    fn people_count_for_the_users_own_server_only() {
383        let mut people = group(SearchKind::People, Vec::<SearchResult>::new());
384        people.people = vec![person()];
385        let results = SearchResults {
386            groups: vec![people],
387            ..SearchResults::default()
388        };
389        assert_eq!(results.clone().only_from(None).counts.all, Some(1));
390        let sa = results.clone().only_from(Some("sa"));
391        assert_eq!((sa.counts.all, sa.groups[0].people.len()), (Some(0), 0));
392    }
393
394    /// A top person also listed in People (as the SDK lists them) is
395    /// counted once.
396    #[test]
397    fn a_top_person_listed_in_people_is_counted_once() {
398        let mut people = group(SearchKind::People, Vec::<SearchResult>::new());
399        people.people = vec![person()];
400        let results = SearchResults {
401            top: Some(TopResult::Person(person())),
402            groups: vec![people],
403            ..SearchResults::default()
404        };
405        let own = results.clone().only_from(None);
406        assert_eq!((own.counts.all, own.groups[0].total), (Some(1), Some(1)));
407    }
408
409    /// The same person by id, though their item count differs between
410    /// the top and People, is one person: counted once.
411    #[test]
412    fn a_top_person_is_known_in_people_by_id() {
413        let mut people = group(SearchKind::People, Vec::<SearchResult>::new());
414        people.people = vec![spoolframe_types::Person {
415            count: Some(4),
416            ..person()
417        }];
418        let results = SearchResults {
419            top: Some(TopResult::Person(person())),
420            groups: vec![people],
421            ..SearchResults::default()
422        };
423        assert_eq!(results.clone().only_from(None).counts.all, Some(1));
424    }
425
426    #[test]
427    fn hidden_episodes_stay_hidden_only_under_a_show_left() {
428        let mut episodes = group(SearchKind::Episodes, Vec::new());
429        episodes.hidden = 3;
430        let results = SearchResults {
431            groups: vec![
432                group(SearchKind::Shows, vec![hit(show("Severance"), Some("sa"))]),
433                episodes,
434            ],
435            ..SearchResults::default()
436        };
437        assert_eq!(results.clone().only_from(Some("sa")).groups[1].hidden, 3);
438        assert_eq!(
439            results.clone().only_from(Some("sa")).counts.episodes,
440            Some(3)
441        );
442        assert_eq!(results.clone().only_from(None).groups[1].hidden, 0);
443    }
444
445    #[test]
446    fn see_all_names_the_groups_total_else_its_scopes_count() {
447        let mut movies = group(SearchKind::Movies, vec![movie(own("1"), "Alien")]);
448        movies.more = true;
449        let mut results = SearchResults {
450            groups: vec![movies, group(SearchKind::Shows, Vec::new())],
451            counts: SearchCounts {
452                movies: Some(23),
453                ..SearchCounts::default()
454            },
455            ..SearchResults::default()
456        };
457        assert_eq!(results.see_all_count(SearchKind::Movies), Some(23));
458        results.groups[0].total = Some(25);
459        assert_eq!(results.see_all_count(SearchKind::Movies), Some(25));
460        // Nothing more to see.
461        assert_eq!(results.see_all_count(SearchKind::Shows), None);
462    }
463
464    #[test]
465    fn hidden_episodes_name_the_shows_that_hold_them() {
466        let mut episodes = group(SearchKind::Episodes, Vec::new());
467        episodes.hidden = 3;
468        let results = SearchResults {
469            top: Some(TopResult::Item(show("Severance").into())),
470            groups: vec![
471                group(SearchKind::Shows, vec![show("Silo").into()]),
472                episodes,
473            ],
474            ..SearchResults::default()
475        };
476        assert_eq!(
477            results.hidden_under(SearchKind::Episodes),
478            Some(HiddenUnder {
479                count: 3,
480                shows: vec!["Silo".into(), "Severance".into()],
481            })
482        );
483        assert_eq!(results.hidden_under(SearchKind::Shows), None);
484    }
485}