1use anyhow::{Ok, Result};
2use nostr_sdk::prelude::*;
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Deserialize, Serialize, Clone)]
7pub struct Rating {
8 pub total_reviews: u64,
9 pub total_rating: f64,
10 pub last_rating: u8,
11 pub max_rate: u8,
12 pub min_rate: u8,
13}
14
15impl Rating {
16 pub fn new(
17 total_reviews: u64,
18 total_rating: f64,
19 last_rating: u8,
20 min_rate: u8,
21 max_rate: u8,
22 ) -> Self {
23 Self {
24 total_reviews,
25 total_rating,
26 last_rating,
27 min_rate,
28 max_rate,
29 }
30 }
31
32 pub fn from_json(json: &str) -> Result<Self> {
34 Ok(serde_json::from_str(json)?)
35 }
36
37 pub fn as_json(&self) -> Result<String> {
39 Ok(serde_json::to_string(&self)?)
40 }
41
42 pub fn to_tags(&self) -> Result<Tags> {
44 let tags = vec![
45 Tag::custom(
46 TagKind::Custom(std::borrow::Cow::Borrowed("total_reviews")),
47 vec![self.total_reviews.to_string()],
48 ),
49 Tag::custom(
50 TagKind::Custom(std::borrow::Cow::Borrowed("total_rating")),
51 vec![self.total_rating.to_string()],
52 ),
53 Tag::custom(
54 TagKind::Custom(std::borrow::Cow::Borrowed("last_rating")),
55 vec![self.last_rating.to_string()],
56 ),
57 Tag::custom(
58 TagKind::Custom(std::borrow::Cow::Borrowed("max_rate")),
59 vec![self.max_rate.to_string()],
60 ),
61 Tag::custom(
62 TagKind::Custom(std::borrow::Cow::Borrowed("min_rate")),
63 vec![self.min_rate.to_string()],
64 ),
65 Tag::custom(
66 TagKind::Custom(std::borrow::Cow::Borrowed("z")),
67 vec!["rating".to_string()],
68 ),
69 ];
70
71 Ok(Tags::new(tags))
72 }
73
74 pub fn from_tags(tags: Tags) -> Result<Self> {
76 let mut total_reviews = 0;
77 let mut total_rating = 0.0;
78 let mut last_rating = 0;
79 let mut max_rate = 0;
80 let mut min_rate = 0;
81
82 for tag in tags.into_iter() {
83 let t = tag.to_vec();
84 let key = t
85 .first()
86 .ok_or_else(|| anyhow::anyhow!("Missing tag key"))?;
87 let value = t
88 .get(1)
89 .ok_or_else(|| anyhow::anyhow!("Missing tag value"))?;
90 match key.as_str() {
91 "total_reviews" => total_reviews = value.parse::<u64>()?,
92 "total_rating" => total_rating = value.parse::<f64>()?,
93 "last_rating" => last_rating = value.parse::<u8>()?,
94 "max_rate" => max_rate = value.parse::<u8>()?,
95 "min_rate" => min_rate = value.parse::<u8>()?,
96 _ => {}
97 }
98 }
99
100 Ok(Self {
101 total_reviews,
102 total_rating,
103 last_rating,
104 max_rate,
105 min_rate,
106 })
107 }
108}