BlueGit

ict rusty-teams

Files

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

actions.rs

actions.rs 23.3 KiB Download Raw
1use chatsvc::ConversationRef;
2use chrono::{DateTime, Duration, Utc};
3use graph::{
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
5 hosted_image_order,
6};
7use store::MessageRecord;
8
9use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10use crate::error::{Error, Result};
11use crate::external_image::external_image_url;
12use crate::links::LinkPreview;
13use crate::mapping::{chat_record, message_record};
14use crate::markdown::markdown_to_html;
15use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
16use crate::remote::Remote;
17
18impl<R: Remote> SyncEngine<R> {
19 pub async fn send_message(
20 &self,
21 conversation_id: &str,
22 markdown: &str,
23 thread_root_id: Option<&str>,
24 ) -> Result<MessageRecord> {
25 self.send_message_with_mentions(conversation_id, markdown, thread_root_id, &[])
26 .await
27 }
28
29 pub async fn send_message_with_mentions(
30 &self,
31 conversation_id: &str,
32 markdown: &str,
33 thread_root_id: Option<&str>,
34 mentions: &[MentionInput],
35 ) -> Result<MessageRecord> {
36 self.send_message_with_extras(
37 conversation_id,
38 &markdown_to_html(markdown),
39 thread_root_id,
40 mentions,
41 &MessageExtras::default(),
42 )
43 .await
44 }
45
46 /// `html` is the message body; mentions are matched as `@name` in it.
47 pub async fn send_message_with_extras(
48 &self,
49 conversation_id: &str,
50 html: &str,
51 thread_root_id: Option<&str>,
52 mentions: &[MentionInput],
53 extras: &MessageExtras,
54 ) -> Result<MessageRecord> {
55 let conversation = self.resolve(conversation_id).await?;
56 let (html, mentions) = outgoing(&conversation, html, mentions)?;
57 let sent = match (conversation, thread_root_id) {
58 (Conversation::Chat, None) => {
59 self.remote
60 .send_chat_message(conversation_id, &html, &mentions, extras)
61 .await?
62 }
63 (Conversation::Channel { team_id }, Some(root_id)) => {
64 self.remote
65 .reply_to_channel_message(
66 &team_id,
67 conversation_id,
68 root_id,
69 &html,
70 &mentions,
71 extras,
72 )
73 .await?
74 }
75 (Conversation::Chat, Some(_)) => {
76 return Err(Error::Unsupported("a thread reply in a chat"));
77 }
78 (Conversation::Channel { .. }, None) => {
79 return Err(Error::Unsupported(
80 "a channel send without a thread root; use post_to_channel",
81 ));
82 }
83 };
84 self.cache_sent(conversation_id, &sent, &html, extras)
85 }
86
87 /// Chat: quoted reply (Graph beta `replyWithQuote`). Channel: reply in the thread of `message_id`.
88 pub async fn reply_to(
89 &self,
90 conversation_id: &str,
91 message_id: &str,
92 markdown: &str,
93 ) -> Result<MessageRecord> {
94 self.reply_to_with_mentions(conversation_id, message_id, markdown, &[])
95 .await
96 }
97
98 pub async fn reply_to_with_mentions(
99 &self,
100 conversation_id: &str,
101 message_id: &str,
102 markdown: &str,
103 mentions: &[MentionInput],
104 ) -> Result<MessageRecord> {
105 self.reply_to_with_extras(
106 conversation_id,
107 message_id,
108 &markdown_to_html(markdown),
109 mentions,
110 &MessageExtras::default(),
111 )
112 .await
113 }
114
115 pub async fn reply_to_with_extras(
116 &self,
117 conversation_id: &str,
118 message_id: &str,
119 html: &str,
120 mentions: &[MentionInput],
121 extras: &MessageExtras,
122 ) -> Result<MessageRecord> {
123 let conversation = self.resolve(conversation_id).await?;
124 let (html, mentions) = outgoing(&conversation, html, mentions)?;
125 let sent = match conversation {
126 Conversation::Chat => {
127 self.remote
128 .reply_with_quote(conversation_id, message_id, &html, &mentions, extras)
129 .await?
130 }
131 Conversation::Channel { team_id } => {
132 let root_id = self
133 .store
134 .messages_by_id(conversation_id, &[message_id.to_owned()])?
135 .remove(message_id)
136 .and_then(|record| record.reply_to_id)
137 .unwrap_or_else(|| message_id.to_owned());
138 self.remote
139 .reply_to_channel_message(
140 &team_id,
141 conversation_id,
142 &root_id,
143 &html,
144 &mentions,
145 extras,
146 )
147 .await?
148 }
149 };
150 self.cache_sent(conversation_id, &sent, &html, extras)
151 }
152
153 /// Own and not deleted. Chat messages, channel posts and channel replies alike.
154 pub fn can_edit(&self, record: &MessageRecord) -> bool {
155 self.is_own(record)
156 }
157
158 pub fn can_delete(&self, record: &MessageRecord) -> bool {
159 self.is_own(record)
160 }
161
162 fn is_own(&self, record: &MessageRecord) -> bool {
163 let my_user_id = self
164 .store
165 .meta(META_USER_ID)
166 .ok()
167 .flatten()
168 .unwrap_or_default();
169 crate::stored::can_edit(record, &my_user_id)
170 }
171
172 pub async fn post_to_channel(
173 &self,
174 channel_id: &str,
175 markdown: &str,
176 subject: Option<&str>,
177 ) -> Result<MessageRecord> {
178 self.post_to_channel_with_mentions(channel_id, markdown, subject, &[])
179 .await
180 }
181
182 pub async fn post_to_channel_with_mentions(
183 &self,
184 channel_id: &str,
185 markdown: &str,
186 subject: Option<&str>,
187 mentions: &[MentionInput],
188 ) -> Result<MessageRecord> {
189 self.post_to_channel_with_extras(
190 channel_id,
191 &markdown_to_html(markdown),
192 subject,
193 mentions,
194 &MessageExtras::default(),
195 )
196 .await
197 }
198
199 pub async fn post_to_channel_with_extras(
200 &self,
201 channel_id: &str,
202 html: &str,
203 subject: Option<&str>,
204 mentions: &[MentionInput],
205 extras: &MessageExtras,
206 ) -> Result<MessageRecord> {
207 let conversation = self.resolve(channel_id).await?;
208 let Conversation::Channel { team_id } = &conversation else {
209 return Err(Error::Unsupported("posting a root message to a chat"));
210 };
211 let (html, mentions) = outgoing(&conversation, html, mentions)?;
212 let sent = self
213 .remote
214 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
215 .await?;
216 self.cache_sent(channel_id, &sent, &html, extras)
217 }
218
219 /// Upload then share; the app uses the two steps apart so a failed share does not upload again.
220 pub async fn upload_attachment(
221 &self,
222 conversation_id: &str,
223 file_name: &str,
224 bytes: &[u8],
225 progress: impl Fn(u8) + Send + Sync,
226 ) -> Result<FileReference> {
227 let uploaded = self
228 .upload_attachment_file(conversation_id, file_name, bytes, progress)
229 .await?;
230 self.share_attachment(conversation_id, &uploaded).await?;
231 uploaded.reference().ok_or_else(missing_attachment_id)
232 }
233
234 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
235 pub async fn upload_attachment_file(
236 &self,
237 conversation_id: &str,
238 file_name: &str,
239 bytes: &[u8],
240 progress: impl Fn(u8) + Send + Sync,
241 ) -> Result<UploadedFile> {
242 let destination = match self.resolve(conversation_id).await? {
243 Conversation::Chat => UploadDestination::ChatFiles,
244 Conversation::Channel { team_id } => {
245 UploadDestination::Folder(self.channel_folder(&team_id, conversation_id).await?)
246 }
247 };
248 let uploaded = self
249 .remote
250 .upload_file(&destination, file_name, bytes, &progress)
251 .await?;
252 if uploaded.reference().is_none() {
253 let _ = self.remote.delete_file(&uploaded).await;
254 return Err(missing_attachment_id());
255 }
256 Ok(uploaded)
257 }
258
259 /// Read-only for the other chat members; channels need nothing.
260 pub async fn share_attachment(
261 &self,
262 conversation_id: &str,
263 uploaded: &UploadedFile,
264 ) -> Result<()> {
265 if !matches!(self.resolve(conversation_id).await?, Conversation::Chat) {
266 return Ok(());
267 }
268 let other_members = self.other_member_ids(conversation_id).await?;
269 self.remote.share_file(uploaded, &other_members).await
270 }
271
272 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
273 self.remote.delete_file(uploaded).await
274 }
275
276 async fn channel_folder(&self, team_id: &str, channel_id: &str) -> Result<graph::DriveFolder> {
277 let cached = self
278 .channel_folders
279 .lock()
280 .expect("channel folder cache poisoned")
281 .get(channel_id)
282 .cloned();
283 if let Some(folder) = cached {
284 return Ok(folder);
285 }
286 let folder = self
287 .remote
288 .channel_files_folder(team_id, channel_id)
289 .await?;
290 self.channel_folders
291 .lock()
292 .expect("channel folder cache poisoned")
293 .insert(channel_id.to_owned(), folder.clone());
294 Ok(folder)
295 }
296
297 async fn other_member_ids(&self, chat_id: &str) -> Result<Vec<String>> {
298 let my_user_id = self.my_user_id().await?;
299 let members = self
300 .store
301 .chat(chat_id)?
302 .map(|chat| chat.members)
303 .filter(|members| !members.is_empty())
304 .ok_or_else(|| graph::Error::Upload("Chat members not loaded yet.".into()))?;
305 Ok(members
306 .into_iter()
307 .filter_map(|member| member.user_id)
308 .filter(|user_id| *user_id != my_user_id)
309 .collect())
310 }
311
312 pub async fn refresh_message(
313 &self,
314 conversation_id: &str,
315 message_id: &str,
316 ) -> Result<Option<MessageRecord>> {
317 let fetched = match self.resolve(conversation_id).await? {
318 Conversation::Chat => self.remote.chat_message(conversation_id, message_id).await,
319 Conversation::Channel { team_id } => {
320 self.fetch_channel_message(&team_id, conversation_id, message_id)
321 .await
322 }
323 };
324 let message = match fetched {
325 Ok(message) => message,
326 Err(error) => {
327 self.report(format!("cannot refresh a message: {error}"));
328 return Err(error);
329 }
330 };
331 let Some(record) = message_record(conversation_id, &message) else {
332 return Ok(None);
333 };
334 let mut record = record;
335 self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))
336 .await;
337 let delta = self.ingest(conversation_id, vec![record.clone()])?;
338 self.announce_stored_late(conversation_id, &delta);
339 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
340 self.announce(conversation_id, !delta.is_empty() || links_changed);
341 Ok(Some(record))
342 }
343
344 pub async fn attach_link_preview(
345 &self,
346 conversation_id: &str,
347 message_id: &str,
348 preview: &LinkPreview,
349 ) -> Result<()> {
350 let target = self.message_target(conversation_id, message_id)?;
351 let links_json = preview.links_json();
352 self.remote.set_message_links(&target, &links_json).await?;
353 if self
354 .store
355 .set_message_links(conversation_id, message_id, &links_json)?
356 {
357 self.announce(conversation_id, true);
358 }
359 Ok(())
360 }
361
362 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
363 if !matches!(self.resolve(conversation_id).await?, Conversation::Chat) {
364 return Err(Error::Unsupported("marking a channel as read"));
365 }
366 let user_id = self.my_user_id().await?;
367 let tenant_id = self.my_tenant_id(conversation_id).await?;
368 self.remote
369 .mark_chat_read(conversation_id, &user_id, &tenant_id)
370 .await?;
371 self.store.mark_chat_read(conversation_id, Utc::now())?;
372 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
373 Ok(())
374 }
375
376 pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
377 let last_message_at = self
378 .store
379 .chat(chat_id)?
380 .and_then(|chat| chat.last_message_at)
381 .ok_or(Error::Unsupported(
382 "marking a chat without messages as unread",
383 ))?;
384 self.mark_unread_from(chat_id, last_message_at).await
385 }
386
387 pub async fn mark_unread_from(
388 &self,
389 chat_id: &str,
390 message_created_at: DateTime<Utc>,
391 ) -> Result<()> {
392 let last_read_at = message_created_at - Duration::milliseconds(1);
393 let user_id = self.my_user_id().await?;
394 let tenant_id = self.my_tenant_id(chat_id).await?;
395 self.remote
396 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
397 .await?;
398 self.store.mark_chat_unread(chat_id, last_read_at)?;
399 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
400 Ok(())
401 }
402
403 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
404 self.remote.set_chat_muted(chat_id, muted).await?;
405 self.store.set_chat_muted(chat_id, muted)?;
406 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
407 Ok(())
408 }
409
410 pub async fn set_channel_notifications(
411 &self,
412 channel_id: &str,
413 notifications: store::ChannelNotifications,
414 ) -> Result<()> {
415 self.remote
416 .set_channel_notifications(channel_id, notifications)
417 .await?;
418 self.store
419 .set_channel_notifications(channel_id, notifications)?;
420 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
421 Ok(())
422 }
423
424 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
425 let user_id = self.my_user_id().await?;
426 let tenant_id = self.my_tenant_id(chat_id).await?;
427 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
428 let hidden_after = self
429 .store
430 .chat(chat_id)?
431 .and_then(|chat| chat.last_message_at)
432 .unwrap_or_else(Utc::now);
433 self.with_locally_hidden(|locally| locally.hide(chat_id, hidden_after))?;
434 self.store.remove_chats(&[chat_id.to_owned()])?;
435 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
436 Ok(())
437 }
438
439 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
440 let user_id = self.my_user_id().await?;
441 let tenant_id = self.my_tenant_id(chat_id).await?;
442 self.remote
443 .unhide_chat(chat_id, &user_id, &tenant_id)
444 .await?;
445 let now = Utc::now();
446 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
447 self.refresh_sidebar_full().await?;
448 Ok(())
449 }
450
451 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
452 let user_id = self.my_user_id().await?;
453 self.remote.leave_chat(chat_id, &user_id).await?;
454 self.store.remove_chats(&[chat_id.to_owned()])?;
455 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
456 Ok(())
457 }
458
459 pub async fn send_typing(
460 &self,
461 conversation_id: &str,
462 thread_root_id: Option<&str>,
463 active: bool,
464 ) -> Result<()> {
465 let conversation = match (self.resolve(conversation_id).await?, thread_root_id) {
466 (Conversation::Chat, _) => ConversationRef::chat(conversation_id),
467 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
468 (Conversation::Channel { .. }, Some(root_id)) => {
469 ConversationRef::channel_reply(conversation_id, root_id)
470 }
471 };
472 self.remote.send_typing(&conversation, active).await
473 }
474
475 pub async fn set_reaction(
476 &self,
477 conversation_id: &str,
478 message_id: &str,
479 reaction_type: &str,
480 ) -> Result<()> {
481 let target = self.message_target(conversation_id, message_id)?;
482 self.remote.set_reaction(&target, reaction_type).await?;
483 self.refresh_message(conversation_id, message_id).await?;
484 Ok(())
485 }
486
487 pub async fn unset_reaction(
488 &self,
489 conversation_id: &str,
490 message_id: &str,
491 reaction_type: &str,
492 ) -> Result<()> {
493 let target = self.message_target(conversation_id, message_id)?;
494 self.remote.unset_reaction(&target, reaction_type).await?;
495 self.refresh_message(conversation_id, message_id).await?;
496 Ok(())
497 }
498
499 pub async fn edit_message(
500 &self,
501 conversation_id: &str,
502 message_id: &str,
503 markdown: &str,
504 ) -> Result<()> {
505 self.edit_message_with_mentions(conversation_id, message_id, markdown, &[])
506 .await
507 }
508
509 pub async fn edit_message_with_mentions(
510 &self,
511 conversation_id: &str,
512 message_id: &str,
513 markdown: &str,
514 mentions: &[MentionInput],
515 ) -> Result<()> {
516 self.edit_message_html(
517 conversation_id,
518 message_id,
519 &markdown_to_html(markdown),
520 mentions,
521 )
522 .await
523 }
524
525 pub async fn edit_message_html(
526 &self,
527 conversation_id: &str,
528 message_id: &str,
529 html: &str,
530 mentions: &[MentionInput],
531 ) -> Result<()> {
532 let conversation = self.resolve(conversation_id).await?;
533 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
534 let target = self.message_target(conversation_id, message_id)?;
535 let mut extras = MessageExtras::default();
536 if let Some(record) = self
537 .store
538 .messages_by_id(conversation_id, &[message_id.to_owned()])?
539 .remove(message_id)
540 {
541 let preserved = crate::stored::edit_preserved(&record);
542 html.push_str(&preserved.images_html);
543 extras.files = preserved.files;
544 extras.kept = preserved.kept;
545 }
546 self.remote
547 .edit_message(&target, &html, &mentions, &extras)
548 .await?;
549 self.refresh_message(conversation_id, message_id).await?;
550 Ok(())
551 }
552
553 pub async fn soft_delete_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
554 let target = self.message_target(conversation_id, message_id)?;
555 let user_id = self.my_user_id().await?;
556 self.remote.soft_delete_message(&user_id, &target).await?;
557 self.refresh_message(conversation_id, message_id).await?;
558 Ok(())
559 }
560
561 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
562 Ok(match self.resolve_stored(conversation_id)? {
563 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
564 Conversation::Channel { team_id } => {
565 let root_id = self
566 .store
567 .messages_by_id(conversation_id, &[message_id.to_owned()])?
568 .remove(message_id)
569 .and_then(|record| record.reply_to_id);
570 MessageTarget::channel(&team_id, conversation_id, message_id, root_id.as_deref())
571 }
572 })
573 }
574
575 pub async fn create_one_on_one(&self, user_id: &str) -> Result<String> {
576 let my_user_id = self.my_user_id().await?;
577 let chat = self.remote.create_one_on_one(&my_user_id, user_id).await?;
578 self.store_new_chat(&chat, &my_user_id)
579 }
580
581 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
582 let my_user_id = self.my_user_id().await?;
583 let chat = self
584 .remote
585 .create_group(&my_user_id, user_ids, topic)
586 .await?;
587 self.store_new_chat(&chat, &my_user_id)
588 }
589
590 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
591 self.store.upsert_chats(&[chat_record(chat, my_user_id)])?;
592 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
593 Ok(chat.id.clone())
594 }
595
596 fn seed_sent_images(
597 &self,
598 record: &MessageRecord,
599 html: &str,
600 extras: &MessageExtras,
601 ) -> Result<()> {
602 let uploaded: Vec<_> = crate::stored::images(record)
603 .into_iter()
604 .filter(|image| external_image_url(&image.url).is_none())
605 .collect();
606 let order = hosted_image_order(html, extras);
607 if uploaded.len() != order.len() {
608 return Ok(());
609 }
610 let seeds: Vec<_> = uploaded
611 .iter()
612 .zip(order)
613 .map(|(image, index)| (image.key(), &extras.images[index]))
614 .collect();
615 self.seed_images(&seeds)
616 }
617
618 fn cache_sent(
619 &self,
620 conversation_id: &str,
621 sent: &graph::Message,
622 html: &str,
623 extras: &MessageExtras,
624 ) -> Result<MessageRecord> {
625 let record = message_record(conversation_id, sent)
626 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
627 let _ = self.seed_sent_images(&record, html, extras);
628 self.store.upsert_messages(std::slice::from_ref(&record))?;
629 self.update_chat_preview(std::slice::from_ref(&record))?;
630 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
631 if state
632 .newest_seen
633 .is_some_and(|newest| newest < record.created_at)
634 {
635 state.newest_seen = Some(record.created_at);
636 self.store.set_sync_state(conversation_id, &state)?;
637 }
638 self.announce(conversation_id, true);
639 Ok(record)
640 }
641
642 async fn fetch_channel_message(
643 &self,
644 team_id: &str,
645 channel_id: &str,
646 message_id: &str,
647 ) -> Result<graph::Message> {
648 let known = self
649 .store
650 .messages_by_id(channel_id, &[message_id.to_owned()])?;
651 match known
652 .get(message_id)
653 .and_then(|record| record.reply_to_id.clone())
654 {
655 Some(root_id) => {
656 self.remote
657 .channel_reply(team_id, channel_id, &root_id, message_id)
658 .await
659 }
660 None => {
661 self.remote
662 .channel_message(team_id, channel_id, message_id)
663 .await
664 }
665 }
666 }
667}
668
669fn outgoing(
670 conversation: &Conversation,
671 html: &str,
672 mentions: &[MentionInput],
673) -> Result<(String, Vec<OutgoingMention>)> {
674 if matches!(conversation, Conversation::Chat) {
675 ensure_allowed_in_chat(mentions)?;
676 }
677 Ok(apply_mentions(html, mentions))
678}
679
680fn missing_attachment_id() -> Error {
681 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
682}