BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / emotions.rs

emotions.rs

fb874ac1 History
emotions.rs 3.8 KiB Download Raw
1use serde_json::Value;
2use session::Request;
3
4use crate::error::Result;
5use crate::messages::{MessageTransport, Messages, ensure_success};
6use crate::window::WindowDirection;
7
8const ORGID_PREFIX: &str = "8:orgid:";
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct EmotionReaction {
12 pub key: String,
13 pub user_id: Option<String>,
14 pub time_ms: Option<i64>,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct MessageEmotions {
19 pub message_id: String,
20 pub reactions: Vec<EmotionReaction>,
21}
22
23pub fn user_id_from_mri(mri: &str) -> &str {
24 mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri)
25}
26
27fn reactions(emotions: Option<&Value>) -> Vec<EmotionReaction> {
28 emotions
29 .and_then(Value::as_array)
30 .into_iter()
31 .flatten()
32 .flat_map(|entry| {
33 let key = entry.get("key").and_then(Value::as_str).unwrap_or_default();
34 entry
35 .get("users")
36 .and_then(Value::as_array)
37 .into_iter()
38 .flatten()
39 .filter(move |_| !key.is_empty())
40 .map(move |user| EmotionReaction {
41 key: key.to_owned(),
42 user_id: user
43 .get("mri")
44 .and_then(Value::as_str)
45 .map(|mri| user_id_from_mri(mri).to_owned()),
46 time_ms: user.get("time").and_then(Value::as_i64),
47 })
48 })
49 .collect()
50}
51
52/// Every listed message, including those without an `emotions` property: the chat service
53/// leaves it out when nobody reacted, and an entry whose `users` is empty means removed.
54pub fn parse_message_emotions(body: &Value) -> Vec<MessageEmotions> {
55 body.get("messages")
56 .and_then(Value::as_array)
57 .into_iter()
58 .flatten()
59 .filter_map(|message| {
60 let message_id = match message.get("id")? {
61 Value::String(text) if !text.is_empty() => text.clone(),
62 Value::Number(number) => number.to_string(),
63 _ => return None,
64 };
65 Some(MessageEmotions {
66 message_id,
67 reactions: reactions(message.pointer("/properties/emotions")),
68 })
69 })
70 .collect()
71}
72
73impl<T: MessageTransport> Messages<T> {
74 pub async fn message_emotions(
75 &self,
76 conversation_id: &str,
77 newest_message_id: &str,
78 page_size: usize,
79 ) -> Result<Vec<MessageEmotions>> {
80 let url = self.message_window_url(
81 conversation_id,
82 newest_message_id,
83 WindowDirection::Backward,
84 page_size,
85 );
86 let answer = self.transport.send(Request::get(url)).await?;
87 ensure_success(&answer)?;
88 Ok(parse_message_emotions(&answer.body))
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use serde_json::json;
95
96 use super::*;
97
98 #[test]
99 fn emotions_expand_per_user_and_skip_removed_entries() {
100 let body = json!({"messages": [
101 {"id": "1", "properties": {"emotions": [
102 {"key": "yes-tone2", "users": [
103 {"mri": "8:orgid:aaa", "time": 1792135855841_i64, "value": "1792135855835"},
104 {"mri": "8:orgid:bbb", "time": 1792135855900_i64, "value": "1"}
105 ]},
106 {"key": "heart", "users": []}
107 ]}},
108 {"id": "2", "properties": {}}
109 ]});
110 let parsed = parse_message_emotions(&body);
111 assert_eq!(parsed.len(), 2);
112 assert_eq!(parsed[0].reactions.len(), 2);
113 assert_eq!(parsed[0].reactions[0].key, "yes-tone2");
114 assert_eq!(parsed[0].reactions[0].user_id.as_deref(), Some("aaa"));
115 assert_eq!(parsed[0].reactions[1].time_ms, Some(1792135855900));
116 assert!(parsed[1].reactions.is_empty());
117 }
118}