BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / reaction.rs

reaction.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
reaction.rs 6.0 KiB Download Raw
1use serde_json::{Value, json};
2
3pub const DEFAULT_SKIN_TONE: u8 = 2;
4const REACTION_TYPE: &str = "Reaction";
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum Reaction {
8 Like,
9 Heart,
10 Applause,
11 Laugh,
12 Surprised,
13 Other(String),
14}
15
16impl Reaction {
17 pub const ALL: [Reaction; 5] = [
18 Reaction::Like,
19 Reaction::Heart,
20 Reaction::Applause,
21 Reaction::Laugh,
22 Reaction::Surprised,
23 ];
24
25 pub fn name(&self) -> &str {
26 match self {
27 Reaction::Like => "like",
28 Reaction::Heart => "heart",
29 Reaction::Applause => "applause",
30 Reaction::Laugh => "laugh",
31 Reaction::Surprised => "surprised",
32 Reaction::Other(name) => name,
33 }
34 }
35
36 pub fn from_name(name: &str) -> Option<Reaction> {
37 if name.trim().is_empty() {
38 return None;
39 }
40 Some(
41 Reaction::ALL
42 .into_iter()
43 .find(|reaction| reaction.name() == name)
44 .unwrap_or_else(|| Reaction::Other(name.to_owned())),
45 )
46 }
47
48 fn takes_skin_tone(&self) -> bool {
49 matches!(self, Reaction::Like | Reaction::Applause)
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct ReactionEvent {
55 pub mri: String,
56 pub reaction: Reaction,
57 pub count: u32,
58}
59
60pub fn reaction_message(
61 from: Value,
62 reaction: Reaction,
63 operation_id: &str,
64 value_id: &str,
65) -> Value {
66 let skin_tone = reaction.takes_skin_tone().then_some(DEFAULT_SKIN_TONE);
67 json!({
68 "from": from,
69 "messageContent": [{
70 "operationId": operation_id,
71 "type": REACTION_TYPE,
72 "scope": "all",
73 "to": [],
74 "payload": {"values": [{
75 "id": value_id,
76 "name": reaction.name(),
77 "count": 1,
78 "attributes": {"skinTone": skin_tone},
79 }]},
80 }],
81 })
82}
83
84pub fn parse_reactions(body: &Value) -> Vec<ReactionEvent> {
85 let items: Vec<&Value> = match body["messageContent"].as_array() {
86 Some(items) => items.iter().collect(),
87 None => vec![body],
88 };
89 items
90 .into_iter()
91 .filter(|item| item["type"].as_str() == Some(REACTION_TYPE))
92 .flat_map(|item| {
93 let mri = item["from"]["id"]
94 .as_str()
95 .or_else(|| body["from"]["id"].as_str())
96 .unwrap_or_default();
97 item["payload"]["values"]
98 .as_array()
99 .into_iter()
100 .flatten()
101 .filter_map(move |value| {
102 Some(ReactionEvent {
103 mri: mri.to_owned(),
104 reaction: Reaction::from_name(value["name"].as_str()?)?,
105 count: value["count"]
106 .as_u64()
107 .map_or(1, |count| u32::try_from(count).unwrap_or(u32::MAX)),
108 })
109 })
110 })
111 .filter(|event| !event.mri.is_empty())
112 .collect()
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118
119 #[test]
120 fn the_send_body_has_one_reaction_value_with_the_skin_tone_only_where_it_applies() {
121 let from = json!({"id": "8:orgid:me"});
122 let like = reaction_message(from.clone(), Reaction::Like, "op-1", "val-1");
123 let item = &like["messageContent"][0];
124 assert_eq!(like["from"]["id"], "8:orgid:me");
125 assert_eq!(item["type"], "Reaction");
126 assert_eq!(item["scope"], "all");
127 assert_eq!(item["operationId"], "op-1");
128 assert_eq!(item["payload"]["values"][0]["name"], "like");
129 assert_eq!(item["payload"]["values"][0]["count"], 1);
130 assert_eq!(
131 item["payload"]["values"][0]["attributes"]["skinTone"],
132 DEFAULT_SKIN_TONE
133 );
134 let heart = reaction_message(from, Reaction::Heart, "op-2", "val-2");
135 assert!(
136 heart["messageContent"][0]["payload"]["values"][0]["attributes"]["skinTone"].is_null()
137 );
138 }
139
140 #[test]
141 fn every_reaction_name_round_trips() {
142 for reaction in Reaction::ALL {
143 assert_eq!(Reaction::from_name(reaction.name()), Some(reaction));
144 }
145 assert_eq!(
146 Reaction::from_name("confetti"),
147 Some(Reaction::Other("confetti".into()))
148 );
149 assert_eq!(Reaction::from_name(""), None);
150 }
151
152 #[test]
153 fn a_single_received_reaction_is_parsed() {
154 let body = json!({
155 "from": {"id": "8:orgid:a", "displayName": "Ana"},
156 "type": "Reaction",
157 "payload": {"values": [{"name": "applause", "count": 2, "attributes": {"skinTone": "2"}}]},
158 "operationId": "op",
159 });
160 assert_eq!(
161 parse_reactions(&body),
162 vec![ReactionEvent {
163 mri: "8:orgid:a".into(),
164 reaction: Reaction::Applause,
165 count: 2
166 }]
167 );
168 }
169
170 #[test]
171 fn several_message_contents_and_foreign_types_are_handled() {
172 let body = json!({
173 "from": {"id": "8:orgid:a"},
174 "messageContent": [
175 {"type": "Reaction", "payload": {"values": [{"name": "heart"}, {"name": "unknown"}]}},
176 {"type": "Typing", "payload": {"values": [{"name": "like"}]}},
177 {"type": "Reaction", "from": {"id": "8:orgid:b"}, "payload": {"values": [{"name": "laugh", "count": 1}]}},
178 ],
179 });
180 let events = parse_reactions(&body);
181 assert_eq!(events.len(), 3);
182 assert_eq!(
183 events[0],
184 ReactionEvent {
185 mri: "8:orgid:a".into(),
186 reaction: Reaction::Heart,
187 count: 1
188 }
189 );
190 assert_eq!(events[1].reaction, Reaction::Other("unknown".into()));
191 assert_eq!(events[2].mri, "8:orgid:b");
192 }
193
194 #[test]
195 fn a_message_without_a_sender_is_ignored() {
196 let body = json!({"type": "Reaction", "payload": {"values": [{"name": "like"}]}});
197 assert!(parse_reactions(&body).is_empty());
198 }
199}