BlueGit

ict rusty-teams

Files

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

actions.rs

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