BlueGit

ict rusty-teams

Files

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

post_follow.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
post_follow.rs 9.1 KiB Download Raw
1use std::collections::HashMap;
2
3use serde_json::{Value, json};
4use session::{Method, Request};
5
6use crate::error::Result;
7use crate::members::user_mri;
8use crate::messages::{MessageTransport, Messages, encode, ensure_success};
9
10const FOLLOW_EMOTION: &str = "follow";
11const EXPLICIT_FOLLOW: u8 = 1;
12const IMPLICIT_FOLLOW: u8 = 2;
13const EXPLICIT_UNFOLLOW: u8 = 3;
14
15/// Teams' reply chain follow state (`rcMetadata.f`).
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum PostFollowState {
18 ExplicitFollow,
19 ImplicitFollow,
20 ExplicitUnfollow,
21}
22
23impl PostFollowState {
24 fn from_code(code: u64) -> Option<Self> {
25 match u8::try_from(code).ok()? {
26 EXPLICIT_FOLLOW => Some(PostFollowState::ExplicitFollow),
27 IMPLICIT_FOLLOW => Some(PostFollowState::ImplicitFollow),
28 EXPLICIT_UNFOLLOW => Some(PostFollowState::ExplicitUnfollow),
29 _ => None,
30 }
31 }
32
33 pub fn followed(self) -> bool {
34 self != PostFollowState::ExplicitUnfollow
35 }
36}
37
38pub fn parse_post_follow_states(body: &Value) -> HashMap<String, PostFollowState> {
39 body.get("rcMetadataList")
40 .and_then(Value::as_array)
41 .into_iter()
42 .flatten()
43 .filter_map(|entry| {
44 let root_id = crate::json_id::id_text(entry.get("rootMessageId")?)?;
45 let state = PostFollowState::from_code(entry.pointer("/rcMetadata/f")?.as_u64()?)?;
46 Some((root_id, state))
47 })
48 .collect()
49}
50
51impl<T: MessageTransport> Messages<T> {
52 fn user_conversations_url(&self, user_id: &str) -> String {
53 self.base_url
54 .replace("/users/ME/", &format!("/users/{}/", user_mri(user_id)))
55 }
56
57 pub fn post_follow_request(
58 &self,
59 user_id: &str,
60 channel_id: &str,
61 root_id: &str,
62 followed: bool,
63 ) -> Request {
64 let code = if followed {
65 EXPLICIT_FOLLOW
66 } else {
67 EXPLICIT_UNFOLLOW
68 };
69 Request::with_body(
70 Method::Put,
71 format!(
72 "{}/{}/rcmetadata/{}",
73 self.user_conversations_url(user_id),
74 encode(channel_id),
75 encode(root_id)
76 ),
77 json!({"f": code}),
78 )
79 }
80
81 pub fn post_follow_annotation_request(
82 &self,
83 channel_id: &str,
84 root_id: &str,
85 followed: bool,
86 ) -> Request {
87 Request::with_body(
88 Method::Put,
89 format!(
90 "{}/{}/messages/{}/properties?name=emotions",
91 self.base_url,
92 encode(channel_id),
93 encode(root_id)
94 ),
95 json!({"emotions": {"key": FOLLOW_EMOTION, "value": u8::from(followed)}}),
96 )
97 }
98
99 pub fn post_follow_states_request(&self, channel_id: &str, root_ids: &[u64]) -> Request {
100 Request::with_body(
101 Method::Post,
102 format!("{}/{}/getrcmetadata", self.base_url, encode(channel_id)),
103 json!({"rootMessageIds": root_ids}),
104 )
105 }
106
107 /// Teams writes the reply chain metadata first and the `follow` annotation only after it succeeded.
108 pub async fn set_post_followed(
109 &self,
110 user_id: &str,
111 channel_id: &str,
112 root_id: &str,
113 followed: bool,
114 ) -> Result<Option<String>> {
115 let answer = self
116 .transport
117 .send(self.post_follow_request(user_id, channel_id, root_id, followed))
118 .await?;
119 ensure_success(&answer)?;
120 let annotation = self
121 .transport
122 .send(self.post_follow_annotation_request(channel_id, root_id, followed))
123 .await
124 .and_then(|answer| ensure_success(&answer));
125 Ok(annotation.err().map(|error| error.to_string()))
126 }
127
128 pub async fn post_follow_states(
129 &self,
130 channel_id: &str,
131 root_ids: &[String],
132 ) -> Result<HashMap<String, PostFollowState>> {
133 let numeric: Vec<u64> = root_ids.iter().filter_map(|id| id.parse().ok()).collect();
134 if numeric.is_empty() {
135 return Ok(HashMap::new());
136 }
137 let answer = self
138 .transport
139 .send(self.post_follow_states_request(channel_id, &numeric))
140 .await?;
141 ensure_success(&answer)?;
142 Ok(parse_post_follow_states(&answer.body))
143 }
144}
145
146#[cfg(test)]
147mod tests {
148 use std::sync::Mutex;
149
150 use session::ApiResponse;
151
152 use super::*;
153
154 struct Canned {
155 statuses: Vec<u16>,
156 body: Value,
157 requests: Mutex<Vec<Request>>,
158 }
159
160 impl MessageTransport for Canned {
161 async fn send(&self, request: Request) -> Result<ApiResponse> {
162 let mut requests = self.requests.lock().unwrap();
163 let status = self.statuses[requests.len().min(self.statuses.len() - 1)];
164 requests.push(request);
165 Ok(ApiResponse {
166 status,
167 body: self.body.clone(),
168 retry_after: None,
169 })
170 }
171 }
172
173 fn canned(status: u16, body: Value) -> Messages<Canned> {
174 canned_sequence(vec![status], body)
175 }
176
177 fn canned_sequence(statuses: Vec<u16>, body: Value) -> Messages<Canned> {
178 Messages::with_transport(
179 Canned {
180 statuses,
181 body,
182 requests: Mutex::new(Vec::new()),
183 },
184 "emea",
185 )
186 }
187
188 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users";
189
190 #[tokio::test]
191 async fn follow_writes_reply_chain_metadata_then_annotation() {
192 let messages = canned(200, json!({}));
193 messages
194 .set_post_followed("a1", "19:c@thread.tacv2", "1791368000000", true)
195 .await
196 .unwrap();
197 messages
198 .set_post_followed("a1", "19:c@thread.tacv2", "1791368000000", false)
199 .await
200 .unwrap();
201 let requests = messages.transport.requests.lock().unwrap();
202 assert_eq!(requests[0].method, Method::Put);
203 assert_eq!(
204 requests[0].url,
205 format!(
206 "{BASE}/8:orgid:a1/conversations/19%3Ac%40thread.tacv2/rcmetadata/1791368000000"
207 )
208 );
209 assert_eq!(requests[0].body, Some(json!({"f": 1})));
210 assert_eq!(
211 requests[1].url,
212 format!(
213 "{BASE}/ME/conversations/19%3Ac%40thread.tacv2/messages/1791368000000/properties?name=emotions"
214 )
215 );
216 assert_eq!(
217 requests[1].body,
218 Some(json!({"emotions": {"key": "follow", "value": 1}}))
219 );
220 assert_eq!(requests[2].body, Some(json!({"f": 3})));
221 assert_eq!(
222 requests[3].body,
223 Some(json!({"emotions": {"key": "follow", "value": 0}}))
224 );
225 }
226
227 #[tokio::test]
228 async fn failed_metadata_write_skips_the_annotation() {
229 let messages = canned(403, json!({}));
230 assert!(
231 messages
232 .set_post_followed("a1", "19:c", "1", true)
233 .await
234 .is_err()
235 );
236 assert_eq!(messages.transport.requests.lock().unwrap().len(), 1);
237 }
238
239 #[tokio::test]
240 async fn failed_annotation_still_counts_as_followed() {
241 let messages = canned_sequence(vec![200, 500], json!({}));
242 let annotation_failure = messages
243 .set_post_followed("a1", "19:c", "1", true)
244 .await
245 .unwrap();
246 assert!(annotation_failure.is_some());
247 assert_eq!(messages.transport.requests.lock().unwrap().len(), 2);
248 }
249
250 #[tokio::test]
251 async fn reads_follow_states_of_root_posts() {
252 let body = json!({"conversationId": "19:c", "rcMetadataList": [
253 {"statusCode": 200, "rootMessageId": 11, "rcMetadata": {"lu": 1, "f": 1}},
254 {"statusCode": 200, "rootMessageId": "12", "rcMetadata": {"lu": 1, "f": 3}},
255 {"statusCode": 200, "rootMessageId": 13, "rcMetadata": {"lu": 1, "f": 2}},
256 {"statusCode": 200, "rootMessageId": 14, "rcMetadata": {"lu": 1, "s": 1}},
257 {"statusCode": 404, "rootMessageId": 15},
258 ]});
259 let messages = canned(207, body);
260 let states = messages
261 .post_follow_states("19:c", &["11".into(), "12".into(), "x".into()])
262 .await
263 .unwrap();
264 assert_eq!(states.len(), 3);
265 assert!(states["11"].followed());
266 assert!(!states["12"].followed());
267 assert_eq!(states["13"], PostFollowState::ImplicitFollow);
268 let requests = messages.transport.requests.lock().unwrap();
269 assert_eq!(requests[0].method, Method::Post);
270 assert_eq!(
271 requests[0].url,
272 format!("{BASE}/ME/conversations/19%3Ac/getrcmetadata")
273 );
274 assert_eq!(requests[0].body, Some(json!({"rootMessageIds": [11, 12]})));
275 }
276
277 #[tokio::test]
278 async fn no_numeric_roots_sends_nothing() {
279 let messages = canned(200, json!({}));
280 assert!(
281 messages
282 .post_follow_states("19:c", &[])
283 .await
284 .unwrap()
285 .is_empty()
286 );
287 assert!(messages.transport.requests.lock().unwrap().is_empty());
288 }
289}