BlueGit

ict rusty-teams

Files

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

messages.rs

messages.rs 13.0 KiB Download Raw
1use std::time::Duration;
2
3use chrono::Utc;
4use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
5use serde_json::{Value, json};
6use session::{ApiResponse, IC3, Method, Request, Scope, Session};
7
8use crate::error::{Error, Result};
9use crate::pins::DEFAULT_REGION;
10
11const MESSAGES_SCOPE: &str = "Teams.AccessAsUser.All";
12pub fn messages_scope() -> Scope {
13 Scope::new(IC3, MESSAGES_SCOPE)
14}
15
16pub const DEFAULT_RETRY_DELAY: Duration = Duration::from_millis(500);
17
18const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
19 .remove(b'-')
20 .remove(b'_')
21 .remove(b'.')
22 .remove(b'!')
23 .remove(b'~')
24 .remove(b'*')
25 .remove(b'\'')
26 .remove(b'(')
27 .remove(b')');
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum ConversationRef {
31 Chat { chat_id: String },
32 ChannelRoot { channel_id: String },
33 ChannelReply { channel_id: String, root_id: String },
34}
35
36impl ConversationRef {
37 pub fn chat(chat_id: &str) -> Self {
38 ConversationRef::Chat {
39 chat_id: chat_id.to_owned(),
40 }
41 }
42
43 pub fn channel_root(channel_id: &str) -> Self {
44 ConversationRef::ChannelRoot {
45 channel_id: channel_id.to_owned(),
46 }
47 }
48
49 pub fn channel_reply(channel_id: &str, root_id: &str) -> Self {
50 ConversationRef::ChannelReply {
51 channel_id: channel_id.to_owned(),
52 root_id: root_id.to_owned(),
53 }
54 }
55
56 pub fn conversation_id(&self) -> String {
57 match self {
58 ConversationRef::Chat { chat_id } => chat_id.clone(),
59 ConversationRef::ChannelRoot { channel_id } => channel_id.clone(),
60 ConversationRef::ChannelReply {
61 channel_id,
62 root_id,
63 } => format!("{channel_id};messageid={root_id}"),
64 }
65 }
66}
67
68pub(crate) fn encode(value: &str) -> String {
69 utf8_percent_encode(value, ENCODE_COMPONENT).to_string()
70}
71
72pub trait MessageTransport {
73 fn send(&self, request: Request) -> impl std::future::Future<Output = Result<ApiResponse>>;
74}
75
76pub struct SessionMessageTransport {
77 session: Session,
78 scope: Scope,
79}
80
81impl SessionMessageTransport {
82 pub fn new(session: &Session) -> Self {
83 SessionMessageTransport {
84 session: session.clone(),
85 scope: messages_scope(),
86 }
87 }
88}
89
90impl MessageTransport for SessionMessageTransport {
91 async fn send(&self, request: Request) -> Result<ApiResponse> {
92 let mut answers = self.session.batch(&[request], &self.scope).await?;
93 Ok(answers.remove(0))
94 }
95}
96
97pub struct Messages<T: MessageTransport = SessionMessageTransport> {
98 pub(crate) transport: T,
99 pub(crate) base_url: String,
100 retry_delay: Duration,
101}
102
103impl Messages<SessionMessageTransport> {
104 pub fn new(session: &Session) -> Self {
105 Self::with_region(session, DEFAULT_REGION)
106 }
107
108 pub fn with_region(session: &Session, region: &str) -> Self {
109 Messages::with_transport(SessionMessageTransport::new(session), region)
110 }
111}
112
113impl<T: MessageTransport> Messages<T> {
114 pub fn with_transport(transport: T, region: &str) -> Self {
115 Messages {
116 transport,
117 base_url: format!(
118 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations"
119 ),
120 retry_delay: DEFAULT_RETRY_DELAY,
121 }
122 }
123
124 pub fn with_retry_delay(mut self, retry_delay: Duration) -> Self {
125 self.retry_delay = retry_delay;
126 self
127 }
128
129 pub fn message_url(&self, conversation: &ConversationRef, message_id: &str) -> String {
130 format!(
131 "{}/{}/messages/{}",
132 self.base_url,
133 encode(&conversation.conversation_id()),
134 encode(message_id)
135 )
136 }
137
138 pub async fn edit_message(
139 &self,
140 conversation: &ConversationRef,
141 message_id: &str,
142 html: &str,
143 ) -> Result<()> {
144 self.edit_message_with_mentions(conversation, message_id, html, None)
145 .await
146 }
147
148 /// `mentions` is the JSON text of the chatsvc mention entries for the spans in `html`.
149 pub async fn edit_message_with_mentions(
150 &self,
151 conversation: &ConversationRef,
152 message_id: &str,
153 html: &str,
154 mentions: Option<&str>,
155 ) -> Result<()> {
156 let url = self.message_url(conversation, message_id);
157 let mut body = edit_body(message_id, html);
158 if let Some(mentions) = mentions {
159 body["properties"]["mentions"] = json!(mentions);
160 }
161 let mut answer = self.put(&url, &body).await?;
162 if answer.status == 404 {
163 tokio::time::sleep(self.retry_delay).await;
164 answer = self.put(&url, &body).await?;
165 }
166 ensure_success(&answer)
167 }
168
169 /// `cards` is the JSON text of the cards array; Teams web reads each card's `content` as an object.
170 pub async fn set_cards(
171 &self,
172 conversation: &ConversationRef,
173 message_id: &str,
174 cards: &str,
175 ) -> Result<()> {
176 let url = format!(
177 "{}/properties?name=cards",
178 self.message_url(conversation, message_id)
179 );
180 let body = json!({ "cards": cards });
181 let mut answer = self.put(&url, &body).await?;
182 if answer.status == 404 {
183 tokio::time::sleep(self.retry_delay).await;
184 answer = self.put(&url, &body).await?;
185 }
186 ensure_success(&answer)
187 }
188
189 pub async fn soft_delete_message(
190 &self,
191 conversation: &ConversationRef,
192 message_id: &str,
193 ) -> Result<()> {
194 let url = format!(
195 "{}?behavior=softDelete",
196 self.message_url(conversation, message_id)
197 );
198 let answer = self.transport.send(Request::delete(&url)).await?;
199 ensure_success(&answer)
200 }
201
202 pub async fn undelete_message(
203 &self,
204 conversation: &ConversationRef,
205 message_id: &str,
206 ) -> Result<()> {
207 let url = format!(
208 "{}/properties?name=deletetime",
209 self.message_url(conversation, message_id)
210 );
211 let body = json!({"deletetime": null});
212 let answer = self
213 .transport
214 .send(Request::with_body(Method::Delete, &url, body))
215 .await?;
216 ensure_success(&answer)
217 }
218
219 pub async fn set_emotion(
220 &self,
221 conversation: &ConversationRef,
222 message_id: &str,
223 key: &str,
224 ) -> Result<()> {
225 let url = self.emotions_url(conversation, message_id);
226 let body = json!({"emotions": {"key": key, "value": Utc::now().timestamp_millis()}});
227 self.send_retrying_server_errors(Method::Put, &url, &body)
228 .await
229 }
230
231 pub async fn unset_emotion(
232 &self,
233 conversation: &ConversationRef,
234 message_id: &str,
235 key: &str,
236 ) -> Result<()> {
237 let url = self.emotions_url(conversation, message_id);
238 let body = json!({"emotions": {"key": key}});
239 self.send_retrying_server_errors(Method::Delete, &url, &body)
240 .await
241 }
242
243 pub async fn unset_emotions(
244 &self,
245 conversation: &ConversationRef,
246 message_id: &str,
247 keys: &[&str],
248 ) -> Result<()> {
249 let mut last_error = None;
250 let mut any_succeeded = false;
251 for key in keys {
252 match self.unset_emotion(conversation, message_id, key).await {
253 Ok(()) => any_succeeded = true,
254 Err(error) => last_error = Some(error),
255 }
256 }
257 match last_error {
258 Some(error) if !any_succeeded => Err(error),
259 _ => Ok(()),
260 }
261 }
262
263 /// Answers with the new message id, which chatsvc returns as `OriginalArrivalTime`.
264 pub async fn post_message(
265 &self,
266 conversation: &ConversationRef,
267 html: &str,
268 display_name: &str,
269 properties: &Value,
270 ) -> Result<String> {
271 let url = format!(
272 "{}/{}/messages",
273 self.base_url,
274 encode(&conversation.conversation_id())
275 );
276 let body = rich_text_body(html, display_name, properties);
277 let answer = self
278 .transport
279 .send(Request::with_body(Method::Post, &url, body))
280 .await?;
281 ensure_success(&answer)?;
282 crate::json_id::id_text(&answer.body["OriginalArrivalTime"]).ok_or_else(|| {
283 Error::UnexpectedAnswer("message post has no OriginalArrivalTime".into())
284 })
285 }
286
287 pub async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
288 let url = format!(
289 "{}/{}/messages",
290 self.base_url,
291 encode(&conversation.conversation_id())
292 );
293 let answer = self
294 .transport
295 .send(Request::with_body(Method::Post, &url, typing_body(active)))
296 .await?;
297 ensure_success(&answer)
298 }
299
300 fn emotions_url(&self, conversation: &ConversationRef, message_id: &str) -> String {
301 format!(
302 "{}/properties?name=emotions",
303 self.message_url(conversation, message_id)
304 )
305 }
306
307 async fn send_retrying_server_errors(
308 &self,
309 method: Method,
310 url: &str,
311 body: &Value,
312 ) -> Result<()> {
313 let request = || Request::with_body(method, url, body.clone());
314 let mut answer = self.transport.send(request()).await?;
315 if (500..600).contains(&answer.status) {
316 tokio::time::sleep(self.retry_delay).await;
317 answer = self.transport.send(request()).await?;
318 }
319 ensure_success(&answer)
320 }
321
322 async fn put(&self, url: &str, body: &Value) -> Result<ApiResponse> {
323 self.transport
324 .send(Request::with_body(Method::Put, url, body.clone()))
325 .await
326 }
327}
328
329fn edit_body(message_id: &str, html: &str) -> Value {
330 json!({
331 "id": message_id,
332 "content": html,
333 "messagetype": "RichText/Html",
334 "contenttype": "text",
335 "properties": {"edittime": Utc::now().timestamp_millis().to_string()},
336 })
337}
338
339fn rich_text_body(html: &str, display_name: &str, properties: &Value) -> Value {
340 json!({
341 "clientmessageid": new_client_message_id(),
342 "content": html,
343 "messagetype": "RichText/Html",
344 "contenttype": "text",
345 "imdisplayname": display_name,
346 "amsreferences": [],
347 "properties": properties,
348 })
349}
350
351const CLIENT_MESSAGE_ID_LENGTH: usize = 19;
352
353/// Teams web: two random `uint32` as decimal strings, joined and cut to 19 characters.
354pub(crate) fn new_client_message_id() -> String {
355 let random = uuid::Uuid::new_v4().as_u128();
356 let first = (random >> 96) as u32;
357 let second = (random >> 64) as u32;
358 let mut id = format!("{first}{second}");
359 id.truncate(CLIENT_MESSAGE_ID_LENGTH);
360 id
361}
362
363fn typing_body(active: bool) -> Value {
364 json!({
365 "content": "",
366 "messagetype": if active { "Control/Typing" } else { "Control/ClearTyping" },
367 "contenttype": "Application/Message",
368 })
369}
370
371pub(crate) fn ensure_success(answer: &ApiResponse) -> Result<()> {
372 if answer.is_success() {
373 Ok(())
374 } else if answer.status == 403 && acl_check_failed(&answer.body) {
375 Err(Error::AccessDenied)
376 } else {
377 Err(Error::Session(session::Error::api(
378 answer.status,
379 "chatsvc",
380 answer.body.clone(),
381 )))
382 }
383}
384
385/// `errorCode` 209 whose `message` is a JSON string with `subCode` `AclCheckFailed`.
386pub(crate) fn acl_check_failed(body: &Value) -> bool {
387 if body.get("errorCode").and_then(Value::as_i64) != Some(209) {
388 return false;
389 }
390 let Some(message) = body.get("message").and_then(Value::as_str) else {
391 return false;
392 };
393 serde_json::from_str::<Value>(message)
394 .ok()
395 .and_then(|inner| {
396 inner
397 .get("subCode")
398 .and_then(Value::as_str)
399 .map(|code| code == "AclCheckFailed")
400 })
401 .unwrap_or(false)
402}
403
404#[cfg(test)]
405mod acl_check_tests {
406 use serde_json::json;
407 use session::ApiResponse;
408
409 use super::{Error, acl_check_failed, ensure_success};
410
411 fn denied() -> serde_json::Value {
412 json!({
413 "errorCode": 209,
414 "message": "{\"subCode\":\"AclCheckFailed\",\"details\":\"The initiator 8:orgid:abc\"}"
415 })
416 }
417
418 #[test]
419 fn acl_check_failed_on_a_roster_denial() {
420 assert!(acl_check_failed(&denied()));
421 assert!(!acl_check_failed(
422 &json!({"errorCode": 209, "message": "{\"subCode\":\"Other\"}"})
423 ));
424 assert!(!acl_check_failed(&json!({"errorCode": 403})));
425 }
426
427 #[test]
428 fn ensure_success_maps_the_denial_and_keeps_other_403s() {
429 let denied = ApiResponse {
430 status: 403,
431 body: denied(),
432 retry_after: None,
433 };
434 assert!(matches!(ensure_success(&denied), Err(Error::AccessDenied)));
435 let other = ApiResponse {
436 status: 403,
437 body: json!({"error": "nope"}),
438 retry_after: None,
439 };
440 assert!(matches!(ensure_success(&other), Err(Error::Session(_))));
441 }
442}