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