BlueGit

ict rusty-teams

Files

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

messages.rs

messages.rs 10.7 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 let url = self.message_url(conversation, message_id);
145 let body = edit_body(message_id, html);
146 let mut answer = self.put(&url, &body).await?;
147 if answer.status == 404 {
148 tokio::time::sleep(self.retry_delay).await;
149 answer = self.put(&url, &body).await?;
150 }
151 ensure_success(&answer)
152 }
153
154 /// `cards` is the JSON text of the cards array; Teams web reads each card's `content` as an object.
155 pub async fn set_cards(
156 &self,
157 conversation: &ConversationRef,
158 message_id: &str,
159 cards: &str,
160 ) -> Result<()> {
161 let url = format!(
162 "{}/properties?name=cards",
163 self.message_url(conversation, message_id)
164 );
165 let body = json!({ "cards": cards });
166 let mut answer = self.put(&url, &body).await?;
167 if answer.status == 404 {
168 tokio::time::sleep(self.retry_delay).await;
169 answer = self.put(&url, &body).await?;
170 }
171 ensure_success(&answer)
172 }
173
174 pub async fn soft_delete_message(
175 &self,
176 conversation: &ConversationRef,
177 message_id: &str,
178 ) -> Result<()> {
179 let url = format!(
180 "{}?behavior=softDelete",
181 self.message_url(conversation, message_id)
182 );
183 let answer = self.transport.send(Request::delete(&url)).await?;
184 ensure_success(&answer)
185 }
186
187 pub async fn undelete_message(
188 &self,
189 conversation: &ConversationRef,
190 message_id: &str,
191 ) -> Result<()> {
192 let url = format!(
193 "{}/properties?name=deletetime",
194 self.message_url(conversation, message_id)
195 );
196 let body = json!({"deletetime": null});
197 let answer = self
198 .transport
199 .send(Request::with_body(Method::Delete, &url, body))
200 .await?;
201 ensure_success(&answer)
202 }
203
204 pub async fn set_emotion(
205 &self,
206 conversation: &ConversationRef,
207 message_id: &str,
208 key: &str,
209 ) -> Result<()> {
210 let url = self.emotions_url(conversation, message_id);
211 let body = json!({"emotions": {"key": key, "value": Utc::now().timestamp_millis()}});
212 self.send_retrying_server_errors(Method::Put, &url, &body)
213 .await
214 }
215
216 pub async fn unset_emotion(
217 &self,
218 conversation: &ConversationRef,
219 message_id: &str,
220 key: &str,
221 ) -> Result<()> {
222 let url = self.emotions_url(conversation, message_id);
223 let body = json!({"emotions": {"key": key}});
224 self.send_retrying_server_errors(Method::Delete, &url, &body)
225 .await
226 }
227
228 pub async fn unset_emotions(
229 &self,
230 conversation: &ConversationRef,
231 message_id: &str,
232 keys: &[&str],
233 ) -> Result<()> {
234 let mut last_error = None;
235 let mut any_succeeded = false;
236 for key in keys {
237 match self.unset_emotion(conversation, message_id, key).await {
238 Ok(()) => any_succeeded = true,
239 Err(error) => last_error = Some(error),
240 }
241 }
242 match last_error {
243 Some(error) if !any_succeeded => Err(error),
244 _ => Ok(()),
245 }
246 }
247
248 /// Answers with the new message id, which chatsvc returns as `OriginalArrivalTime`.
249 pub async fn post_message(
250 &self,
251 conversation: &ConversationRef,
252 html: &str,
253 display_name: &str,
254 properties: &Value,
255 ) -> Result<String> {
256 let url = format!(
257 "{}/{}/messages",
258 self.base_url,
259 encode(&conversation.conversation_id())
260 );
261 let body = rich_text_body(html, display_name, properties);
262 let answer = self
263 .transport
264 .send(Request::with_body(Method::Post, &url, body))
265 .await?;
266 ensure_success(&answer)?;
267 crate::json_id::id_text(&answer.body["OriginalArrivalTime"]).ok_or_else(|| {
268 Error::UnexpectedAnswer("message post has no OriginalArrivalTime".into())
269 })
270 }
271
272 pub async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
273 let url = format!(
274 "{}/{}/messages",
275 self.base_url,
276 encode(&conversation.conversation_id())
277 );
278 let answer = self
279 .transport
280 .send(Request::with_body(Method::Post, &url, typing_body(active)))
281 .await?;
282 ensure_success(&answer)
283 }
284
285 fn emotions_url(&self, conversation: &ConversationRef, message_id: &str) -> String {
286 format!(
287 "{}/properties?name=emotions",
288 self.message_url(conversation, message_id)
289 )
290 }
291
292 async fn send_retrying_server_errors(
293 &self,
294 method: Method,
295 url: &str,
296 body: &Value,
297 ) -> Result<()> {
298 let request = || Request::with_body(method, url, body.clone());
299 let mut answer = self.transport.send(request()).await?;
300 if (500..600).contains(&answer.status) {
301 tokio::time::sleep(self.retry_delay).await;
302 answer = self.transport.send(request()).await?;
303 }
304 ensure_success(&answer)
305 }
306
307 async fn put(&self, url: &str, body: &Value) -> Result<ApiResponse> {
308 self.transport
309 .send(Request::with_body(Method::Put, url, body.clone()))
310 .await
311 }
312}
313
314fn edit_body(message_id: &str, html: &str) -> Value {
315 json!({
316 "id": message_id,
317 "content": html,
318 "messagetype": "RichText/Html",
319 "contenttype": "text",
320 "properties": {"edittime": Utc::now().timestamp_millis().to_string()},
321 })
322}
323
324fn rich_text_body(html: &str, display_name: &str, properties: &Value) -> Value {
325 json!({
326 "clientmessageid": new_client_message_id(),
327 "content": html,
328 "messagetype": "RichText/Html",
329 "contenttype": "text",
330 "imdisplayname": display_name,
331 "amsreferences": [],
332 "properties": properties,
333 })
334}
335
336const CLIENT_MESSAGE_ID_LENGTH: usize = 19;
337
338/// Teams web: two random `uint32` as decimal strings, joined and cut to 19 characters.
339pub(crate) fn new_client_message_id() -> String {
340 let random = uuid::Uuid::new_v4().as_u128();
341 let first = (random >> 96) as u32;
342 let second = (random >> 64) as u32;
343 let mut id = format!("{first}{second}");
344 id.truncate(CLIENT_MESSAGE_ID_LENGTH);
345 id
346}
347
348fn typing_body(active: bool) -> Value {
349 json!({
350 "content": "",
351 "messagetype": if active { "Control/Typing" } else { "Control/ClearTyping" },
352 "contenttype": "Application/Message",
353 })
354}
355
356pub(crate) fn ensure_success(answer: &ApiResponse) -> Result<()> {
357 if answer.is_success() {
358 Ok(())
359 } else {
360 Err(Error::Session(session::Error::api(
361 answer.status,
362 "chatsvc",
363 answer.body.clone(),
364 )))
365 }
366}