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