BlueGit

ict rusty-teams

Files

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

messages.rs

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