Skip to main content

spoolframe_types/
id.rs

1//! Identifiers. On the wire each one is a namespaced string, for example
2//! `plex:movie:12345`.
3//!
4//! Clients treat them as opaque: they compare them and send them back, and
5//! never take them apart. The namespace is part of the ID so that `native:`
6//! IDs (and, with federation, IDs from another server) can be added without
7//! a format change. Only the server reads the parts, through the accessors.
8//!
9//! A paired server's item (P8-02) is in [`Namespace::Federated`]: its key
10//! is the origin's server id, then the id the origin knows it by without
11//! the kind, which the federated id carries already
12//! (`fed:movie:mzxw6ytbojtg633c:plex:12`). The origin is the server id,
13//! not its endpoint key, so a rotated key keeps every id.
14
15use std::fmt;
16use std::str::FromStr;
17
18use serde::{Deserialize, Serialize};
19
20/// Why a string is not a valid identifier.
21#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
22pub enum IdError {
23    #[error("{0:?} is not a known ID namespace")]
24    UnknownNamespace(String),
25    #[error("{0:?} is not a known media kind")]
26    UnknownKind(String),
27    #[error("{0:?} has no key")]
28    MissingKey(String),
29    /// A federated id's origin is empty or has a `:` in it.
30    #[error("{0:?} is not a server id to name an origin by")]
31    InvalidOrigin(String),
32}
33
34/// Which catalog an ID belongs to.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36#[non_exhaustive]
37pub enum Namespace {
38    /// An item in the Plex library; the key is its Plex `ratingKey`.
39    Plex,
40    /// Something the server made itself rather than a catalog: a sheet of
41    /// frame previews (P3-13), an [`ArtworkId`] like `preview:<set>/<n>`.
42    Preview,
43    /// An image the server keeps or draws itself (PX-53): a playlist's
44    /// uploaded cover (`image:playlist/<hash>`), its mosaic, a built-in
45    /// playlist's tile. Only ever an [`ArtworkId`].
46    Image,
47    /// A paired server's (P8-02), as this server caches it: the key is the
48    /// origin's server id and the id the origin knows it by
49    /// (`fed:movie:<origin>:plex:12`, `fed:<origin>:plex:2`).
50    Federated,
51}
52
53impl Namespace {
54    fn as_str(self) -> &'static str {
55        match self {
56            Namespace::Plex => "plex",
57            Namespace::Preview => "preview",
58            Namespace::Image => "image",
59            Namespace::Federated => "fed",
60        }
61    }
62}
63
64/// `origin` checked as a federated id's: not empty, and no `:` in it.
65fn origin(origin: &str) -> Result<&str, IdError> {
66    if origin.is_empty() || origin.contains(':') {
67        return Err(IdError::InvalidOrigin(origin.to_owned()));
68    }
69    Ok(origin)
70}
71
72/// A federated key's origin and the rest, if it is one.
73fn split_origin(key: &str) -> Option<(&str, &str)> {
74    key.split_once(':')
75        .filter(|(origin, rest)| !origin.is_empty() && !rest.is_empty())
76}
77
78impl FromStr for Namespace {
79    type Err = IdError;
80
81    fn from_str(s: &str) -> Result<Self, IdError> {
82        match s {
83            "plex" => Ok(Namespace::Plex),
84            "preview" => Ok(Namespace::Preview),
85            "image" => Ok(Namespace::Image),
86            "fed" => Ok(Namespace::Federated),
87            other => Err(IdError::UnknownNamespace(other.to_owned())),
88        }
89    }
90}
91
92/// What kind of item a [`MediaId`] names.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub enum MediaKind {
95    Movie,
96    Show,
97    Season,
98    Episode,
99    Artist,
100    Album,
101    Track,
102}
103
104impl MediaKind {
105    /// Its name in an id (`movie` in `plex:movie:12`).
106    pub fn as_str(self) -> &'static str {
107        match self {
108            MediaKind::Movie => "movie",
109            MediaKind::Show => "show",
110            MediaKind::Season => "season",
111            MediaKind::Episode => "episode",
112            MediaKind::Artist => "artist",
113            MediaKind::Album => "album",
114            MediaKind::Track => "track",
115        }
116    }
117
118    /// Whether an item of this kind plays: a movie, an episode or a
119    /// track, never a show, a season, an artist or an album.
120    pub fn plays(self) -> bool {
121        matches!(
122            self,
123            MediaKind::Movie | MediaKind::Episode | MediaKind::Track
124        )
125    }
126}
127
128impl FromStr for MediaKind {
129    type Err = IdError;
130
131    fn from_str(s: &str) -> Result<Self, IdError> {
132        Ok(match s {
133            "movie" => MediaKind::Movie,
134            "show" => MediaKind::Show,
135            "season" => MediaKind::Season,
136            "episode" => MediaKind::Episode,
137            "artist" => MediaKind::Artist,
138            "album" => MediaKind::Album,
139            "track" => MediaKind::Track,
140            other => return Err(IdError::UnknownKind(other.to_owned())),
141        })
142    }
143}
144
145/// A key must be non-empty; it may contain `:` (only the leading parts are
146/// split off).
147fn key(whole: &str, key: Option<&str>) -> Result<String, IdError> {
148    match key {
149        Some(k) if !k.is_empty() => Ok(k.to_owned()),
150        _ => Err(IdError::MissingKey(whole.to_owned())),
151    }
152}
153
154/// A movie, show, season, episode, artist, album or track:
155/// `<namespace>:<kind>:<key>`.
156#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
157#[serde(try_from = "String", into = "String")]
158pub struct MediaId {
159    namespace: Namespace,
160    kind: MediaKind,
161    key: String,
162}
163
164impl MediaId {
165    /// Build an ID. The server does this; clients only receive them.
166    pub fn new(
167        namespace: Namespace,
168        kind: MediaKind,
169        key: impl Into<String>,
170    ) -> Result<Self, IdError> {
171        let key = key.into();
172        if key.is_empty() {
173            return Err(IdError::MissingKey(format!(
174                "{}:{}:",
175                namespace.as_str(),
176                kind.as_str()
177            )));
178        }
179        Ok(Self {
180            namespace,
181            kind,
182            key,
183        })
184    }
185
186    /// For the server: which catalog resolves this ID.
187    pub fn namespace(&self) -> Namespace {
188        self.namespace
189    }
190
191    /// For the server: what kind of item this is.
192    pub fn kind(&self) -> MediaKind {
193        self.kind
194    }
195
196    /// For the server: the catalog's own key for the item.
197    pub fn key(&self) -> &str {
198        &self.key
199    }
200
201    /// `remote`, an item of the server whose server id is `origin`, as
202    /// this server names it (P8-02): `fed:<kind>:<origin>:<namespace>:<key>`.
203    pub fn federated(origin_id: &str, remote: &MediaId) -> Result<Self, IdError> {
204        let key = format!(
205            "{}:{}:{}",
206            origin(origin_id)?,
207            remote.namespace.as_str(),
208            remote.key
209        );
210        Self::new(Namespace::Federated, remote.kind, key)
211    }
212
213    /// For a federated id: the origin's server id, and the id the origin
214    /// knows the item by. `None` for any other id, or one that does not
215    /// read as one.
216    pub fn remote(&self) -> Option<(&str, MediaId)> {
217        if self.namespace != Namespace::Federated {
218            return None;
219        }
220        let (origin, rest) = split_origin(&self.key)?;
221        let (namespace, key) = rest.split_once(':')?;
222        Some((
223            origin,
224            Self::new(namespace.parse().ok()?, self.kind, key).ok()?,
225        ))
226    }
227
228    /// The server id of the paired server a federated id's item is on;
229    /// `None` for this server's own, as [`MediaId::remote`] reads it.
230    pub fn origin(&self) -> Option<&str> {
231        self.remote().map(|(origin, _)| origin)
232    }
233}
234
235impl fmt::Display for MediaId {
236    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237        write!(
238            f,
239            "{}:{}:{}",
240            self.namespace.as_str(),
241            self.kind.as_str(),
242            self.key
243        )
244    }
245}
246
247impl FromStr for MediaId {
248    type Err = IdError;
249
250    fn from_str(s: &str) -> Result<Self, IdError> {
251        let mut parts = s.splitn(3, ':');
252        let namespace = parts.next().unwrap_or_default().parse()?;
253        let kind = parts.next().unwrap_or_default().parse()?;
254        let key = key(s, parts.next())?;
255        Ok(Self {
256            namespace,
257            kind,
258            key,
259        })
260    }
261}
262
263/// Defines an ID made of a namespace and a key: `<namespace>:<key>`.
264macro_rules! namespaced_id {
265    ($(#[$doc:meta])* $name:ident) => {
266        $(#[$doc])*
267        #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
268        #[serde(try_from = "String", into = "String")]
269        pub struct $name {
270            namespace: Namespace,
271            key: String,
272        }
273
274        impl $name {
275            /// Build an ID. The server does this; clients only receive them.
276            pub fn new(namespace: Namespace, key: impl Into<String>) -> Result<Self, IdError> {
277                let key = key.into();
278                if key.is_empty() {
279                    return Err(IdError::MissingKey(format!("{}:", namespace.as_str())));
280                }
281                Ok(Self { namespace, key })
282            }
283
284            /// For the server: which catalog resolves this ID.
285            pub fn namespace(&self) -> Namespace {
286                self.namespace
287            }
288
289            /// For the server: the catalog's own key.
290            pub fn key(&self) -> &str {
291                &self.key
292            }
293
294            /// `remote`, of the server whose server id is `origin`, as
295            /// this server names it (P8-02): `fed:<origin>:<remote>`.
296            pub fn federated(origin_id: &str, remote: &$name) -> Result<Self, IdError> {
297                Self::new(
298                    Namespace::Federated,
299                    format!("{}:{remote}", origin(origin_id)?),
300                )
301            }
302
303            /// For a federated id: the origin's server id, and the id the
304            /// origin knows it by. `None` for any other id, or one that
305            /// does not read as one.
306            pub fn remote(&self) -> Option<(&str, $name)> {
307                if self.namespace != Namespace::Federated {
308                    return None;
309                }
310                let (origin, rest) = split_origin(&self.key)?;
311                Some((origin, rest.parse().ok()?))
312            }
313        }
314
315        impl fmt::Display for $name {
316            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317                write!(f, "{}:{}", self.namespace.as_str(), self.key)
318            }
319        }
320
321        impl FromStr for $name {
322            type Err = IdError;
323
324            fn from_str(s: &str) -> Result<Self, IdError> {
325                let mut parts = s.splitn(2, ':');
326                let namespace = parts.next().unwrap_or_default().parse()?;
327                let key = key(s, parts.next())?;
328                Ok(Self { namespace, key })
329            }
330        }
331
332        impl TryFrom<String> for $name {
333            type Error = IdError;
334
335            fn try_from(s: String) -> Result<Self, IdError> {
336                s.parse()
337            }
338        }
339
340        impl From<$name> for String {
341            fn from(id: $name) -> String {
342                id.to_string()
343            }
344        }
345    };
346}
347
348namespaced_id!(
349    /// A library (a Plex library section today): `<namespace>:<key>`.
350    LibraryId
351);
352
353namespaced_id!(
354    /// A piece of artwork, fetched through the client protocol, never from
355    /// Plex directly: `<namespace>:<key>`.
356    ArtworkId
357);
358
359namespaced_id!(
360    /// A person a search found (P3-09), whose items can be listed:
361    /// `<namespace>:<key>`.
362    PersonId
363);
364
365impl TryFrom<String> for MediaId {
366    type Error = IdError;
367
368    fn try_from(s: String) -> Result<Self, IdError> {
369        s.parse()
370    }
371}
372
373impl From<MediaId> for String {
374    fn from(id: MediaId) -> String {
375        id.to_string()
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    #[test]
384    fn a_media_id_prints_as_namespace_kind_key() {
385        let id = MediaId::new(Namespace::Plex, MediaKind::Movie, "12345").unwrap();
386        assert_eq!(id.to_string(), "plex:movie:12345");
387    }
388
389    #[test]
390    fn a_media_id_survives_a_round_trip_through_its_string() {
391        let id: MediaId = "plex:episode:98321".parse().unwrap();
392        assert_eq!(id.to_string().parse::<MediaId>().unwrap(), id);
393    }
394
395    #[test]
396    fn a_media_id_on_the_wire_is_a_plain_string() {
397        let id = MediaId::new(Namespace::Plex, MediaKind::Track, "7").unwrap();
398        assert_eq!(serde_json::to_string(&id).unwrap(), r#""plex:track:7""#);
399    }
400
401    #[test]
402    fn a_key_may_contain_colons() {
403        let id: MediaId = "plex:movie:a:b".parse().unwrap();
404        assert_eq!(id.key(), "a:b");
405    }
406
407    #[test]
408    fn an_unknown_namespace_is_rejected() {
409        assert_eq!(
410            "nope:movie:1".parse::<MediaId>(),
411            Err(IdError::UnknownNamespace("nope".into()))
412        );
413    }
414
415    #[test]
416    fn an_unknown_kind_is_rejected() {
417        assert_eq!(
418            "plex:photo:1".parse::<MediaId>(),
419            Err(IdError::UnknownKind("photo".into()))
420        );
421    }
422
423    #[test]
424    fn an_empty_key_is_rejected() {
425        assert_eq!(
426            "plex:movie:".parse::<MediaId>(),
427            Err(IdError::MissingKey("plex:movie:".into()))
428        );
429        assert!(MediaId::new(Namespace::Plex, MediaKind::Movie, "").is_err());
430    }
431
432    #[test]
433    fn a_missing_key_is_rejected() {
434        assert!("plex:movie".parse::<MediaId>().is_err());
435    }
436
437    #[test]
438    fn deserializing_a_bad_media_id_fails() {
439        assert!(serde_json::from_str::<MediaId>(r#""nope:movie:1""#).is_err());
440    }
441
442    #[test]
443    fn a_library_id_round_trips_through_its_string() {
444        let id = LibraryId::new(Namespace::Plex, "3").unwrap();
445        assert_eq!(id.to_string(), "plex:3");
446        assert_eq!("plex:3".parse::<LibraryId>().unwrap(), id);
447    }
448
449    #[test]
450    fn an_artwork_id_keeps_a_path_like_key() {
451        let id: ArtworkId = "plex:/library/metadata/123/thumb/1699".parse().unwrap();
452        assert_eq!(id.key(), "/library/metadata/123/thumb/1699");
453    }
454
455    #[test]
456    fn a_preview_sheet_s_id_is_in_a_namespace_of_its_own() {
457        let id: ArtworkId = "preview:0f3a/2".parse().unwrap();
458        assert_eq!(id.namespace(), Namespace::Preview);
459        assert_eq!(id.key(), "0f3a/2");
460        assert_eq!(id.to_string(), "preview:0f3a/2");
461    }
462
463    #[test]
464    fn a_stored_image_s_id_is_in_a_namespace_of_its_own() {
465        let id: ArtworkId = "image:playlist/0f3a".parse().unwrap();
466        assert_eq!(id.namespace(), Namespace::Image);
467        assert_eq!(id.key(), "playlist/0f3a");
468        assert_eq!(id.to_string(), "image:playlist/0f3a");
469    }
470
471    const ORIGIN: &str = "mzxw6ytbojtg633c";
472
473    /// P8-02: a paired server's item names its origin and the origin's
474    /// id, reads back with the parser every id reads with, and says what
475    /// it is of.
476    #[test]
477    fn a_federated_id_round_trips_and_names_its_origin() {
478        let remote: MediaId = "plex:episode:cabin:12".parse().unwrap();
479        let id = MediaId::federated(ORIGIN, &remote).unwrap();
480        assert_eq!(id.to_string(), "fed:episode:mzxw6ytbojtg633c:plex:cabin:12");
481        assert_eq!(id.namespace(), Namespace::Federated);
482        assert_eq!(id.kind(), MediaKind::Episode);
483        let read: MediaId = id.to_string().parse().unwrap();
484        assert_eq!(read, id);
485        assert_eq!(read.remote(), Some((ORIGIN, remote)));
486        assert_eq!(
487            serde_json::from_str::<MediaId>(&serde_json::to_string(&id).unwrap()).unwrap(),
488            id
489        );
490
491        let library = LibraryId::federated(ORIGIN, &"plex:2".parse().unwrap()).unwrap();
492        assert_eq!(library.to_string(), "fed:mzxw6ytbojtg633c:plex:2");
493        assert_eq!(
494            library.to_string().parse::<LibraryId>().unwrap().remote(),
495            Some((ORIGIN, "plex:2".parse().unwrap()))
496        );
497        let art: ArtworkId = "plex:/library/metadata/1/thumb/2".parse().unwrap();
498        let ours = ArtworkId::federated(ORIGIN, &art).unwrap();
499        assert_eq!(
500            ours.to_string(),
501            "fed:mzxw6ytbojtg633c:plex:/library/metadata/1/thumb/2"
502        );
503        assert_eq!(ours.remote(), Some((ORIGIN, art)));
504    }
505
506    /// The namespaces there were read and print as they did, and are not
507    /// federated.
508    #[test]
509    fn the_namespaces_there_were_are_unchanged() {
510        for text in [
511            "plex:movie:12345",
512            "plex:episode:cabin:12",
513            "plex:movie:a:b",
514        ] {
515            let id: MediaId = text.parse().unwrap();
516            assert_eq!(id.to_string(), text);
517            assert_eq!(id.remote(), None);
518        }
519        for text in ["plex:3", "preview:0f3a/2", "image:playlist/0f3a"] {
520            let id: ArtworkId = text.parse().unwrap();
521            assert_eq!(id.to_string(), text);
522            assert_eq!(id.remote(), None);
523        }
524    }
525
526    #[test]
527    fn a_federated_id_needs_an_origin_and_an_id_the_origin_reads() {
528        let remote: MediaId = "plex:movie:1".parse().unwrap();
529        assert_eq!(
530            MediaId::federated("", &remote),
531            Err(IdError::InvalidOrigin(String::new()))
532        );
533        assert!(MediaId::federated("a:b", &remote).is_err());
534        // Read, but not as anything an origin has.
535        for text in [
536            "fed:movie:mzxw",
537            "fed:movie:mzxw:nope:1",
538            "fed:movie::plex:1",
539        ] {
540            let id: MediaId = text.parse().unwrap();
541            assert_eq!(id.remote(), None, "{text}");
542        }
543    }
544
545    #[test]
546    fn an_artwork_id_without_a_key_is_rejected() {
547        assert!("plex:".parse::<ArtworkId>().is_err());
548        assert!("plex".parse::<ArtworkId>().is_err());
549    }
550}