Skip to main content

mostro_core/
rating.rs

1//! Encoding of user reputation as Nostr event tags.
2//!
3//! Mostro publishes user reputation as addressable Nostr events of kind
4//! [`NOSTR_RATING_EVENT_KIND`](crate::prelude::NOSTR_RATING_EVENT_KIND). The
5//! [`Rating`] struct in this module mirrors the tag set used on those events
6//! and provides helpers to serialize to / deserialize from both JSON and
7//! `nostr_sdk::Tags`.
8
9use nostr_sdk::prelude::*;
10use serde::{Deserialize, Serialize};
11
12use crate::error::ServiceError;
13
14/// User reputation snapshot, suitable for publishing as Nostr tags.
15///
16/// The fields are the same aggregates stored on [`crate::user::User`], but
17/// typed for transport (unsigned integers for counts, `u8` for rating values).
18#[derive(Debug, Deserialize, Serialize, Clone)]
19pub struct Rating {
20    /// Total number of ratings received.
21    pub total_reviews: u64,
22    /// Weighted rating average across all reviews.
23    pub total_rating: f64,
24    /// Most recent rating, in the `MIN_RATING..=MAX_RATING` range.
25    pub last_rating: u8,
26    /// Highest rating ever received.
27    pub max_rate: u8,
28    /// Lowest rating ever received.
29    pub min_rate: u8,
30}
31
32impl Rating {
33    /// Construct a new [`Rating`] from its individual components.
34    pub fn new(
35        total_reviews: u64,
36        total_rating: f64,
37        last_rating: u8,
38        min_rate: u8,
39        max_rate: u8,
40    ) -> Self {
41        Self {
42            total_reviews,
43            total_rating,
44            last_rating,
45            min_rate,
46            max_rate,
47        }
48    }
49
50    /// Parse a [`Rating`] from its JSON representation.
51    ///
52    /// Returns [`ServiceError::MessageSerializationError`] if `json` is not a
53    /// valid serialization of this type.
54    pub fn from_json(json: &str) -> Result<Self, ServiceError> {
55        serde_json::from_str(json).map_err(|_| ServiceError::MessageSerializationError)
56    }
57
58    /// Serialize the rating to a JSON string.
59    pub fn as_json(&self) -> Result<String, ServiceError> {
60        serde_json::to_string(&self).map_err(|_| ServiceError::MessageSerializationError)
61    }
62
63    /// Encode the rating as a set of Nostr tags, ready to attach to an event.
64    ///
65    /// Returns a [`Tags`] value with one entry per numeric field plus a `z`
66    /// marker tag identifying the payload as a rating. Encoding is infallible
67    /// (nostr 0.45 `Tag::custom` takes string kind keys directly).
68    pub fn to_tags(&self) -> Tags {
69        let tags = vec![
70            Tag::custom("total_reviews", vec![self.total_reviews.to_string()]),
71            Tag::custom("total_rating", vec![self.total_rating.to_string()]),
72            Tag::custom("last_rating", vec![self.last_rating.to_string()]),
73            Tag::custom("max_rate", vec![self.max_rate.to_string()]),
74            Tag::custom("min_rate", vec![self.min_rate.to_string()]),
75            Tag::custom("z", vec!["rating".to_string()]),
76        ];
77
78        Tags::from_list(tags)
79    }
80
81    /// Rebuild a [`Rating`] from a set of Nostr tags previously produced by
82    /// [`Rating::to_tags`].
83    ///
84    /// Unknown tag keys are ignored so that the function keeps working if the
85    /// server adds new metadata fields. Returns a [`ServiceError`] if a
86    /// required key carries a non-parseable value.
87    pub fn from_tags(tags: Tags) -> Result<Self, ServiceError> {
88        let mut total_reviews = 0;
89        let mut total_rating = 0.0;
90        let mut last_rating = 0;
91        let mut max_rate = 0;
92        let mut min_rate = 0;
93
94        for tag in tags.into_iter() {
95            let t = tag.to_vec();
96            let key = t
97                .first()
98                .ok_or_else(|| ServiceError::NostrError("Missing tag key".to_string()))?;
99            let value = t
100                .get(1)
101                .ok_or_else(|| ServiceError::NostrError("Missing tag value".to_string()))?;
102            match key.as_str() {
103                "total_reviews" => {
104                    total_reviews = value
105                        .parse::<u64>()
106                        .map_err(|_| ServiceError::ParsingNumberError)?
107                }
108                "total_rating" => {
109                    total_rating = value
110                        .parse::<f64>()
111                        .map_err(|_| ServiceError::ParsingNumberError)?
112                }
113                "last_rating" => {
114                    last_rating = value
115                        .parse::<u8>()
116                        .map_err(|_| ServiceError::ParsingNumberError)?
117                }
118                "max_rate" => {
119                    max_rate = value
120                        .parse::<u8>()
121                        .map_err(|_| ServiceError::ParsingNumberError)?
122                }
123                "min_rate" => {
124                    min_rate = value
125                        .parse::<u8>()
126                        .map_err(|_| ServiceError::ParsingNumberError)?
127                }
128                _ => {}
129            }
130        }
131
132        Ok(Self {
133            total_reviews,
134            total_rating,
135            last_rating,
136            max_rate,
137            min_rate,
138        })
139    }
140}