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