//! Typed shapes of everything the services send back. //! //! The models follow three rules (see `AGENTS.md`): //! //! * A field the UI cannot work without is required, and its absence or a //! malformed value is a decode error. //! * Fields that are genuinely optional in the wild are `Option` or default to //! empty. //! * Server enums are open: values this client has not seen yet land in an //! `Other(String)` variant instead of failing the whole response. //! //! Everything also serializes (back to the server's spelling), so callers can //! cache responses and tests can round-trip them. /// Declares an open server enum: known wire values map to variants, anything /// else is preserved in `Other(String)` and serializes back verbatim. macro_rules! open_enum { ( $(#[$meta:meta])* pub enum $name:ident { $( $(#[$vmeta:meta])* $variant:ident => $wire:literal, )+ } ) => { $(#[$meta])* #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum $name { $( $(#[$vmeta])* $variant, )+ /// A value this client does not know, preserved verbatim. Other(String), } impl $name { /// The server's spelling. #[must_use] pub fn as_str(&self) -> &str { match self { $( Self::$variant => $wire, )+ Self::Other(other) => other, } } } impl From<&str> for $name { fn from(raw: &str) -> Self { match raw { $( $wire => Self::$variant, )+ other => Self::Other(other.to_owned()), } } } impl ::std::fmt::Display for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { f.write_str(self.as_str()) } } impl ::serde::Serialize for $name { fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(self.as_str()) } } impl<'de> ::serde::Deserialize<'de> for $name { fn deserialize>(deserializer: D) -> Result { let raw = <::std::borrow::Cow<'de, str>>::deserialize(deserializer)?; Ok(Self::from(raw.as_ref())) } } }; } mod account; mod catalog; mod format; mod tags; pub use account::{ Card, CardLibrary, CloneCode, Counts, Hold, LendingPeriod, Loan, Period, SyncState, }; pub use catalog::{ Availability, AvailabilityType, Color, Cover, Covers, Creator, FacetGroup, FacetItem, Facets, Library, LibraryAvailability, LibraryFormat, LibraryMatch, LibraryPage, Link, LocateBranch, LocateResponse, LocateSystem, Media, Named, PageLink, PageLinks, Publisher, SearchPage, Series, SortBy, SortOption, TitleAvailability, }; pub use format::{DownloadKind, Format, FormatAccess, Identifier}; pub use tags::{Tag, TagDetail, TagSummary, Tagging}; open_enum! { /// What kind of title something is (`type.id` on the wire). pub enum MediaKind { /// An ebook. Ebook => "ebook", /// An audiobook. Audiobook => "audiobook", /// A magazine issue. Magazine => "magazine", } } impl MediaKind { /// The key for this kind in a card's `lendingPeriods`. Sentry spells the /// ebook key `book`. #[must_use] pub fn lending_period_key(&self) -> &str { match self { Self::Ebook => "book", other => other.as_str(), } } } /// `#[serde(with = "kind_object")]`: the wire carries the kind as an object, /// `{"id": "audiobook", "name": "Audiobook"}`; only the id is meaningful. pub(crate) mod kind_object { use serde::{Deserialize, Deserializer, Serialize, Serializer}; use super::MediaKind; #[derive(Deserialize)] struct Wire { id: MediaKind, } #[derive(Serialize)] struct WireRef<'a> { id: &'a MediaKind, } pub(crate) fn deserialize<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result { Wire::deserialize(deserializer).map(|wire| wire.id) } pub(crate) fn serialize( value: &MediaKind, serializer: S, ) -> Result { WireRef { id: value }.serialize(serializer) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn open_enums_preserve_unknown_values() { let known: MediaKind = serde_json::from_str("\"audiobook\"").unwrap(); assert_eq!(known, MediaKind::Audiobook); let unknown: MediaKind = serde_json::from_str("\"video\"").unwrap(); assert_eq!(unknown, MediaKind::Other("video".into())); assert_eq!(serde_json::to_string(&unknown).unwrap(), "\"video\""); assert_eq!(MediaKind::Ebook.lending_period_key(), "book"); assert_eq!(MediaKind::Magazine.lending_period_key(), "magazine"); } }