Skip to main content

spoolframe_protocol/
playlists.rs

1//! Playlists (feature `spoolframe:playlists`): ordered
2//! lists of movies, episodes and tracks a user makes, shares, pins and
3//! plays.
4//!
5//! An entry is one place in a playlist, named by its [`EntryId`]: the same
6//! item may be in a playlist more than once, as two entries. Edits name
7//! entries, never items, so two editors moving the same film each move
8//! their own.
9
10use serde::{Deserialize, Serialize};
11use spoolframe_types::{ArtworkId, MediaId, MediaKind};
12
13/// One place in a playlist. Never reused, in any playlist.
14pub type EntryId = u64;
15
16/// The largest cover a `SetPlaylistArt` takes, in bytes: past it,
17/// `ImageTooLarge`, and the bytes are not read.
18pub const MAX_ART_BYTES: u64 = 20 << 20;
19
20/// The most pixels a cover may have: past it, `ImageTooLarge`,
21/// from the picture's header, before it is decoded.
22pub const MAX_ART_PIXELS: u64 = 40_000_000;
23
24/// The kinds of item a playlist may hold, ticked when it is made. They
25/// can change later only to allow more.
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
28pub struct Kinds {
29    #[cfg_attr(feature = "uniffi", uniffi(default = false))]
30    pub movies: bool,
31    #[cfg_attr(feature = "uniffi", uniffi(default = false))]
32    pub episodes: bool,
33    #[cfg_attr(feature = "uniffi", uniffi(default = false))]
34    pub tracks: bool,
35}
36
37impl Kinds {
38    /// Whether an item of `kind` may be added. A season or show adds its
39    /// episodes, an album or artist its tracks: they are allowed when
40    /// those are.
41    pub fn allows(self, kind: MediaKind) -> bool {
42        match kind {
43            MediaKind::Movie => self.movies,
44            MediaKind::Episode | MediaKind::Season | MediaKind::Show => self.episodes,
45            MediaKind::Track | MediaKind::Album | MediaKind::Artist => self.tracks,
46        }
47    }
48
49    /// Ticks none: not a playlist's kinds.
50    pub fn is_empty(self) -> bool {
51        !(self.movies || self.episodes || self.tracks)
52    }
53
54    /// Whether `to` keeps every kind these allow: the only change a
55    /// playlist's kinds may make.
56    pub fn widen_only(self, to: Kinds) -> bool {
57        (!self.movies || to.movies)
58            && (!self.episodes || to.episodes)
59            && (!self.tracks || to.tracks)
60    }
61}
62
63/// An item's kind, as `KindNotAllowed` names the one refused.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
65#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
66#[serde(rename_all = "snake_case")]
67pub enum ItemKind {
68    Movie,
69    Show,
70    Season,
71    Episode,
72    Artist,
73    Album,
74    Track,
75    #[serde(other)]
76    Unknown,
77}
78
79impl From<MediaKind> for ItemKind {
80    fn from(kind: MediaKind) -> Self {
81        match kind {
82            MediaKind::Movie => ItemKind::Movie,
83            MediaKind::Show => ItemKind::Show,
84            MediaKind::Season => ItemKind::Season,
85            MediaKind::Episode => ItemKind::Episode,
86            MediaKind::Artist => ItemKind::Artist,
87            MediaKind::Album => ItemKind::Album,
88            MediaKind::Track => ItemKind::Track,
89        }
90    }
91}
92
93/// One change to a playlist's entries (`EditPlaylist`).
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
96#[serde(tag = "type", rename_all = "snake_case")]
97pub enum PlaylistEdit {
98    /// Add `id` before entry `before`, or at the end when `None` (or when
99    /// that entry is gone by the time the edit is redone on a newer
100    /// revision). A movie, an episode or a track adds itself; a season its
101    /// episodes, a show every episode in airing order (specials last), an
102    /// album its tracks in disc and track order, an artist each album's in
103    /// turn.
104    Add {
105        id: MediaId,
106        #[serde(deserialize_with = "spoolframe_types::required::option")]
107        before: Option<EntryId>,
108    },
109    /// Take the entry out.
110    Remove { entry: EntryId },
111    /// Put the entry before `before`, or at the end when `None` (or when
112    /// that entry is gone by the time the edit is redone).
113    Move {
114        entry: EntryId,
115        #[serde(deserialize_with = "spoolframe_types::required::option")]
116        before: Option<EntryId>,
117    },
118    /// An edit this build does not know; refused with `InvalidInput`.
119    #[serde(other)]
120    Unknown,
121}
122
123impl PlaylistEdit {
124    /// The existing entry it changes, if any: an add changes none.
125    pub fn touches(&self) -> Option<EntryId> {
126        match self {
127            PlaylistEdit::Remove { entry } | PlaylistEdit::Move { entry, .. } => Some(*entry),
128            PlaylistEdit::Add { .. } | PlaylistEdit::Unknown => None,
129        }
130    }
131}
132
133/// Who sees a playlist, as whoever manages it sets it.
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
136#[serde(tag = "type", rename_all = "snake_case")]
137pub enum Visibility {
138    /// Its owner alone.
139    Personal,
140    /// Its owner and these users. Listed only to whoever manages the
141    /// playlist; anyone else sees it empty.
142    Shared { with: Vec<PlaylistShare> },
143    /// Every user of the server, portable guests included; admins edit
144    /// it. Only an admin makes one.
145    ServerWide,
146    /// A kind this build does not know; refused with `InvalidInput`.
147    #[serde(other)]
148    Unknown,
149}
150
151/// One user a playlist is shared with.
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
154pub struct PlaylistShare {
155    /// As `WhoAmI` gives it: `local:<uuid>`, or `portable:` and 64 hex
156    /// digits.
157    pub user_id: String,
158    /// They may add, remove and move its entries; never rename it, change
159    /// its kinds or sharing, or delete it.
160    pub can_edit: bool,
161    /// What they are shown as; `None` for someone no longer here (shown
162    /// by `user_id`). Read by no request: a share is named by `user_id`
163    /// alone, and a client sends `null`.
164    #[serde(deserialize_with = "spoolframe_types::required::option")]
165    pub display_name: Option<String>,
166    /// Whose account they are. Read by no request: a client sends `null`.
167    #[serde(deserialize_with = "spoolframe_types::required::option")]
168    pub kind: Option<UserKind>,
169}
170
171impl PlaylistShare {
172    /// A share with `user_id`, as a request names it: no name, no kind.
173    pub fn new(user_id: impl Into<String>, can_edit: bool) -> Self {
174        Self {
175            user_id: user_id.into(),
176            can_edit,
177            display_name: None,
178            kind: None,
179        }
180    }
181}
182
183/// Whose account a user is (`spoolframe:playlist-sharing`).
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
185#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
186#[serde(rename_all = "snake_case")]
187pub enum UserKind {
188    /// An account on this server: `local:<uuid>`.
189    Local,
190    /// A portable user granted access here: `portable:` and 64 hex
191    /// digits.
192    Portable,
193    /// One this build does not know.
194    #[serde(other)]
195    Unknown,
196}
197
198/// Someone a playlist can be shared with (`ListShareCandidates`): an
199/// enabled account here, or a portable user granted access.
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
201pub struct ShareCandidate {
202    /// As [`PlaylistShare::user_id`] takes it.
203    pub user_id: String,
204    /// What they are shown as: an account's display name, else its
205    /// username; a portable user's name, else their fingerprint.
206    pub display_name: String,
207    /// An account's username; `None` for a portable user, who has none
208    /// here.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub username: Option<String>,
211    pub kind: UserKind,
212}
213
214/// One page of whom a playlist can be shared with
215/// (`ListShareCandidates`), by display name.
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217pub struct ShareCandidatePage {
218    pub candidates: Vec<ShareCandidate>,
219    /// Where `candidates` start in the whole list.
220    pub offset: u32,
221    /// How many match in all.
222    pub total: u32,
223}
224
225/// How a playlist stands to whoever asks: what a client lists its
226/// playlists apart by.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
228#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
229#[serde(rename_all = "snake_case")]
230pub enum PlaylistOwnerKind {
231    /// Theirs, personal or shared by them.
232    Mine,
233    /// Someone else's, shared with them.
234    SharedWithMe,
235    /// Seen by every user.
236    ServerWide,
237    #[serde(other)]
238    Unknown,
239}
240
241/// A built-in playlist: every user has one of each, made by the
242/// server, never renamed, re-kinded, shared or deleted. Music only.
243#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
244#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
245#[serde(rename_all = "snake_case")]
246pub enum Builtin {
247    /// The tracks the user liked (`Like`), newest first unless they
248    /// moved them. Its entries change by `Like` and `Unlike`, and by
249    /// `EditPlaylist`'s removes and moves; an add there is refused.
250    Liked,
251    /// Every track the user may see, worked out when read or played, so
252    /// a newly scanned album is in it at once. Read-only.
253    All,
254    /// One this build does not know: shown as any read-only playlist.
255    #[serde(other)]
256    Unknown,
257}
258
259/// A heart: whether an item is in the user's Liked. A track's is
260/// `All` or `None`; an album's is `All` when every track it has now is
261/// liked, `Some` when some are, `None` when none are.
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
263#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
264#[serde(rename_all = "snake_case")]
265pub enum Liked {
266    All,
267    Some,
268    None,
269    /// One this build does not know: shown as `None`.
270    #[serde(other)]
271    Unknown,
272}
273
274/// A playlist as one user sees it, without its entries.
275#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
276#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
277pub struct PlaylistSummary {
278    pub id: String,
279    pub name: String,
280    pub kinds: Kinds,
281    pub owner_kind: PlaylistOwnerKind,
282    pub visibility: Visibility,
283    /// They may change its entries (`EditPlaylist`).
284    pub can_edit: bool,
285    /// They may rename it, change its kinds and sharing
286    /// (`UpdatePlaylist`), and delete it.
287    pub can_manage: bool,
288    /// What an `EditPlaylist` names; raised by every change.
289    pub revision: u64,
290    /// Its place in their Pinned (0 first), or `None` when not pinned.
291    #[serde(deserialize_with = "spoolframe_types::required::option")]
292    pub pinned: Option<u32>,
293    /// Which built-in playlist it is, or `None` for one a user
294    /// made: what a client lists Liked and All first by, and hides
295    /// rename, share and delete for.
296    #[serde(deserialize_with = "spoolframe_types::required::option")]
297    pub builtin: Option<Builtin>,
298    /// What its owner is shown as: what a row says "Alice's" by. `None`
299    /// for an owner no longer here.
300    #[serde(deserialize_with = "spoolframe_types::required::option")]
301    pub owner_name: Option<String>,
302    /// Its picture, fetched as any artwork is: the cover an editor uploaded;
303    /// else a 2×2 mosaic of the first four different album covers or
304    /// posters in it; one alone when it has fewer; a placeholder when it
305    /// has none. Liked's and All's are fixed tiles. Changes when any of
306    /// that does.
307    #[serde(deserialize_with = "spoolframe_types::required::option")]
308    pub artwork: Option<ArtworkId>,
309    /// `artwork` is a cover an editor uploaded, which `RemovePlaylistArt`
310    /// takes away; false for a mosaic, a placeholder or a built-in tile.
311    pub custom_art: bool,
312}
313
314/// Whose a playlist is, as its card says under its name
315/// ([`PlaylistSummary::facts`]).
316#[derive(Debug, Clone, PartialEq, Eq)]
317pub enum PlaylistOwner {
318    /// Liked or All, the server's own.
319    BuiltIn(Builtin),
320    /// The user's, shared with `shared_with` people (none: personal).
321    Yours { shared_with: usize },
322    /// Someone else's, shared with the user: by `owner` where the server
323    /// names them.
324    SharedWithYou {
325        owner: Option<String>,
326        can_edit: bool,
327    },
328    /// Every user's; `can_edit` for an admin.
329    ServerWide { can_edit: bool },
330}
331
332/// What a playlist's card says of it, worked out once.
333#[derive(Debug, Clone, PartialEq, Eq)]
334pub struct PlaylistFacts {
335    pub owner: PlaylistOwner,
336    pub kinds: Kinds,
337    /// Tracks and nothing else: it plays as music does, with no place
338    /// kept and no watched to skip.
339    pub music_only: bool,
340    pub pinned: bool,
341}
342
343impl PlaylistSummary {
344    /// Whose it is and what it holds, for its card. A kind of owner from
345    /// a newer server reads as shared with the user: someone else's.
346    pub fn facts(&self) -> PlaylistFacts {
347        let owner = match (self.builtin, self.owner_kind, &self.visibility) {
348            (Some(builtin), _, _) => PlaylistOwner::BuiltIn(builtin),
349            (None, PlaylistOwnerKind::Mine, Visibility::Shared { with }) => PlaylistOwner::Yours {
350                shared_with: with.len(),
351            },
352            (None, PlaylistOwnerKind::Mine, _) => PlaylistOwner::Yours { shared_with: 0 },
353            (None, PlaylistOwnerKind::ServerWide, _) => PlaylistOwner::ServerWide {
354                can_edit: self.can_manage,
355            },
356            (None, PlaylistOwnerKind::SharedWithMe | PlaylistOwnerKind::Unknown, _) => {
357                PlaylistOwner::SharedWithYou {
358                    owner: self.owner_name.clone(),
359                    can_edit: self.can_edit,
360                }
361            }
362        };
363        PlaylistFacts {
364            owner,
365            kinds: self.kinds,
366            music_only: self.kinds.tracks && !self.kinds.movies && !self.kinds.episodes,
367            pinned: self.pinned.is_some(),
368        }
369    }
370}
371
372/// A playlist holding an item, as the item's details list it.
373#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
374#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
375pub struct PlaylistRef {
376    pub id: String,
377    pub name: String,
378    pub owner_kind: PlaylistOwnerKind,
379    /// As [`PlaylistSummary::builtin`]. All is never listed here: it
380    /// holds every track.
381    #[serde(deserialize_with = "spoolframe_types::required::option")]
382    pub builtin: Option<Builtin>,
383    /// What its owner is shown as, as [`PlaylistSummary::owner_name`]:
384    /// what an item's row says "Alice's" by. `None` for an owner no
385    /// longer here.
386    #[serde(deserialize_with = "spoolframe_types::required::option")]
387    pub owner_name: Option<String>,
388    /// Its picture, as [`PlaylistSummary::artwork`]: an uploaded cover,
389    /// else the mosaic of its first four, so an item's page can show the
390    /// playlists holding it as it shows seasons.
391    #[serde(deserialize_with = "spoolframe_types::required::option")]
392    pub artwork: Option<ArtworkId>,
393}
394
395/// One entry of a playlist, with its item as the catalog has it now and
396/// the user's watch state on it.
397#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
398#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
399pub struct PlaylistEntry {
400    pub entry: EntryId,
401    pub item: spoolframe_types::Item,
402    /// Still in the library, but its file cannot be read now (a drive
403    /// offline, a file moved): shown, counted, skipped when playing.
404    pub unavailable: bool,
405    /// A track in the user's Liked: its heart.
406    pub liked: bool,
407}
408
409/// One page of a playlist's entries (`GetPlaylist`). Items the user may
410/// not see are neither listed nor counted.
411#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
412#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
413pub struct PlaylistPage {
414    pub playlist: PlaylistSummary,
415    pub entries: Vec<PlaylistEntry>,
416    /// Where `entries` start in the whole list.
417    pub offset: u32,
418    /// How many entries the whole list has.
419    pub total: u32,
420    /// How many of them can be played now: `total` less the unavailable.
421    /// All's is `total`: its files are looked at only as they
422    /// are listed and played, not all at every read.
423    pub playable: u32,
424    /// The user's place: the entry playing or last played, which
425    /// `PlayPlaylist` without `from` goes on from; `None` to start at the
426    /// top.
427    #[serde(deserialize_with = "spoolframe_types::required::option")]
428    pub place: Option<EntryId>,
429    /// How the user last played it.
430    pub settings: PlaySettings,
431}
432
433/// How a user plays a playlist, kept per user and playlist.
434#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
435#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
436pub struct PlaySettings {
437    /// Play in a shuffled order: every playable entry once per round.
438    #[cfg_attr(feature = "uniffi", uniffi(default = false))]
439    pub shuffle: bool,
440    pub repeat: Repeat,
441    /// Pass entries whose item the user has watched.
442    #[cfg_attr(feature = "uniffi", uniffi(default = false))]
443    pub skip_watched: bool,
444}
445
446/// What plays again.
447#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
448#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
449#[serde(rename_all = "snake_case")]
450pub enum Repeat {
451    /// The end of the playlist ends it. (Each takes the Linux app's own
452    /// name too, as its saved queues have it.)
453    #[default]
454    #[serde(alias = "Off")]
455    Off,
456    /// The same entry, over and over.
457    #[serde(alias = "One")]
458    One,
459    /// The whole playlist again after the last entry; shuffled, the same
460    /// round again.
461    #[serde(alias = "All")]
462    All,
463    /// A kind this build does not know: played as `Off`.
464    #[serde(other)]
465    Unknown,
466}
467
468/// The entry to play now (`PlayPlaylist`, `NextInPlaylist`), with its
469/// item, the user's watch state on it (to resume where they were) and its
470/// intro and credits markers (to skip the credits).
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
472#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
473pub struct PlaylistNext {
474    pub entry: EntryId,
475    pub item: spoolframe_types::Item,
476    pub markers: spoolframe_types::Markers,
477    /// A track in the user's Liked: the now-playing heart.
478    pub liked: bool,
479}
480
481impl From<PlaylistNext> for PlaylistEntry {
482    /// The server only ever answers with an entry that plays.
483    fn from(next: PlaylistNext) -> Self {
484        Self {
485            entry: next.entry,
486            item: next.item,
487            unavailable: false,
488            liked: next.liked,
489        }
490    }
491}
492
493/// What importing the user's Plex playlists made, or would make
494/// (`ImportPlexPlaylists`).
495#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
496pub struct PlexImport {
497    /// One per Plex playlist with at least one item found here; and one
498    /// named "Liked" for the tracks rated in Plex that were liked here,
499    /// its `entries` those newly liked.
500    pub made: Vec<PlexImported>,
501    /// The items, or whole playlists, not found here, and why.
502    pub unmapped: Vec<PlexUnmapped>,
503    /// Plex servers that could not be read for the user, and why.
504    pub notes: Vec<String>,
505}
506
507/// One Plex playlist imported.
508#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
509pub struct PlexImported {
510    /// Its name in Plex, and here.
511    pub name: String,
512    /// The playlist made; `None` on a dry run.
513    #[serde(deserialize_with = "spoolframe_types::required::option")]
514    pub playlist_id: Option<String>,
515    /// How many entries it has.
516    pub entries: u32,
517}
518
519/// Something of a Plex playlist not imported.
520#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
521pub struct PlexUnmapped {
522    /// The Plex playlist's name.
523    pub playlist: String,
524    /// The item's title; `None` for the whole playlist.
525    #[serde(deserialize_with = "spoolframe_types::required::option")]
526    pub title: Option<String>,
527    pub reason: String,
528}
529
530/// A pinned playlist that left the user's Pinned: say so once, then
531/// `DismissPinNotes`.
532#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
533#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
534pub struct PinNote {
535    pub playlist_id: String,
536    /// Its name when it left.
537    pub name: String,
538    pub reason: PinNoteReason,
539}
540
541#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
542#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
543#[serde(rename_all = "snake_case")]
544pub enum PinNoteReason {
545    /// It is no longer shared with them.
546    Unshared,
547    /// It was deleted.
548    Deleted,
549    #[serde(other)]
550    Unknown,
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556    fn summary(owner_kind: PlaylistOwnerKind, visibility: Visibility) -> PlaylistSummary {
557        PlaylistSummary {
558            id: "p".into(),
559            name: "Heists".into(),
560            kinds: Kinds {
561                tracks: true,
562                ..Kinds::default()
563            },
564            owner_kind,
565            visibility,
566            can_edit: false,
567            can_manage: false,
568            revision: 1,
569            pinned: None,
570            builtin: None,
571            owner_name: Some("Alice".into()),
572            artwork: None,
573            custom_art: false,
574        }
575    }
576
577    #[test]
578    fn whose_it_is_reads_from_the_summary() {
579        let shared = Visibility::Shared {
580            with: vec![PlaylistShare::new("local:b", false)],
581        };
582        let mine = summary(PlaylistOwnerKind::Mine, shared).facts();
583        assert_eq!(mine.owner, PlaylistOwner::Yours { shared_with: 1 });
584        assert!(mine.music_only);
585        let theirs = summary(PlaylistOwnerKind::SharedWithMe, Visibility::Personal).facts();
586        assert_eq!(
587            theirs.owner,
588            PlaylistOwner::SharedWithYou {
589                owner: Some("Alice".into()),
590                can_edit: false
591            }
592        );
593        let newer = summary(PlaylistOwnerKind::Unknown, Visibility::Personal).facts();
594        assert!(matches!(newer.owner, PlaylistOwner::SharedWithYou { .. }));
595        let mut liked = summary(PlaylistOwnerKind::Mine, Visibility::Personal);
596        liked.builtin = Some(Builtin::Liked);
597        assert_eq!(liked.facts().owner, PlaylistOwner::BuiltIn(Builtin::Liked));
598    }
599
600    const EPISODES: Kinds = Kinds {
601        movies: false,
602        episodes: true,
603        tracks: false,
604    };
605
606    #[test]
607    fn an_episodes_playlist_takes_seasons_and_shows_but_no_film_or_album() {
608        assert!(EPISODES.allows(MediaKind::Episode));
609        assert!(EPISODES.allows(MediaKind::Season));
610        assert!(EPISODES.allows(MediaKind::Show));
611        assert!(!EPISODES.allows(MediaKind::Movie));
612        assert!(!EPISODES.allows(MediaKind::Album));
613    }
614
615    #[test]
616    fn kinds_widen_and_never_narrow() {
617        let more = Kinds {
618            movies: true,
619            ..EPISODES
620        };
621        assert!(EPISODES.widen_only(more));
622        assert!(EPISODES.widen_only(EPISODES));
623        assert!(!more.widen_only(EPISODES));
624    }
625
626    #[test]
627    fn a_builtin_or_heart_of_a_newer_build_reads_as_unknown() {
628        let builtin: Builtin = serde_json::from_str(r#""recent""#).unwrap();
629        assert_eq!(builtin, Builtin::Unknown);
630        let liked: Liked = serde_json::from_str(r#""most""#).unwrap();
631        assert_eq!(liked, Liked::Unknown);
632        assert_eq!(serde_json::to_string(&Liked::Some).unwrap(), r#""some""#);
633    }
634
635    /// A summary without `builtin` and the rest, as a server before the
636    /// reset to revision 1 could send it, is refused.
637    #[test]
638    fn a_summary_without_builtin_is_refused() {
639        let json = serde_json::json!({
640            "id": "x", "name": "Heists",
641            "kinds": { "movies": false, "episodes": true, "tracks": false },
642            "owner_kind": "mine", "visibility": { "type": "personal" },
643            "can_edit": true, "can_manage": true, "revision": 1, "pinned": null,
644        });
645        let error = serde_json::from_value::<PlaylistSummary>(json).unwrap_err();
646        assert!(
647            error.to_string().contains("missing field `builtin`"),
648            "{error}"
649        );
650    }
651
652    /// A share without its name and kind keys is refused; a request's
653    /// share, which names neither, sends both as `null`.
654    #[test]
655    fn a_share_names_its_name_and_kind_or_null() {
656        assert!(
657            serde_json::from_str::<PlaylistShare>(r#"{"user_id":"local:x","can_edit":true}"#)
658                .is_err()
659        );
660        let sent = serde_json::to_value(PlaylistShare::new("local:x", false)).unwrap();
661        assert!(sent["display_name"].is_null(), "{sent}");
662        assert!(sent["kind"].is_null(), "{sent}");
663        assert_eq!(
664            serde_json::from_value::<PlaylistShare>(sent).unwrap(),
665            PlaylistShare::new("local:x", false)
666        );
667        let kind: UserKind = serde_json::from_str(r#""federated""#).unwrap();
668        assert_eq!(kind, UserKind::Unknown);
669    }
670
671    #[test]
672    fn an_edit_of_a_newer_build_reads_as_unknown() {
673        let edit: PlaylistEdit = serde_json::from_str(r#"{"type":"shuffle_all"}"#).unwrap();
674        assert_eq!(edit, PlaylistEdit::Unknown);
675    }
676}