BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / actions.rs

actions.rs

eba4ad94 History
actions.rs 17.3 KiB Download Raw
1use chrono::Utc;
2use graph::{
3 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
4};
5use store::MessageRecord;
6
7use crate::engine::{Conversation, META_USER_ID, SyncEngine};
8use crate::error::{Error, Result};
9use crate::mapping::{chat_record, message_record};
10use crate::markdown::markdown_to_html;
11use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
12use crate::remote::Remote;
13
14impl<R: Remote> SyncEngine<R> {
15 pub async fn send_message(
16 &self,
17 conversation_id: &str,
18 markdown: &str,
19 thread_root_id: Option<&str>,
20 ) -> Result<MessageRecord> {
21 self.send_message_with_mentions(conversation_id, markdown, thread_root_id, &[])
22 .await
23 }
24
25 pub async fn send_message_with_mentions(
26 &self,
27 conversation_id: &str,
28 markdown: &str,
29 thread_root_id: Option<&str>,
30 mentions: &[MentionInput],
31 ) -> Result<MessageRecord> {
32 self.send_message_with_extras(
33 conversation_id,
34 markdown,
35 thread_root_id,
36 mentions,
37 &MessageExtras::default(),
38 )
39 .await
40 }
41
42 pub async fn send_message_with_extras(
43 &self,
44 conversation_id: &str,
45 markdown: &str,
46 thread_root_id: Option<&str>,
47 mentions: &[MentionInput],
48 extras: &MessageExtras,
49 ) -> Result<MessageRecord> {
50 let conversation = self.resolve(conversation_id)?;
51 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
52 let sent = match (conversation, thread_root_id) {
53 (Conversation::Chat, None) => {
54 self.remote
55 .send_chat_message(conversation_id, &html, &mentions, extras)
56 .await?
57 }
58 (Conversation::Channel { team_id }, Some(root_id)) => {
59 self.remote
60 .reply_to_channel_message(
61 &team_id,
62 conversation_id,
63 root_id,
64 &html,
65 &mentions,
66 extras,
67 )
68 .await?
69 }
70 (Conversation::Chat, Some(_)) => {
71 return Err(Error::Unsupported("a thread reply in a chat"));
72 }
73 (Conversation::Channel { .. }, None) => {
74 return Err(Error::Unsupported(
75 "a channel send without a thread root; use post_to_channel",
76 ));
77 }
78 };
79 self.cache_sent(conversation_id, &sent)
80 }
81
82 /// Chat: quoted reply (Graph beta `replyWithQuote`). Channel: reply in the thread of `message_id`.
83 pub async fn reply_to(
84 &self,
85 conversation_id: &str,
86 message_id: &str,
87 markdown: &str,
88 ) -> Result<MessageRecord> {
89 self.reply_to_with_mentions(conversation_id, message_id, markdown, &[])
90 .await
91 }
92
93 pub async fn reply_to_with_mentions(
94 &self,
95 conversation_id: &str,
96 message_id: &str,
97 markdown: &str,
98 mentions: &[MentionInput],
99 ) -> Result<MessageRecord> {
100 self.reply_to_with_extras(
101 conversation_id,
102 message_id,
103 markdown,
104 mentions,
105 &MessageExtras::default(),
106 )
107 .await
108 }
109
110 pub async fn reply_to_with_extras(
111 &self,
112 conversation_id: &str,
113 message_id: &str,
114 markdown: &str,
115 mentions: &[MentionInput],
116 extras: &MessageExtras,
117 ) -> Result<MessageRecord> {
118 let conversation = self.resolve(conversation_id)?;
119 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
120 let sent = match conversation {
121 Conversation::Chat => {
122 self.remote
123 .reply_with_quote(conversation_id, message_id, &html, &mentions, extras)
124 .await?
125 }
126 Conversation::Channel { team_id } => {
127 let root_id = self
128 .store
129 .messages_by_id(conversation_id, &[message_id.to_owned()])?
130 .remove(message_id)
131 .and_then(|record| record.reply_to_id)
132 .unwrap_or_else(|| message_id.to_owned());
133 self.remote
134 .reply_to_channel_message(
135 &team_id,
136 conversation_id,
137 &root_id,
138 &html,
139 &mentions,
140 extras,
141 )
142 .await?
143 }
144 };
145 self.cache_sent(conversation_id, &sent)
146 }
147
148 /// Own and not deleted. Chat messages, channel posts and channel replies alike.
149 pub fn can_edit(&self, record: &MessageRecord) -> bool {
150 self.is_own(record)
151 }
152
153 pub fn can_delete(&self, record: &MessageRecord) -> bool {
154 self.is_own(record)
155 }
156
157 fn is_own(&self, record: &MessageRecord) -> bool {
158 let my_user_id = self
159 .store
160 .meta(META_USER_ID)
161 .ok()
162 .flatten()
163 .unwrap_or_default();
164 crate::stored::can_edit(record, &my_user_id)
165 }
166
167 pub async fn post_to_channel(
168 &self,
169 channel_id: &str,
170 markdown: &str,
171 subject: Option<&str>,
172 ) -> Result<MessageRecord> {
173 self.post_to_channel_with_mentions(channel_id, markdown, subject, &[])
174 .await
175 }
176
177 pub async fn post_to_channel_with_mentions(
178 &self,
179 channel_id: &str,
180 markdown: &str,
181 subject: Option<&str>,
182 mentions: &[MentionInput],
183 ) -> Result<MessageRecord> {
184 self.post_to_channel_with_extras(
185 channel_id,
186 markdown,
187 subject,
188 mentions,
189 &MessageExtras::default(),
190 )
191 .await
192 }
193
194 pub async fn post_to_channel_with_extras(
195 &self,
196 channel_id: &str,
197 markdown: &str,
198 subject: Option<&str>,
199 mentions: &[MentionInput],
200 extras: &MessageExtras,
201 ) -> Result<MessageRecord> {
202 let conversation = self.resolve(channel_id)?;
203 let Conversation::Channel { team_id } = &conversation else {
204 return Err(Error::Unsupported("posting a root message to a chat"));
205 };
206 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
207 let sent = self
208 .remote
209 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
210 .await?;
211 self.cache_sent(channel_id, &sent)
212 }
213
214 /// Upload then share; the app uses the two steps apart so a failed share does not upload again.
215 pub async fn upload_attachment(
216 &self,
217 conversation_id: &str,
218 file_name: &str,
219 bytes: &[u8],
220 progress: impl Fn(u8) + Send + Sync,
221 ) -> Result<FileReference> {
222 let uploaded = self
223 .upload_attachment_file(conversation_id, file_name, bytes, progress)
224 .await?;
225 self.share_attachment(conversation_id, &uploaded).await?;
226 uploaded.reference().ok_or_else(missing_attachment_id)
227 }
228
229 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
230 pub async fn upload_attachment_file(
231 &self,
232 conversation_id: &str,
233 file_name: &str,
234 bytes: &[u8],
235 progress: impl Fn(u8) + Send + Sync,
236 ) -> Result<UploadedFile> {
237 let destination = match self.resolve(conversation_id)? {
238 Conversation::Chat => UploadDestination::ChatFiles,
239 Conversation::Channel { team_id } => {
240 UploadDestination::Folder(self.channel_folder(&team_id, conversation_id).await?)
241 }
242 };
243 let uploaded = self
244 .remote
245 .upload_file(&destination, file_name, bytes, &progress)
246 .await?;
247 if uploaded.reference().is_none() {
248 let _ = self.remote.delete_file(&uploaded).await;
249 return Err(missing_attachment_id());
250 }
251 Ok(uploaded)
252 }
253
254 /// Read-only for the other chat members; channels need nothing.
255 pub async fn share_attachment(
256 &self,
257 conversation_id: &str,
258 uploaded: &UploadedFile,
259 ) -> Result<()> {
260 if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
261 return Ok(());
262 }
263 let other_members = self.other_member_ids(conversation_id).await?;
264 self.remote.share_file(uploaded, &other_members).await
265 }
266
267 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
268 self.remote.delete_file(uploaded).await
269 }
270
271 async fn channel_folder(&self, team_id: &str, channel_id: &str) -> Result<graph::DriveFolder> {
272 let cached = self
273 .channel_folders
274 .lock()
275 .expect("channel folder cache poisoned")
276 .get(channel_id)
277 .cloned();
278 if let Some(folder) = cached {
279 return Ok(folder);
280 }
281 let folder = self
282 .remote
283 .channel_files_folder(team_id, channel_id)
284 .await?;
285 self.channel_folders
286 .lock()
287 .expect("channel folder cache poisoned")
288 .insert(channel_id.to_owned(), folder.clone());
289 Ok(folder)
290 }
291
292 async fn other_member_ids(&self, chat_id: &str) -> Result<Vec<String>> {
293 let my_user_id = self.my_user_id().await?;
294 let members = self
295 .store
296 .chat(chat_id)?
297 .map(|chat| chat.members)
298 .filter(|members| !members.is_empty())
299 .ok_or_else(|| graph::Error::Upload("Chat members not loaded yet.".into()))?;
300 Ok(members
301 .into_iter()
302 .filter_map(|member| member.user_id)
303 .filter(|user_id| *user_id != my_user_id)
304 .collect())
305 }
306
307 pub async fn refresh_message(
308 &self,
309 conversation_id: &str,
310 message_id: &str,
311 ) -> Result<Option<MessageRecord>> {
312 let fetched = match self.resolve(conversation_id)? {
313 Conversation::Chat => self.remote.chat_message(conversation_id, message_id).await,
314 Conversation::Channel { team_id } => {
315 self.fetch_channel_message(&team_id, conversation_id, message_id)
316 .await
317 }
318 };
319 let message = match fetched {
320 Ok(message) => message,
321 Err(error) => {
322 self.report(format!("cannot refresh a message: {error}"));
323 return Err(error);
324 }
325 };
326 let Some(record) = message_record(conversation_id, &message) else {
327 return Ok(None);
328 };
329 let delta = self.ingest(conversation_id, vec![record.clone()])?;
330 self.announce(conversation_id, !delta.is_empty());
331 Ok(Some(record))
332 }
333
334 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
335 if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
336 return Err(Error::Unsupported("marking a channel as read"));
337 }
338 let user_id = self.my_user_id().await?;
339 let tenant_id = self.my_tenant_id(conversation_id).await?;
340 self.remote
341 .mark_chat_read(conversation_id, &user_id, &tenant_id)
342 .await?;
343 self.store.mark_chat_read(conversation_id, Utc::now())?;
344 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
345 Ok(())
346 }
347
348 pub async fn set_reaction(
349 &self,
350 conversation_id: &str,
351 message_id: &str,
352 reaction_type: &str,
353 ) -> Result<()> {
354 let target = self.message_target(conversation_id, message_id)?;
355 self.remote.set_reaction(&target, reaction_type).await?;
356 self.refresh_message(conversation_id, message_id).await?;
357 Ok(())
358 }
359
360 pub async fn unset_reaction(
361 &self,
362 conversation_id: &str,
363 message_id: &str,
364 reaction_type: &str,
365 ) -> Result<()> {
366 let target = self.message_target(conversation_id, message_id)?;
367 self.remote.unset_reaction(&target, reaction_type).await?;
368 self.refresh_message(conversation_id, message_id).await?;
369 Ok(())
370 }
371
372 pub async fn edit_message(
373 &self,
374 conversation_id: &str,
375 message_id: &str,
376 markdown: &str,
377 ) -> Result<()> {
378 self.edit_message_with_mentions(conversation_id, message_id, markdown, &[])
379 .await
380 }
381
382 pub async fn edit_message_with_mentions(
383 &self,
384 conversation_id: &str,
385 message_id: &str,
386 markdown: &str,
387 mentions: &[MentionInput],
388 ) -> Result<()> {
389 let conversation = self.resolve(conversation_id)?;
390 let (mut html, mentions) = outgoing(&conversation, markdown, mentions)?;
391 let target = self.message_target(conversation_id, message_id)?;
392 let mut extras = MessageExtras::default();
393 if let Some(record) = self
394 .store
395 .messages_by_id(conversation_id, &[message_id.to_owned()])?
396 .remove(message_id)
397 {
398 let preserved = crate::stored::edit_preserved(&record);
399 html.push_str(&preserved.images_html);
400 extras.files = preserved.files;
401 extras.kept = preserved.kept;
402 }
403 self.remote
404 .edit_message(&target, &html, &mentions, &extras)
405 .await?;
406 self.refresh_message(conversation_id, message_id).await?;
407 Ok(())
408 }
409
410 pub async fn soft_delete_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
411 let target = self.message_target(conversation_id, message_id)?;
412 let user_id = self.my_user_id().await?;
413 self.remote.soft_delete_message(&user_id, &target).await?;
414 self.refresh_message(conversation_id, message_id).await?;
415 Ok(())
416 }
417
418 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
419 Ok(match self.resolve(conversation_id)? {
420 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
421 Conversation::Channel { team_id } => {
422 let root_id = self
423 .store
424 .messages_by_id(conversation_id, &[message_id.to_owned()])?
425 .remove(message_id)
426 .and_then(|record| record.reply_to_id);
427 MessageTarget::channel(&team_id, conversation_id, message_id, root_id.as_deref())
428 }
429 })
430 }
431
432 pub async fn create_one_on_one(&self, user_id: &str) -> Result<String> {
433 let my_user_id = self.my_user_id().await?;
434 let chat = self.remote.create_one_on_one(&my_user_id, user_id).await?;
435 self.store_new_chat(&chat, &my_user_id)
436 }
437
438 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
439 let my_user_id = self.my_user_id().await?;
440 let chat = self
441 .remote
442 .create_group(&my_user_id, user_ids, topic)
443 .await?;
444 self.store_new_chat(&chat, &my_user_id)
445 }
446
447 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
448 if let Some(record) = chat_record(chat, my_user_id) {
449 self.store.upsert_chats(&[record])?;
450 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
451 }
452 Ok(chat.id.clone())
453 }
454
455 fn cache_sent(&self, conversation_id: &str, sent: &graph::Message) -> Result<MessageRecord> {
456 let record = message_record(conversation_id, sent)
457 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
458 self.store.upsert_messages(std::slice::from_ref(&record))?;
459 self.update_chat_preview(std::slice::from_ref(&record))?;
460 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
461 if state
462 .newest_seen
463 .is_some_and(|newest| newest < record.created_at)
464 {
465 state.newest_seen = Some(record.created_at);
466 self.store.set_sync_state(conversation_id, &state)?;
467 }
468 self.announce(conversation_id, true);
469 Ok(record)
470 }
471
472 async fn fetch_channel_message(
473 &self,
474 team_id: &str,
475 channel_id: &str,
476 message_id: &str,
477 ) -> Result<graph::Message> {
478 let known = self
479 .store
480 .messages_by_id(channel_id, &[message_id.to_owned()])?;
481 match known
482 .get(message_id)
483 .and_then(|record| record.reply_to_id.clone())
484 {
485 Some(root_id) => {
486 self.remote
487 .channel_reply(team_id, channel_id, &root_id, message_id)
488 .await
489 }
490 None => {
491 self.remote
492 .channel_message(team_id, channel_id, message_id)
493 .await
494 }
495 }
496 }
497}
498
499fn outgoing(
500 conversation: &Conversation,
501 markdown: &str,
502 mentions: &[MentionInput],
503) -> Result<(String, Vec<OutgoingMention>)> {
504 if matches!(conversation, Conversation::Chat) {
505 ensure_allowed_in_chat(mentions)?;
506 }
507 Ok(apply_mentions(&markdown_to_html(markdown), mentions))
508}
509
510fn missing_attachment_id() -> Error {
511 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
512}