BlueGit

ict rusty-teams

Files

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

messages.rs

messages.rs 13.5 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 self.edit_post(conversation, message_id, html, mentions, None)
157 .await
158 }
159
160 /// The PUT replaces all properties, so a channel post sends its `subject` again to keep it.
161 pub async fn edit_post(
162 &self,
163 conversation: &ConversationRef,
164 message_id: &str,
165 html: &str,
166 mentions: Option<&str>,
167 subject: Option<&str>,
168 ) -> Result<()> {
169 let url = self.message_url(conversation, message_id);
170 let mut body = edit_body(message_id, html);
171 if let Some(mentions) = mentions {
172 body["properties"]["mentions"] = json!(mentions);
173 }
174 if let Some(subject) = subject {
175 body["properties"]["subject"] = json!(subject);
176 }
177 let mut answer = self.put(&url, &body).await?;
178 if answer.status == 404 {
179 tokio::time::sleep(self.retry_delay).await;
180 answer = self.put(&url, &body).await?;
181 }
182 ensure_success(&answer)
183 }
184
185 /// `cards` is the JSON text of the cards array; Teams web reads each card's `content` as an object.
186 pub async fn set_cards(
187 &self,
188 conversation: &ConversationRef,
189 message_id: &str,
190 cards: &str,
191 ) -> Result<()> {
192 let url = format!(
193 "{}/properties?name=cards",
194 self.message_url(conversation, message_id)
195 );
196 let body = json!({ "cards": cards });
197 let mut answer = self.put(&url, &body).await?;
198 if answer.status == 404 {
199 tokio::time::sleep(self.retry_delay).await;
200 answer = self.put(&url, &body).await?;
201 }
202 ensure_success(&answer)
203 }
204
205 pub async fn soft_delete_message(
206 &self,
207 conversation: &ConversationRef,
208 message_id: &str,
209 ) -> Result<()> {
210 let url = format!(
211 "{}?behavior=softDelete",
212 self.message_url(conversation, message_id)
213 );
214 let answer = self.transport.send(Request::delete(&url)).await?;
215 ensure_success(&answer)
216 }
217
218 pub async fn undelete_message(
219 &self,
220 conversation: &ConversationRef,
221 message_id: &str,
222 ) -> Result<()> {
223 let url = format!(
224 "{}/properties?name=deletetime",
225 self.message_url(conversation, message_id)
226 );
227 let body = json!({"deletetime": null});
228 let answer = self
229 .transport
230 .send(Request::with_body(Method::Delete, &url, body))
231 .await?;
232 ensure_success(&answer)
233 }
234
235 pub async fn set_emotion(
236 &self,
237 conversation: &ConversationRef,
238 message_id: &str,
239 key: &str,
240 ) -> Result<()> {
241 let url = self.emotions_url(conversation, message_id);
242 let body = json!({"emotions": {"key": key, "value": Utc::now().timestamp_millis()}});
243 self.send_retrying_server_errors(Method::Put, &url, &body)
244 .await
245 }
246
247 pub async fn unset_emotion(
248 &self,
249 conversation: &ConversationRef,
250 message_id: &str,
251 key: &str,
252 ) -> Result<()> {
253 let url = self.emotions_url(conversation, message_id);
254 let body = json!({"emotions": {"key": key}});
255 self.send_retrying_server_errors(Method::Delete, &url, &body)
256 .await
257 }
258
259 pub async fn unset_emotions(
260 &self,
261 conversation: &ConversationRef,
262 message_id: &str,
263 keys: &[&str],
264 ) -> Result<()> {
265 let mut last_error = None;
266 let mut any_succeeded = false;
267 for key in keys {
268 match self.unset_emotion(conversation, message_id, key).await {
269 Ok(()) => any_succeeded = true,
270 Err(error) => last_error = Some(error),
271 }
272 }
273 match last_error {
274 Some(error) if !any_succeeded => Err(error),
275 _ => Ok(()),
276 }
277 }
278
279 /// Answers with the new message id, which chatsvc returns as `OriginalArrivalTime`.
280 pub async fn post_message(
281 &self,
282 conversation: &ConversationRef,
283 html: &str,
284 display_name: &str,
285 properties: &Value,
286 ) -> Result<String> {
287 let url = format!(
288 "{}/{}/messages",
289 self.base_url,
290 encode(&conversation.conversation_id())
291 );
292 let body = rich_text_body(html, display_name, properties);
293 let answer = self
294 .transport
295 .send(Request::with_body(Method::Post, &url, body))
296 .await?;
297 ensure_success(&answer)?;
298 crate::json_id::id_text(&answer.body["OriginalArrivalTime"]).ok_or_else(|| {
299 Error::UnexpectedAnswer("message post has no OriginalArrivalTime".into())
300 })
301 }
302
303 pub async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
304 let url = format!(
305 "{}/{}/messages",
306 self.base_url,
307 encode(&conversation.conversation_id())
308 );
309 let answer = self
310 .transport
311 .send(Request::with_body(Method::Post, &url, typing_body(active)))
312 .await?;
313 ensure_success(&answer)
314 }
315
316 fn emotions_url(&self, conversation: &ConversationRef, message_id: &str) -> String {
317 format!(
318 "{}/properties?name=emotions",
319 self.message_url(conversation, message_id)
320 )
321 }
322
323 async fn send_retrying_server_errors(
324 &self,
325 method: Method,
326 url: &str,
327 body: &Value,
328 ) -> Result<()> {
329 let request = || Request::with_body(method, url, body.clone());
330 let mut answer = self.transport.send(request()).await?;
331 if (500..600).contains(&answer.status) {
332 tokio::time::sleep(self.retry_delay).await;
333 answer = self.transport.send(request()).await?;
334 }
335 ensure_success(&answer)
336 }
337
338 async fn put(&self, url: &str, body: &Value) -> Result<ApiResponse> {
339 self.transport
340 .send(Request::with_body(Method::Put, url, body.clone()))
341 .await
342 }
343}
344
345fn edit_body(message_id: &str, html: &str) -> Value {
346 json!({
347 "id": message_id,
348 "content": html,
349 "messagetype": "RichText/Html",
350 "contenttype": "text",
351 "properties": {"edittime": Utc::now().timestamp_millis().to_string()},
352 })
353}
354
355fn rich_text_body(html: &str, display_name: &str, properties: &Value) -> Value {
356 json!({
357 "clientmessageid": new_client_message_id(),
358 "content": html,
359 "messagetype": "RichText/Html",
360 "contenttype": "text",
361 "imdisplayname": display_name,
362 "amsreferences": [],
363 "properties": properties,
364 })
365}
366
367const CLIENT_MESSAGE_ID_LENGTH: usize = 19;
368
369/// Teams web: two random `uint32` as decimal strings, joined and cut to 19 characters.
370pub(crate) fn new_client_message_id() -> String {
371 let random = uuid::Uuid::new_v4().as_u128();
372 let first = (random >> 96) as u32;
373 let second = (random >> 64) as u32;
374 let mut id = format!("{first}{second}");
375 id.truncate(CLIENT_MESSAGE_ID_LENGTH);
376 id
377}
378
379fn typing_body(active: bool) -> Value {
380 json!({
381 "content": "",
382 "messagetype": if active { "Control/Typing" } else { "Control/ClearTyping" },
383 "contenttype": "Application/Message",
384 })
385}
386
387pub(crate) fn ensure_success(answer: &ApiResponse) -> Result<()> {
388 if answer.is_success() {
389 Ok(())
390 } else if answer.status == 403 && acl_check_failed(&answer.body) {
391 Err(Error::AccessDenied)
392 } else {
393 Err(Error::Session(session::Error::api(
394 answer.status,
395 "chatsvc",
396 answer.body.clone(),
397 )))
398 }
399}
400
401/// `errorCode` 209 whose `message` is a JSON string with `subCode` `AclCheckFailed`.
402pub(crate) fn acl_check_failed(body: &Value) -> bool {
403 if body.get("errorCode").and_then(Value::as_i64) != Some(209) {
404 return false;
405 }
406 let Some(message) = body.get("message").and_then(Value::as_str) else {
407 return false;
408 };
409 serde_json::from_str::<Value>(message)
410 .ok()
411 .and_then(|inner| {
412 inner
413 .get("subCode")
414 .and_then(Value::as_str)
415 .map(|code| code == "AclCheckFailed")
416 })
417 .unwrap_or(false)
418}
419
420#[cfg(test)]
421mod acl_check_tests {
422 use serde_json::json;
423 use session::ApiResponse;
424
425 use super::{Error, acl_check_failed, ensure_success};
426
427 fn denied() -> serde_json::Value {
428 json!({
429 "errorCode": 209,
430 "message": "{\"subCode\":\"AclCheckFailed\",\"details\":\"The initiator 8:orgid:abc\"}"
431 })
432 }
433
434 #[test]
435 fn acl_check_failed_on_a_roster_denial() {
436 assert!(acl_check_failed(&denied()));
437 assert!(!acl_check_failed(
438 &json!({"errorCode": 209, "message": "{\"subCode\":\"Other\"}"})
439 ));
440 assert!(!acl_check_failed(&json!({"errorCode": 403})));
441 }
442
443 #[test]
444 fn ensure_success_maps_the_denial_and_keeps_other_403s() {
445 let denied = ApiResponse {
446 status: 403,
447 body: denied(),
448 retry_after: None,
449 };
450 assert!(matches!(ensure_success(&denied), Err(Error::AccessDenied)));
451 let other = ApiResponse {
452 status: 403,
453 body: json!({"error": "nope"}),
454 retry_after: None,
455 };
456 assert!(matches!(ensure_success(&other), Err(Error::Session(_))));
457 }
458}