Skip to main content

spoolframe_protocol/
home_view.rs

1//! What a client picks out of Home: the hero, Continue watching and Up
2//! next as one row, and what a TV's Top Shelf or Watch Next shows.
3
4use std::collections::HashSet;
5use std::time::{Duration, SystemTime};
6
7use spoolframe_types::{Item, MediaId};
8
9use crate::messages::HomeScreen;
10
11/// Which of Home's rows a featured item came from.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum FeaturedRow {
14    ContinueWatching,
15    UpNext,
16    RecentlyAdded,
17}
18
19/// One item a TV features ([`HomeScreen::featured`]).
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Featured {
22    pub item: Item,
23    pub row: FeaturedRow,
24}
25
26/// How much of each row is featured.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct FeaturedLimits {
29    /// Continue watching viewed within this long; all of the newest when
30    /// the server does not say when each was viewed.
31    pub continue_within: Duration,
32    pub continue_watching: usize,
33    pub up_next: usize,
34    /// Recently added fills up to this many in all.
35    pub total: usize,
36}
37
38impl Default for FeaturedLimits {
39    /// The Apple TV's Top Shelf: three continued within 48 hours, five up
40    /// next, twelve in all.
41    fn default() -> Self {
42        Self {
43            continue_within: Duration::from_secs(48 * 3600),
44            continue_watching: 3,
45            up_next: 5,
46            total: 12,
47        }
48    }
49}
50
51/// A film, an episode, a show or a season: what a TV features.
52fn video(item: &Item) -> bool {
53    matches!(
54        item,
55        Item::Movie(_) | Item::Episode(_) | Item::Show(_) | Item::Season(_)
56    )
57}
58
59/// What a row shows once: an episode or a season stands for its show,
60/// anything else for itself.
61fn shown_as(item: &Item) -> &MediaId {
62    match item {
63        Item::Episode(e) => &e.show_id,
64        Item::Season(s) => &s.show_id,
65        other => other.id(),
66    }
67}
68
69impl HomeScreen {
70    /// The item Home shows large: the first continued, else the newest
71    /// added.
72    pub fn hero(&self) -> Option<&Item> {
73        self.continue_watching
74            .first()
75            .or_else(|| self.recently_added.first())
76    }
77
78    /// Continue watching, then Up next, as one row: each show once (its
79    /// first episode listed, the one continued before one up next), each
80    /// other item once.
81    pub fn up_next_merged(&self) -> Vec<Item> {
82        let mut seen = HashSet::new();
83        self.continue_watching
84            .iter()
85            .chain(&self.next_up)
86            .filter(|item| seen.insert(shown_as(item).clone()))
87            .cloned()
88            .collect()
89    }
90
91    /// What a TV's Top Shelf or Watch Next shows at `now`: Continue watching viewed lately, then Up next of shows
92    /// not already continued, then Recently added, films and shows only,
93    /// each show once (an episode or a season stands for its show).
94    pub fn featured(&self, now: SystemTime, limits: FeaturedLimits) -> Vec<Featured> {
95        let mut picked: Vec<Featured> = Vec::new();
96        let mut seen = HashSet::new();
97        let mut add = |item: &Item, row, picked: &mut Vec<Featured>| {
98            if !video(item) || !seen.insert(shown_as(item).clone()) {
99                return false;
100            }
101            picked.push(Featured {
102                item: item.clone(),
103                row,
104            });
105            true
106        };
107        let viewed = |item: &Item| item.playback().and_then(|p| p.last_viewed_at);
108        // From a server that does not say when, all are taken as recent.
109        let timed = self.continue_watching.iter().any(|i| viewed(i).is_some());
110        let recent = self
111            .continue_watching
112            .iter()
113            .filter(|i| {
114                !timed
115                    || viewed(i).is_some_and(|at| {
116                        // A time ahead of `now` (another clock) is recent.
117                        now.duration_since(at)
118                            .ok()
119                            .is_none_or(|ago| ago < limits.continue_within)
120                    })
121            })
122            .take(limits.continue_watching);
123        for item in recent {
124            add(item, FeaturedRow::ContinueWatching, &mut picked);
125        }
126        let mut up_next = 0;
127        for item in &self.next_up {
128            if up_next == limits.up_next {
129                break;
130            }
131            // A show already continued is skipped: `add` sees it.
132            if add(item, FeaturedRow::UpNext, &mut picked) {
133                up_next += 1;
134            }
135        }
136        for item in &self.recently_added {
137            if picked.len() >= limits.total {
138                break;
139            }
140            add(item, FeaturedRow::RecentlyAdded, &mut picked);
141        }
142        picked
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149    use spoolframe_types::{Episode, MediaKind, Movie, Namespace, PlaybackState};
150    use std::time::UNIX_EPOCH;
151
152    fn id(kind: MediaKind, key: &str) -> MediaId {
153        MediaId::new(Namespace::Plex, kind, key).unwrap()
154    }
155
156    fn movie(key: &str, viewed: Option<SystemTime>) -> Item {
157        Item::Movie(Movie {
158            id: id(MediaKind::Movie, key),
159            title: key.into(),
160            year: None,
161            release_date: None,
162            summary: None,
163            content_rating: None,
164            duration: None,
165            cast: Vec::new(),
166            artwork: Vec::new(),
167            playback: PlaybackState {
168                last_viewed_at: viewed,
169                ..PlaybackState::default()
170            },
171        })
172    }
173
174    fn episode(show: &str, n: u32) -> Item {
175        Item::Episode(Episode {
176            id: id(MediaKind::Episode, &format!("{show}{n}")),
177            show_id: id(MediaKind::Show, show),
178            show_title: Some(show.into()),
179            season_id: id(MediaKind::Season, &format!("{show}1")),
180            season: 1,
181            episode: n,
182            title: format!("{show} {n}"),
183            summary: None,
184            content_rating: None,
185            year: None,
186            air_date: None,
187            duration: None,
188            cast: Vec::new(),
189            artwork: Vec::new(),
190            playback: PlaybackState::default(),
191        })
192    }
193
194    fn home(continuing: Vec<Item>, next_up: Vec<Item>, added: Vec<Item>) -> HomeScreen {
195        HomeScreen {
196            continue_watching: continuing,
197            next_up,
198            recently_added: added,
199            unavailable: Vec::new(),
200            servers: Vec::new(),
201        }
202    }
203
204    #[test]
205    fn the_hero_is_the_first_continued_else_the_newest_added() {
206        let h = home(vec![movie("a", None)], Vec::new(), vec![movie("b", None)]);
207        assert_eq!(h.hero().map(|i| i.title()), Some("a"));
208        let h = home(Vec::new(), Vec::new(), vec![movie("b", None)]);
209        assert_eq!(h.hero().map(|i| i.title()), Some("b"));
210    }
211
212    #[test]
213    fn up_next_merged_has_each_show_once_continued_first() {
214        let h = home(
215            vec![movie("a", None), episode("s", 2)],
216            vec![episode("s", 3), episode("t", 1)],
217            Vec::new(),
218        );
219        let titles: Vec<_> = h
220            .up_next_merged()
221            .iter()
222            .map(|i| i.title().to_owned())
223            .collect();
224        assert_eq!(titles, ["a", "s 2", "t 1"]);
225    }
226
227    #[test]
228    fn featured_takes_what_was_continued_lately_then_up_next_then_added() {
229        let now = UNIX_EPOCH + Duration::from_secs(1_000_000);
230        let h = home(
231            vec![
232                movie("lately", Some(now - Duration::from_secs(3600))),
233                movie("long ago", Some(now - Duration::from_secs(72 * 3600))),
234                episode("s", 4),
235            ],
236            vec![episode("s", 5), episode("t", 1)],
237            (0..20).map(|n| movie(&format!("new {n}"), None)).collect(),
238        );
239        let featured = h.featured(now, FeaturedLimits::default());
240        let rows: Vec<_> = featured
241            .iter()
242            .map(|f| (f.item.title().to_owned(), f.row))
243            .collect();
244        assert_eq!(rows[0], ("lately".into(), FeaturedRow::ContinueWatching));
245        // Not viewed within 48 hours, and an episode with no time.
246        assert!(!rows.iter().any(|(t, _)| t == "long ago" || t == "s 4"));
247        assert_eq!(rows[1], ("s 5".into(), FeaturedRow::UpNext));
248        assert_eq!(rows[2], ("t 1".into(), FeaturedRow::UpNext));
249        assert_eq!(featured.len(), 12);
250        assert_eq!(rows[11].1, FeaturedRow::RecentlyAdded);
251    }
252
253    #[test]
254    fn up_next_of_a_show_already_continued_is_not_featured_again() {
255        let h = home(vec![episode("s", 4)], vec![episode("s", 5)], Vec::new());
256        let featured = h.featured(
257            spoolframe_types::serde_time::unix_seconds::from_wire(0),
258            FeaturedLimits::default(),
259        );
260        assert_eq!(featured.len(), 1);
261        assert_eq!(featured[0].row, FeaturedRow::ContinueWatching);
262    }
263
264    #[test]
265    fn a_show_continued_is_not_featured_again_as_recently_added() {
266        let h = home(
267            vec![episode("s", 4)],
268            Vec::new(),
269            vec![episode("s", 9), movie("new", None)],
270        );
271        let titles: Vec<_> = h
272            .featured(
273                spoolframe_types::serde_time::unix_seconds::from_wire(0),
274                FeaturedLimits::default(),
275            )
276            .iter()
277            .map(|f| f.item.title().to_owned())
278            .collect();
279        assert_eq!(titles, ["s 4", "new"]);
280    }
281
282    #[test]
283    fn music_is_never_featured() {
284        let track = Item::Artist(spoolframe_types::Artist {
285            id: id(MediaKind::Artist, "1"),
286            name: "A".into(),
287            summary: None,
288            artwork: Vec::new(),
289        });
290        let h = home(Vec::new(), Vec::new(), vec![track]);
291        assert!(
292            h.featured(
293                spoolframe_types::serde_time::unix_seconds::from_wire(0),
294                FeaturedLimits::default()
295            )
296            .is_empty()
297        );
298    }
299}