Skip to main content

spoolframe_types/
preferences.rs

1//! How a viewer wants tracks chosen. Kept per user on the server,
2//! so a TV and a laptop choose the same.
3
4use serde::{Deserialize, Serialize};
5
6use crate::media::AudioRole;
7
8/// A language code that stands for the item's original language: the
9/// language of the file's default audio track.
10pub const ORIGINAL_LANGUAGE: &str = "original";
11
12/// A language code that stands for the device's language: the one the
13/// connection's `Hello.language` says, at each choosing. Kept as it is, so
14/// a viewer's one setting means each of their devices' own language. Left
15/// out where the client says none.
16pub const DEVICE_LANGUAGE: &str = "device";
17
18/// Every field is required on the wire: a peer that leaves one out
19/// is refused, not filled in.
20#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
21#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
22pub struct TrackPreferences {
23    pub audio: AudioPreferences,
24    pub subtitles: SubtitlePreferences,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
29pub struct AudioPreferences {
30    /// ISO 639 codes in order of preference, or [`ORIGINAL_LANGUAGE`] or
31    /// [`DEVICE_LANGUAGE`]. Empty: the file's default track.
32    pub languages: Vec<String>,
33    /// Roles never chosen while another track is left.
34    pub avoid: Vec<AudioRole>,
35}
36
37impl Default for AudioPreferences {
38    fn default() -> Self {
39        Self {
40            languages: Vec::new(),
41            avoid: vec![AudioRole::AudioDescription, AudioRole::Commentary],
42        }
43    }
44}
45
46#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
47#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
48pub struct SubtitlePreferences {
49    pub mode: SubtitleMode,
50    /// ISO 639 codes in order of preference, or [`DEVICE_LANGUAGE`].
51    /// Empty: the audio's language. A list of only [`DEVICE_LANGUAGE`] on
52    /// a device that says none matches nothing, and is not empty.
53    pub languages: Vec<String>,
54    pub sdh: SdhPreference,
55    /// How picture subtitles (PGS, VobSub, DVB) are shown when the app
56    /// leaves it to the server. It has no effect on a server that does not
57    /// read them as text.
58    pub bitmap: BitmapPreference,
59    /// Forced subtitles (only the parts in another language) among a
60    /// subtitle search's results. Playback follows `mode`.
61    pub forced: ForcedPreference,
62}
63
64/// When subtitles are shown.
65#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
66#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
67#[serde(rename_all = "snake_case")]
68pub enum SubtitleMode {
69    /// Always, in a preferred language.
70    Always,
71    /// Only when the audio is not in a preferred subtitle language.
72    ForeignOnly,
73    Off,
74    /// Only forced subtitles (foreign parts, signs) in the audio's
75    /// language. Also any mode this build does not know. (Last, as serde
76    /// wants of `other`.)
77    #[default]
78    #[serde(other)]
79    ForcedOnly,
80}
81
82/// What to do with subtitles for the deaf and hard of hearing: in
83/// playback, which track is chosen; in a subtitle search, the
84/// results' order, or which are listed at all.
85#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
86#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
87#[serde(rename_all = "snake_case")]
88pub enum SdhPreference {
89    /// SDH before plain subtitles.
90    Prefer,
91    /// Never SDH: a search lists none.
92    Avoid,
93    /// Only SDH: no subtitles where there is none, and a search lists no
94    /// plain ones. An older peer that does not know it reads it as
95    /// `Accept`.
96    Only,
97    /// Plain subtitles first, SDH when there are none. Also any value this
98    /// build does not know. (Last, as serde wants of `other`.)
99    #[default]
100    #[serde(other)]
101    Accept,
102}
103
104/// What to do with forced subtitles (only the parts in another language:
105/// signs, a foreign line) in a subtitle search's results: the
106/// same four ways as [`SdhPreference`].
107#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
108#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
109#[serde(rename_all = "snake_case")]
110pub enum ForcedPreference {
111    /// Forced ones before the rest.
112    Prefer,
113    /// None forced.
114    Avoid,
115    /// Only forced ones.
116    Only,
117    /// The rest first, forced ones after. Also any value this build does
118    /// not know. (Last, as serde wants of `other`.)
119    #[default]
120    #[serde(other)]
121    Accept,
122}
123
124/// How a viewer wants picture subtitles shown: read as text by the
125/// server, so any device shows them styled and sized, or as the pictures
126/// they are.
127#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
128#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
129#[serde(rename_all = "snake_case")]
130pub enum BitmapPreference {
131    /// Drawn by the device if it can, else burned into the video.
132    Pictures,
133    /// Read as text when the server can read the track; else as
134    /// `Pictures`. Also any value this build does not know. (Last, as
135    /// serde wants of `other`.)
136    #[default]
137    #[serde(other)]
138    Text,
139}
140
141/// How the user's music shows in Home's "Recently played" row.
142#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
143#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
144#[serde(rename_all = "snake_case")]
145pub enum RecentMusicMode {
146    /// By where each play was started: the playlist, the album, or the
147    /// track when it was queued by hand. A play with no source (one from
148    /// before sources were kept) shows its album.
149    #[default]
150    Sources,
151    /// Each track played, its own card.
152    Tracks,
153    /// Each track played folded into its album, whatever its source.
154    Albums,
155    /// No music in the row.
156    Hidden,
157    /// A choice this build does not know: read as [`Self::Sources`].
158    #[serde(other)]
159    Unknown,
160}
161
162/// How the user's shows show in Home's "Recently played" row.
163#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
164#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
165#[serde(rename_all = "snake_case")]
166pub enum RecentShowsMode {
167    /// One card for the show, at its latest episode played.
168    Show,
169    /// One card for each season played.
170    Season,
171    /// Each episode played, its own card.
172    #[default]
173    Episode,
174    /// No shows in the row.
175    Hidden,
176    /// A choice this build does not know: read as [`Self::Episode`].
177    #[serde(other)]
178    Unknown,
179}
180
181/// How the user's films show in Home's "Recently played" row.
182#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
183#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
184#[serde(rename_all = "snake_case")]
185pub enum RecentMoviesMode {
186    /// Each film played, its own card.
187    #[default]
188    Movie,
189    /// No films in the row.
190    Hidden,
191    /// A choice this build does not know: read as [`Self::Movie`].
192    #[serde(other)]
193    Unknown,
194}
195
196/// How each kind shows in a user's Home "Recently played" row, kept on
197/// the server for every device of theirs (`RecentlyPlayedPreferences` and
198/// `SetRecentlyPlayedPreferences` in `spoolframe-protocol`). It only
199/// changes what the row shows: every play is recorded and counted
200/// whatever it says. Every field is required on the wire.
201#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
202#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
203pub struct RecentlyPlayedPreferences {
204    pub music: RecentMusicMode,
205    pub shows: RecentShowsMode,
206    pub movies: RecentMoviesMode,
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn a_new_user_follows_the_file_avoids_description_and_shows_only_forced() {
215        let p = TrackPreferences::default();
216        assert!(p.audio.languages.is_empty());
217        assert_eq!(
218            p.audio.avoid,
219            [AudioRole::AudioDescription, AudioRole::Commentary]
220        );
221        assert_eq!(p.subtitles.mode, SubtitleMode::ForcedOnly);
222    }
223
224    /// The defaults as JSON, with `edit` applied.
225    fn full(edit: impl FnOnce(&mut serde_json::Value)) -> serde_json::Value {
226        let mut json = serde_json::to_value(TrackPreferences::default()).unwrap();
227        edit(&mut json);
228        json
229    }
230
231    #[test]
232    fn picture_subtitles_are_read_as_text_unless_the_viewer_wants_pictures() {
233        assert_eq!(
234            TrackPreferences::default().subtitles.bitmap,
235            BitmapPreference::Text
236        );
237        let p: TrackPreferences =
238            serde_json::from_value(full(|j| j["subtitles"]["bitmap"] = "pictures".into())).unwrap();
239        assert_eq!(p.subtitles.bitmap, BitmapPreference::Pictures);
240    }
241
242    #[test]
243    fn a_picture_subtitle_preference_this_build_does_not_know_reads_as_text() {
244        let p: TrackPreferences =
245            serde_json::from_value(full(|j| j["subtitles"]["bitmap"] = "hologram".into())).unwrap();
246        assert_eq!(p.subtitles.bitmap, BitmapPreference::Text);
247    }
248
249    #[test]
250    fn every_field_round_trips() {
251        let p: TrackPreferences = serde_json::from_value(full(|_| {})).unwrap();
252        assert_eq!(p, TrackPreferences::default());
253    }
254
255    #[test]
256    fn only_sdh_reads_and_an_unknown_sdh_preference_is_accept() {
257        let p: TrackPreferences =
258            serde_json::from_value(full(|j| j["subtitles"]["sdh"] = "only".into())).unwrap();
259        assert_eq!(p.subtitles.sdh, SdhPreference::Only);
260        let p: TrackPreferences =
261            serde_json::from_value(full(|j| j["subtitles"]["sdh"] = "sometimes".into())).unwrap();
262        assert_eq!(p.subtitles.sdh, SdhPreference::Accept);
263    }
264
265    #[test]
266    fn a_forced_preference_reads_by_name_and_an_unknown_one_is_accept() {
267        assert_eq!(
268            TrackPreferences::default().subtitles.forced,
269            ForcedPreference::Accept
270        );
271        for (name, wanted) in [
272            ("prefer", ForcedPreference::Prefer),
273            ("avoid", ForcedPreference::Avoid),
274            ("only", ForcedPreference::Only),
275            ("accept", ForcedPreference::Accept),
276            ("hologram", ForcedPreference::Accept),
277        ] {
278            let p: TrackPreferences =
279                serde_json::from_value(full(|j| j["subtitles"]["forced"] = name.into())).unwrap();
280            assert_eq!(p.subtitles.forced, wanted, "{name}");
281        }
282    }
283
284    /// Preferences without the forced preference, as a peer before the
285    /// reset to revision 1 could send them, are refused.
286    #[test]
287    fn preferences_without_the_forced_preference_are_refused() {
288        let error = serde_json::from_value::<TrackPreferences>(full(|j| {
289            j["subtitles"].as_object_mut().unwrap().remove("forced");
290        }))
291        .unwrap_err();
292        assert!(
293            error.to_string().contains("missing field `forced`"),
294            "{error}"
295        );
296    }
297
298    /// Each field in turn, by its JSON path, left out of the defaults.
299    /// (Not `subtitles.forced`, which a peer before it leaves out.)
300    #[test]
301    fn preferences_missing_any_field_are_refused() {
302        for (section, field) in [
303            (None, "audio"),
304            (None, "subtitles"),
305            (Some("audio"), "languages"),
306            (Some("audio"), "avoid"),
307            (Some("subtitles"), "mode"),
308            (Some("subtitles"), "languages"),
309            (Some("subtitles"), "sdh"),
310            (Some("subtitles"), "bitmap"),
311        ] {
312            let json = full(|j| {
313                let object = match section {
314                    Some(section) => &mut j[section],
315                    None => j,
316                };
317                object.as_object_mut().unwrap().remove(field);
318            });
319            let error = serde_json::from_value::<TrackPreferences>(json).unwrap_err();
320            assert!(
321                error
322                    .to_string()
323                    .contains(&format!("missing field `{field}`")),
324                "{section:?}.{field}: {error}"
325            );
326        }
327    }
328}