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            merge: Default::default(),
292            id,
293            title: title.into(),
294            year: None,
295            release_date: None,
296            summary: None,
297            content_rating: None,
298            duration: None,
299            cast: Vec::new(),
300            artwork: Vec::new(),
301            playback: PlaybackState::default(),
302        })
303    }
304
305    fn show(title: &str) -> Item {
306        Item::Show(Show {
307            merge: Default::default(),
308            id: MediaId::new(Namespace::Plex, MediaKind::Show, title).unwrap(),
309            title: title.into(),
310            year: None,
311            summary: None,
312            content_rating: None,
313            season_count: None,
314            genres: Vec::new(),
315            last_aired: None,
316            cast: Vec::new(),
317            artwork: Vec::new(),
318        })
319    }
320
321    fn hit(item: Item, origin: Option<&str>) -> SearchResult {
322        crate::SearchHit {
323            play_from: item.id().clone(),
324            origin: origin.map(|o| server(o, true)),
325            also_on: Vec::new(),
326            item,
327        }
328        .into()
329    }
330
331    fn group<T>(kind: SearchKind, items: Vec<T>) -> SearchGroup<T> {
332        SearchGroup {
333            kind,
334            items,
335            people: Vec::new(),
336            more: false,
337            total: None,
338            hidden: 0,
339        }
340    }
341
342    #[test]
343    fn one_servers_hits_are_counted_as_shown() {
344        let results = SearchResults {
345            top: Some(TopResult::Item(hit(
346                movie(fed("sa", "1"), "Alien"),
347                Some("sa"),
348            ))),
349            groups: vec![group(
350                SearchKind::Movies,
351                vec![
352                    hit(movie(own("2"), "Aliens"), None),
353                    hit(movie(fed("sa", "3"), "Alien 3"), Some("sa")),
354                ],
355            )],
356            counts: SearchCounts {
357                all: Some(40),
358                movies: Some(40),
359                ..SearchCounts::default()
360            },
361            ..SearchResults::default()
362        };
363        let sa = results.clone().only_from(Some("sa"));
364        assert!(sa.top.is_some());
365        assert_eq!(sa.groups[0].items.len(), 1);
366        assert_eq!((sa.counts.movies, sa.counts.all), (Some(2), Some(2)));
367        // The group had no more: what is left is all of it, top included.
368        assert_eq!(sa.groups[0].total, Some(2));
369        let home = results.clone().only_from(None);
370        assert!(home.top.is_none());
371        assert_eq!(home.counts.movies, Some(1));
372    }
373
374    fn person() -> spoolframe_types::Person {
375        spoolframe_types::Person {
376            id: spoolframe_types::PersonId::new(Namespace::Plex, "actor-1").unwrap(),
377            name: "Sigourney Weaver".into(),
378            role: spoolframe_types::PersonRole::Actor,
379            count: Some(3),
380        }
381    }
382
383    #[test]
384    fn people_count_for_the_users_own_server_only() {
385        let mut people = group(SearchKind::People, Vec::<SearchResult>::new());
386        people.people = vec![person()];
387        let results = SearchResults {
388            groups: vec![people],
389            ..SearchResults::default()
390        };
391        assert_eq!(results.clone().only_from(None).counts.all, Some(1));
392        let sa = results.clone().only_from(Some("sa"));
393        assert_eq!((sa.counts.all, sa.groups[0].people.len()), (Some(0), 0));
394    }
395
396    /// A top person also listed in People (as the SDK lists them) is
397    /// counted once.
398    #[test]
399    fn a_top_person_listed_in_people_is_counted_once() {
400        let mut people = group(SearchKind::People, Vec::<SearchResult>::new());
401        people.people = vec![person()];
402        let results = SearchResults {
403            top: Some(TopResult::Person(person())),
404            groups: vec![people],
405            ..SearchResults::default()
406        };
407        let own = results.clone().only_from(None);
408        assert_eq!((own.counts.all, own.groups[0].total), (Some(1), Some(1)));
409    }
410
411    /// The same person by id, though their item count differs between
412    /// the top and People, is one person: counted once.
413    #[test]
414    fn a_top_person_is_known_in_people_by_id() {
415        let mut people = group(SearchKind::People, Vec::<SearchResult>::new());
416        people.people = vec![spoolframe_types::Person {
417            count: Some(4),
418            ..person()
419        }];
420        let results = SearchResults {
421            top: Some(TopResult::Person(person())),
422            groups: vec![people],
423            ..SearchResults::default()
424        };
425        assert_eq!(results.clone().only_from(None).counts.all, Some(1));
426    }
427
428    #[test]
429    fn hidden_episodes_stay_hidden_only_under_a_show_left() {
430        let mut episodes = group(SearchKind::Episodes, Vec::new());
431        episodes.hidden = 3;
432        let results = SearchResults {
433            groups: vec![
434                group(SearchKind::Shows, vec![hit(show("Severance"), Some("sa"))]),
435                episodes,
436            ],
437            ..SearchResults::default()
438        };
439        assert_eq!(results.clone().only_from(Some("sa")).groups[1].hidden, 3);
440        assert_eq!(
441            results.clone().only_from(Some("sa")).counts.episodes,
442            Some(3)
443        );
444        assert_eq!(results.clone().only_from(None).groups[1].hidden, 0);
445    }
446
447    #[test]
448    fn see_all_names_the_groups_total_else_its_scopes_count() {
449        let mut movies = group(SearchKind::Movies, vec![movie(own("1"), "Alien")]);
450        movies.more = true;
451        let mut results = SearchResults {
452            groups: vec![movies, group(SearchKind::Shows, Vec::new())],
453            counts: SearchCounts {
454                movies: Some(23),
455                ..SearchCounts::default()
456            },
457            ..SearchResults::default()
458        };
459        assert_eq!(results.see_all_count(SearchKind::Movies), Some(23));
460        results.groups[0].total = Some(25);
461        assert_eq!(results.see_all_count(SearchKind::Movies), Some(25));
462        // Nothing more to see.
463        assert_eq!(results.see_all_count(SearchKind::Shows), None);
464    }
465
466    #[test]
467    fn hidden_episodes_name_the_shows_that_hold_them() {
468        let mut episodes = group(SearchKind::Episodes, Vec::new());
469        episodes.hidden = 3;
470        let results = SearchResults {
471            top: Some(TopResult::Item(show("Severance").into())),
472            groups: vec![
473                group(SearchKind::Shows, vec![show("Silo").into()]),
474                episodes,
475            ],
476            ..SearchResults::default()
477        };
478        assert_eq!(
479            results.hidden_under(SearchKind::Episodes),
480            Some(HiddenUnder {
481                count: 3,
482                shows: vec!["Silo".into(), "Severance".into()],
483            })
484        );
485        assert_eq!(results.hidden_under(SearchKind::Shows), None);
486    }
487}