Skip to main content

spoolframe_types/
rating.rs

1//! Whose a rating is: Rotten Tomatoes' Tomatometer, IMDb's, TMDB's
2//! ([`RatingSource`], feature `spoolframe:rating-sources`), read from the
3//! catalog's rating image (Plex's `ratingImage` and `audienceRatingImage`,
4//! such as `rottentomatoes://image.rating.ripe`).
5
6use serde::{Deserialize, Serialize};
7
8/// Whose a rating is, and how it reads: its provider, Rotten Tomatoes'
9/// verdict where it has one, and the catalog's own name for its image.
10#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
12pub struct RatingSource {
13    pub provider: RatingProvider,
14    /// Rotten Tomatoes' verdict: fresh or rotten for critics, upright or
15    /// spilled for the audience. `None` for a provider with none.
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
18    pub state: Option<RatingState>,
19    /// The catalog's name for its image, as it gave it
20    /// (`rottentomatoes://image.rating.ripe`): for an app to tell a
21    /// provider or verdict this build does not know.
22    pub image: String,
23}
24
25/// The names of `MergeFacts`' rating source fields on the wire: what a
26/// server leaves out of a reply to a connection without
27/// `spoolframe:rating-sources`.
28pub const RATING_SOURCE_FIELDS: [&str; 2] = ["rating_source", "audience_rating_source"];
29
30/// Who rated it.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
32#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
33#[serde(rename_all = "snake_case")]
34pub enum RatingProvider {
35    RottenTomatoes,
36    Imdb,
37    Tmdb,
38    /// One this build does not know: its `image` says which.
39    #[serde(other)]
40    Unknown,
41}
42
43/// Rotten Tomatoes' verdict.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
45#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
46#[serde(rename_all = "snake_case")]
47pub enum RatingState {
48    /// The critics' Tomatometer is 60% or more (Plex's `ripe`).
49    Fresh,
50    /// Certified Fresh (Plex's `certified`).
51    CertifiedFresh,
52    /// The critics' Tomatometer is under 60%.
53    Rotten,
54    /// The audience score is 60% or more (the full popcorn bucket).
55    Upright,
56    /// The audience score is under 60% (the tipped bucket).
57    Spilled,
58    /// One this build does not know: the source's `image` says which.
59    #[serde(other)]
60    Unknown,
61}
62
63/// How a provider's rating reads.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
65#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
66pub enum RatingScale {
67    /// A percentage: Rotten Tomatoes'.
68    Percent,
69    /// Out of 10, to one place: IMDb's, TMDB's, and any not known.
70    OutOf10,
71}
72
73impl RatingSource {
74    /// The source an image name says (Plex's `ratingImage` or
75    /// `audienceRatingImage`): `None` for an empty one. A provider or
76    /// verdict this build does not know is `Unknown`, and `image` keeps
77    /// the name as it was.
78    pub fn from_image(image: &str) -> Option<Self> {
79        let image = image.trim();
80        if image.is_empty() {
81            return None;
82        }
83        let (scheme, rest) = image.split_once("://").unwrap_or((image, ""));
84        let provider = match scheme {
85            "rottentomatoes" => RatingProvider::RottenTomatoes,
86            "imdb" => RatingProvider::Imdb,
87            "themoviedb" | "tmdb" => RatingProvider::Tmdb,
88            _ => RatingProvider::Unknown,
89        };
90        let state = (provider == RatingProvider::RottenTomatoes).then(|| {
91            match rest.strip_prefix("image.rating.").unwrap_or_default() {
92                "ripe" => RatingState::Fresh,
93                "certified" => RatingState::CertifiedFresh,
94                "rotten" => RatingState::Rotten,
95                "upright" => RatingState::Upright,
96                "spilled" => RatingState::Spilled,
97                _ => RatingState::Unknown,
98            }
99        });
100        Some(Self {
101            provider,
102            state,
103            image: image.to_owned(),
104        })
105    }
106
107    /// How its ratings read.
108    pub fn scale(&self) -> RatingScale {
109        match self.provider {
110            RatingProvider::RottenTomatoes => RatingScale::Percent,
111            RatingProvider::Imdb | RatingProvider::Tmdb | RatingProvider::Unknown => {
112                RatingScale::OutOf10
113            }
114        }
115    }
116
117    /// A rating of `tenths` (0 to 100, as `MergeFacts` has them) as this
118    /// provider shows it: `"92%"` for Rotten Tomatoes' 9.2, `"7.9"` for
119    /// IMDb's.
120    pub fn display(&self, tenths: u16) -> String {
121        match self.scale() {
122            RatingScale::Percent => format!("{tenths}%"),
123            RatingScale::OutOf10 => format!("{}.{}", tenths / 10, tenths % 10),
124        }
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    fn read(image: &str) -> (RatingProvider, Option<RatingState>) {
133        let source = RatingSource::from_image(image).unwrap();
134        assert_eq!(source.image, image);
135        (source.provider, source.state)
136    }
137
138    #[test]
139    fn each_known_plex_image_is_read() {
140        use RatingProvider::*;
141        use RatingState::*;
142        let cases = [
143            (
144                "rottentomatoes://image.rating.ripe",
145                (RottenTomatoes, Some(Fresh)),
146            ),
147            (
148                "rottentomatoes://image.rating.certified",
149                (RottenTomatoes, Some(CertifiedFresh)),
150            ),
151            (
152                "rottentomatoes://image.rating.rotten",
153                (RottenTomatoes, Some(Rotten)),
154            ),
155            (
156                "rottentomatoes://image.rating.upright",
157                (RottenTomatoes, Some(Upright)),
158            ),
159            (
160                "rottentomatoes://image.rating.spilled",
161                (RottenTomatoes, Some(Spilled)),
162            ),
163            ("imdb://image.rating", (Imdb, None)),
164            ("themoviedb://image.rating", (Tmdb, None)),
165        ];
166        for (image, expected) in cases {
167            assert_eq!(read(image), expected, "{image}");
168        }
169    }
170
171    #[test]
172    fn an_unknown_image_keeps_its_name() {
173        assert_eq!(
174            read("metacritic://image.rating"),
175            (RatingProvider::Unknown, None)
176        );
177        assert_eq!(
178            read("rottentomatoes://image.rating.verified"),
179            (RatingProvider::RottenTomatoes, Some(RatingState::Unknown))
180        );
181        assert_eq!(RatingSource::from_image(""), None);
182    }
183
184    #[test]
185    fn rotten_tomatoes_shows_a_percentage_and_the_rest_out_of_ten() {
186        let rt = RatingSource::from_image("rottentomatoes://image.rating.ripe").unwrap();
187        let imdb = RatingSource::from_image("imdb://image.rating").unwrap();
188        assert_eq!(
189            (rt.display(92), imdb.display(79), imdb.display(100)),
190            ("92%".to_owned(), "7.9".to_owned(), "10.0".to_owned())
191        );
192    }
193
194    /// The names a server strips are the fields' own.
195    #[test]
196    fn the_stripped_names_are_merge_facts_fields() {
197        let source = RatingSource::from_image("imdb://image.rating");
198        let facts = crate::MergeFacts {
199            rating_source: source.clone(),
200            audience_rating_source: source,
201            ..Default::default()
202        };
203        let json = serde_json::to_value(&facts).unwrap();
204        for name in RATING_SOURCE_FIELDS {
205            assert!(json.get(name).is_some(), "{name}");
206        }
207    }
208
209    #[test]
210    fn the_wire_names_are_fixed() {
211        let source = RatingSource::from_image("rottentomatoes://image.rating.certified").unwrap();
212        assert_eq!(
213            serde_json::to_value(&source).unwrap(),
214            serde_json::json!({
215                "provider": "rotten_tomatoes",
216                "state": "certified_fresh",
217                "image": "rottentomatoes://image.rating.certified"
218            })
219        );
220        let newer: RatingSource = serde_json::from_value(serde_json::json!({
221            "provider": "letterboxd",
222            "state": "glowing",
223            "image": "letterboxd://image.rating"
224        }))
225        .unwrap();
226        assert_eq!(
227            (newer.provider, newer.state),
228            (RatingProvider::Unknown, Some(RatingState::Unknown))
229        );
230    }
231}