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;
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` (Unix
92    /// seconds): Continue watching viewed lately, then Up next of shows
93    /// not already continued, then Recently added, films and shows only,
94    /// each show once (an episode or a season stands for its show).
95    pub fn featured(&self, now: i64, limits: FeaturedLimits) -> Vec<Featured> {
96        let mut picked: Vec<Featured> = Vec::new();
97        let mut seen = HashSet::new();
98        let mut add = |item: &Item, row, picked: &mut Vec<Featured>| {
99            if !video(item) || !seen.insert(shown_as(item).clone()) {
100                return false;
101            }
102            picked.push(Featured {
103                item: item.clone(),
104                row,
105            });
106            true
107        };
108        let viewed = |item: &Item| item.playback().and_then(|p| p.last_viewed_at);
109        // From a server that does not say when, all are taken as recent.
110        let timed = self.continue_watching.iter().any(|i| viewed(i).is_some());
111        let within = limits.continue_within.as_secs() as i64;
112        let recent = self
113            .continue_watching
114            .iter()
115            .filter(|i| !timed || viewed(i).is_some_and(|at| now - at < within))
116            .take(limits.continue_watching);
117        for item in recent {
118            add(item, FeaturedRow::ContinueWatching, &mut picked);
119        }
120        let mut up_next = 0;
121        for item in &self.next_up {
122            if up_next == limits.up_next {
123                break;
124            }
125            // A show already continued is skipped: `add` sees it.
126            if add(item, FeaturedRow::UpNext, &mut picked) {
127                up_next += 1;
128            }
129        }
130        for item in &self.recently_added {
131            if picked.len() >= limits.total {
132                break;
133            }
134            add(item, FeaturedRow::RecentlyAdded, &mut picked);
135        }
136        picked
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use spoolframe_types::{Episode, MediaKind, Movie, Namespace, PlaybackState};
144
145    fn id(kind: MediaKind, key: &str) -> MediaId {
146        MediaId::new(Namespace::Plex, kind, key).unwrap()
147    }
148
149    fn movie(key: &str, viewed: Option<i64>) -> Item {
150        Item::Movie(Movie {
151            id: id(MediaKind::Movie, key),
152            title: key.into(),
153            year: None,
154            release_date: None,
155            summary: None,
156            content_rating: None,
157            duration: None,
158            cast: Vec::new(),
159            artwork: Vec::new(),
160            playback: PlaybackState {
161                last_viewed_at: viewed,
162                ..PlaybackState::default()
163            },
164        })
165    }
166
167    fn episode(show: &str, n: u32) -> Item {
168        Item::Episode(Episode {
169            id: id(MediaKind::Episode, &format!("{show}{n}")),
170            show_id: id(MediaKind::Show, show),
171            show_title: Some(show.into()),
172            season_id: id(MediaKind::Season, &format!("{show}1")),
173            season: 1,
174            episode: n,
175            title: format!("{show} {n}"),
176            summary: None,
177            content_rating: None,
178            year: None,
179            air_date: None,
180            duration: None,
181            cast: Vec::new(),
182            artwork: Vec::new(),
183            playback: PlaybackState::default(),
184        })
185    }
186
187    fn home(continuing: Vec<Item>, next_up: Vec<Item>, added: Vec<Item>) -> HomeScreen {
188        HomeScreen {
189            continue_watching: continuing,
190            next_up,
191            recently_added: added,
192            unavailable: Vec::new(),
193            servers: Vec::new(),
194        }
195    }
196
197    #[test]
198    fn the_hero_is_the_first_continued_else_the_newest_added() {
199        let h = home(vec![movie("a", None)], Vec::new(), vec![movie("b", None)]);
200        assert_eq!(h.hero().map(|i| i.title()), Some("a"));
201        let h = home(Vec::new(), Vec::new(), vec![movie("b", None)]);
202        assert_eq!(h.hero().map(|i| i.title()), Some("b"));
203    }
204
205    #[test]
206    fn up_next_merged_has_each_show_once_continued_first() {
207        let h = home(
208            vec![movie("a", None), episode("s", 2)],
209            vec![episode("s", 3), episode("t", 1)],
210            Vec::new(),
211        );
212        let titles: Vec<_> = h
213            .up_next_merged()
214            .iter()
215            .map(|i| i.title().to_owned())
216            .collect();
217        assert_eq!(titles, ["a", "s 2", "t 1"]);
218    }
219
220    #[test]
221    fn featured_takes_what_was_continued_lately_then_up_next_then_added() {
222        let now = 1_000_000;
223        let h = home(
224            vec![
225                movie("lately", Some(now - 3600)),
226                movie("long ago", Some(now - 72 * 3600)),
227                episode("s", 4),
228            ],
229            vec![episode("s", 5), episode("t", 1)],
230            (0..20).map(|n| movie(&format!("new {n}"), None)).collect(),
231        );
232        let featured = h.featured(now, FeaturedLimits::default());
233        let rows: Vec<_> = featured
234            .iter()
235            .map(|f| (f.item.title().to_owned(), f.row))
236            .collect();
237        assert_eq!(rows[0], ("lately".into(), FeaturedRow::ContinueWatching));
238        // Not viewed within 48 hours, and an episode with no time.
239        assert!(!rows.iter().any(|(t, _)| t == "long ago" || t == "s 4"));
240        assert_eq!(rows[1], ("s 5".into(), FeaturedRow::UpNext));
241        assert_eq!(rows[2], ("t 1".into(), FeaturedRow::UpNext));
242        assert_eq!(featured.len(), 12);
243        assert_eq!(rows[11].1, FeaturedRow::RecentlyAdded);
244    }
245
246    #[test]
247    fn up_next_of_a_show_already_continued_is_not_featured_again() {
248        let h = home(vec![episode("s", 4)], vec![episode("s", 5)], Vec::new());
249        let featured = h.featured(0, FeaturedLimits::default());
250        assert_eq!(featured.len(), 1);
251        assert_eq!(featured[0].row, FeaturedRow::ContinueWatching);
252    }
253
254    #[test]
255    fn a_show_continued_is_not_featured_again_as_recently_added() {
256        let h = home(
257            vec![episode("s", 4)],
258            Vec::new(),
259            vec![episode("s", 9), movie("new", None)],
260        );
261        let titles: Vec<_> = h
262            .featured(0, FeaturedLimits::default())
263            .iter()
264            .map(|f| f.item.title().to_owned())
265            .collect();
266        assert_eq!(titles, ["s 4", "new"]);
267    }
268
269    #[test]
270    fn music_is_never_featured() {
271        let track = Item::Artist(spoolframe_types::Artist {
272            id: id(MediaKind::Artist, "1"),
273            name: "A".into(),
274            summary: None,
275            artwork: Vec::new(),
276        });
277        let h = home(Vec::new(), Vec::new(), vec![track]);
278        assert!(h.featured(0, FeaturedLimits::default()).is_empty());
279    }
280}