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. So too a track's in
423    /// any playlist over 200 entries, off the page read.
424    pub playable: u32,
425    /// The user's place: the entry playing or last played, which
426    /// `PlayPlaylist` without `from` goes on from; `None` to start at the
427    /// top.
428    #[serde(deserialize_with = "spoolframe_types::required::option")]
429    pub place: Option<EntryId>,
430    /// How the user last played it.
431    pub settings: PlaySettings,
432}
433
434/// How a user plays a playlist, kept per user and playlist.
435#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
436#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
437pub struct PlaySettings {
438    /// Play in a shuffled order: every playable entry once per round.
439    #[cfg_attr(feature = "uniffi", uniffi(default = false))]
440    pub shuffle: bool,
441    pub repeat: Repeat,
442    /// Pass entries whose item the user has watched.
443    #[cfg_attr(feature = "uniffi", uniffi(default = false))]
444    pub skip_watched: bool,
445}
446
447/// What plays again.
448#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
449#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
450#[serde(rename_all = "snake_case")]
451pub enum Repeat {
452    /// The end of the playlist ends it. (Each takes the Linux app's own
453    /// name too, as its saved queues have it.)
454    #[default]
455    #[serde(alias = "Off")]
456    Off,
457    /// The same entry, over and over.
458    #[serde(alias = "One")]
459    One,
460    /// The whole playlist again after the last entry; shuffled, the same
461    /// round again.
462    #[serde(alias = "All")]
463    All,
464    /// A kind this build does not know: played as `Off`.
465    #[serde(other)]
466    Unknown,
467}
468
469/// The entry to play now (`PlayPlaylist`, `NextInPlaylist`), with its
470/// item, the user's watch state on it (to resume where they were) and its
471/// intro and credits markers (to skip the credits).
472#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
473#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
474pub struct PlaylistNext {
475    pub entry: EntryId,
476    pub item: spoolframe_types::Item,
477    pub markers: spoolframe_types::Markers,
478    /// A track in the user's Liked: the now-playing heart.
479    pub liked: bool,
480}
481
482impl From<PlaylistNext> for PlaylistEntry {
483    /// The server only ever answers with an entry that plays.
484    fn from(next: PlaylistNext) -> Self {
485        Self {
486            entry: next.entry,
487            item: next.item,
488            unavailable: false,
489            liked: next.liked,
490        }
491    }
492}
493
494/// What importing the user's Plex playlists made, or would make
495/// (`ImportPlexPlaylists`).
496#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
497pub struct PlexImport {
498    /// One per Plex playlist with at least one item found here; and one
499    /// named "Liked" for the tracks rated in Plex that were liked here,
500    /// its `entries` those newly liked.
501    pub made: Vec<PlexImported>,
502    /// The items, or whole playlists, not found here, and why.
503    pub unmapped: Vec<PlexUnmapped>,
504    /// Plex servers that could not be read for the user, and why.
505    pub notes: Vec<String>,
506}
507
508/// One Plex playlist imported.
509#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
510pub struct PlexImported {
511    /// Its name in Plex, and here.
512    pub name: String,
513    /// The playlist made; `None` on a dry run.
514    #[serde(deserialize_with = "spoolframe_types::required::option")]
515    pub playlist_id: Option<String>,
516    /// How many entries it has.
517    pub entries: u32,
518}
519
520/// Something of a Plex playlist not imported.
521#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
522pub struct PlexUnmapped {
523    /// The Plex playlist's name.
524    pub playlist: String,
525    /// The item's title; `None` for the whole playlist.
526    #[serde(deserialize_with = "spoolframe_types::required::option")]
527    pub title: Option<String>,
528    pub reason: String,
529}
530
531/// A pinned playlist that left the user's Pinned: say so once, then
532/// `DismissPinNotes`.
533#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
534#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
535pub struct PinNote {
536    pub playlist_id: String,
537    /// Its name when it left.
538    pub name: String,
539    pub reason: PinNoteReason,
540}
541
542#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
543#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
544#[serde(rename_all = "snake_case")]
545pub enum PinNoteReason {
546    /// It is no longer shared with them.
547    Unshared,
548    /// It was deleted.
549    Deleted,
550    #[serde(other)]
551    Unknown,
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557    fn summary(owner_kind: PlaylistOwnerKind, visibility: Visibility) -> PlaylistSummary {
558        PlaylistSummary {
559            id: "p".into(),
560            name: "Heists".into(),
561            kinds: Kinds {
562                tracks: true,
563                ..Kinds::default()
564            },
565            owner_kind,
566            visibility,
567            can_edit: false,
568            can_manage: false,
569            revision: 1,
570            pinned: None,
571            builtin: None,
572            owner_name: Some("Alice".into()),
573            artwork: None,
574            custom_art: false,
575        }
576    }
577
578    #[test]
579    fn whose_it_is_reads_from_the_summary() {
580        let shared = Visibility::Shared {
581            with: vec![PlaylistShare::new("local:b", false)],
582        };
583        let mine = summary(PlaylistOwnerKind::Mine, shared).facts();
584        assert_eq!(mine.owner, PlaylistOwner::Yours { shared_with: 1 });
585        assert!(mine.music_only);
586        let theirs = summary(PlaylistOwnerKind::SharedWithMe, Visibility::Personal).facts();
587        assert_eq!(
588            theirs.owner,
589            PlaylistOwner::SharedWithYou {
590                owner: Some("Alice".into()),
591                can_edit: false
592            }
593        );
594        let newer = summary(PlaylistOwnerKind::Unknown, Visibility::Personal).facts();
595        assert!(matches!(newer.owner, PlaylistOwner::SharedWithYou { .. }));
596        let mut liked = summary(PlaylistOwnerKind::Mine, Visibility::Personal);
597        liked.builtin = Some(Builtin::Liked);
598        assert_eq!(liked.facts().owner, PlaylistOwner::BuiltIn(Builtin::Liked));
599    }
600
601    const EPISODES: Kinds = Kinds {
602        movies: false,
603        episodes: true,
604        tracks: false,
605    };
606
607    #[test]
608    fn an_episodes_playlist_takes_seasons_and_shows_but_no_film_or_album() {
609        assert!(EPISODES.allows(MediaKind::Episode));
610        assert!(EPISODES.allows(MediaKind::Season));
611        assert!(EPISODES.allows(MediaKind::Show));
612        assert!(!EPISODES.allows(MediaKind::Movie));
613        assert!(!EPISODES.allows(MediaKind::Album));
614    }
615
616    #[test]
617    fn kinds_widen_and_never_narrow() {
618        let more = Kinds {
619            movies: true,
620            ..EPISODES
621        };
622        assert!(EPISODES.widen_only(more));
623        assert!(EPISODES.widen_only(EPISODES));
624        assert!(!more.widen_only(EPISODES));
625    }
626
627    #[test]
628    fn a_builtin_or_heart_of_a_newer_build_reads_as_unknown() {
629        let builtin: Builtin = serde_json::from_str(r#""recent""#).unwrap();
630        assert_eq!(builtin, Builtin::Unknown);
631        let liked: Liked = serde_json::from_str(r#""most""#).unwrap();
632        assert_eq!(liked, Liked::Unknown);
633        assert_eq!(serde_json::to_string(&Liked::Some).unwrap(), r#""some""#);
634    }
635
636    /// A summary without `builtin` and the rest, as a server before the
637    /// reset to revision 1 could send it, is refused.
638    #[test]
639    fn a_summary_without_builtin_is_refused() {
640        let json = serde_json::json!({
641            "id": "x", "name": "Heists",
642            "kinds": { "movies": false, "episodes": true, "tracks": false },
643            "owner_kind": "mine", "visibility": { "type": "personal" },
644            "can_edit": true, "can_manage": true, "revision": 1, "pinned": null,
645        });
646        let error = serde_json::from_value::<PlaylistSummary>(json).unwrap_err();
647        assert!(
648            error.to_string().contains("missing field `builtin`"),
649            "{error}"
650        );
651    }
652
653    /// A share without its name and kind keys is refused; a request's
654    /// share, which names neither, sends both as `null`.
655    #[test]
656    fn a_share_names_its_name_and_kind_or_null() {
657        assert!(
658            serde_json::from_str::<PlaylistShare>(r#"{"user_id":"local:x","can_edit":true}"#)
659                .is_err()
660        );
661        let sent = serde_json::to_value(PlaylistShare::new("local:x", false)).unwrap();
662        assert!(sent["display_name"].is_null(), "{sent}");
663        assert!(sent["kind"].is_null(), "{sent}");
664        assert_eq!(
665            serde_json::from_value::<PlaylistShare>(sent).unwrap(),
666            PlaylistShare::new("local:x", false)
667        );
668        let kind: UserKind = serde_json::from_str(r#""federated""#).unwrap();
669        assert_eq!(kind, UserKind::Unknown);
670    }
671
672    #[test]
673    fn an_edit_of_a_newer_build_reads_as_unknown() {
674        let edit: PlaylistEdit = serde_json::from_str(r#"{"type":"shuffle_all"}"#).unwrap();
675        assert_eq!(edit, PlaylistEdit::Unknown);
676    }
677}