BlueGit

ict rusty-teams

Files

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

actions.rs

23a3899b History
actions.rs 24.4 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;
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 let Conversation::Channel { .. } = self.resolve(conversation_id).await? {
364 return self.mark_channel_read(conversation_id).await;
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 async fn mark_channel_read(&self, channel_id: &str) -> Result<()> {
377 let now = Utc::now();
378 let last_message_at = self
379 .store
380 .channel(channel_id)?
381 .and_then(|channel| channel.last_message_at)
382 .unwrap_or(now);
383 self.remote
384 .set_read_horizon(
385 channel_id,
386 &chatsvc::read_horizon::read_up_to(last_message_at, now),
387 )
388 .await?;
389 self.store.mark_channel_read(channel_id)?;
390 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
391 Ok(())
392 }
393
394 pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
395 let last_message_at = self
396 .store
397 .chat(chat_id)?
398 .and_then(|chat| chat.last_message_at)
399 .ok_or(Error::Unsupported(
400 "marking a chat without messages as unread",
401 ))?;
402 self.mark_unread_from(chat_id, last_message_at).await
403 }
404
405 pub async fn mark_unread_from(
406 &self,
407 chat_id: &str,
408 message_created_at: DateTime<Utc>,
409 ) -> Result<()> {
410 let last_read_at = message_created_at - Duration::milliseconds(1);
411 let user_id = self.my_user_id().await?;
412 let tenant_id = self.my_tenant_id(chat_id).await?;
413 self.remote
414 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
415 .await?;
416 self.store.mark_chat_unread(chat_id, last_read_at)?;
417 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
418 Ok(())
419 }
420
421 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
422 self.remote.set_chat_muted(chat_id, muted).await?;
423 self.store.set_chat_muted(chat_id, muted)?;
424 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
425 Ok(())
426 }
427
428 pub async fn set_channel_notifications(
429 &self,
430 channel_id: &str,
431 notifications: store::ChannelNotifications,
432 ) -> Result<()> {
433 self.remote
434 .set_channel_notifications(channel_id, notifications)
435 .await?;
436 self.store
437 .set_channel_notifications(channel_id, notifications)?;
438 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
439 Ok(())
440 }
441
442 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
443 let user_id = self.my_user_id().await?;
444 let tenant_id = self.my_tenant_id(chat_id).await?;
445 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
446 let hidden_after = self
447 .store
448 .chat(chat_id)?
449 .and_then(|chat| chat.last_message_at)
450 .unwrap_or_else(Utc::now);
451 self.with_locally_hidden(|locally| locally.hide(chat_id, hidden_after))?;
452 self.store.remove_chats(&[chat_id.to_owned()])?;
453 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
454 Ok(())
455 }
456
457 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
458 let user_id = self.my_user_id().await?;
459 let tenant_id = self.my_tenant_id(chat_id).await?;
460 self.remote
461 .unhide_chat(chat_id, &user_id, &tenant_id)
462 .await?;
463 let now = Utc::now();
464 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
465 self.refresh_sidebar_full().await?;
466 Ok(())
467 }
468
469 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
470 let user_id = self.my_user_id().await?;
471 self.remote.remove_chat_member(chat_id, &user_id).await?;
472 self.store.remove_chats(&[chat_id.to_owned()])?;
473 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
474 Ok(())
475 }
476
477 pub async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
478 self.remote.remove_chat_member(chat_id, user_id).await?;
479 if let Some(mut chat) = self.store.chat(chat_id)? {
480 chat.members
481 .retain(|member| member.user_id.as_deref() != Some(user_id));
482 self.store.upsert_chats(std::slice::from_ref(&chat))?;
483 }
484 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
485 Ok(())
486 }
487
488 pub async fn send_typing(
489 &self,
490 conversation_id: &str,
491 thread_root_id: Option<&str>,
492 active: bool,
493 ) -> Result<()> {
494 let conversation = match (self.resolve(conversation_id).await?, thread_root_id) {
495 (Conversation::Chat, _) => ConversationRef::chat(conversation_id),
496 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
497 (Conversation::Channel { .. }, Some(root_id)) => {
498 ConversationRef::channel_reply(conversation_id, root_id)
499 }
500 };
501 self.remote.send_typing(&conversation, active).await
502 }
503
504 pub async fn set_reaction(
505 &self,
506 conversation_id: &str,
507 message_id: &str,
508 reaction_type: &str,
509 ) -> Result<()> {
510 let target = self.message_target(conversation_id, message_id)?;
511 self.remote.set_reaction(&target, reaction_type).await?;
512 self.refresh_message(conversation_id, message_id).await?;
513 Ok(())
514 }
515
516 pub async fn unset_reaction(
517 &self,
518 conversation_id: &str,
519 message_id: &str,
520 reaction_type: &str,
521 ) -> Result<()> {
522 let target = self.message_target(conversation_id, message_id)?;
523 self.remote.unset_reaction(&target, reaction_type).await?;
524 self.refresh_message(conversation_id, message_id).await?;
525 Ok(())
526 }
527
528 pub async fn edit_message(
529 &self,
530 conversation_id: &str,
531 message_id: &str,
532 markdown: &str,
533 ) -> Result<()> {
534 self.edit_message_with_mentions(conversation_id, message_id, markdown, &[])
535 .await
536 }
537
538 pub async fn edit_message_with_mentions(
539 &self,
540 conversation_id: &str,
541 message_id: &str,
542 markdown: &str,
543 mentions: &[MentionInput],
544 ) -> Result<()> {
545 self.edit_message_html(
546 conversation_id,
547 message_id,
548 &markdown_to_html(markdown),
549 mentions,
550 )
551 .await
552 }
553
554 pub async fn edit_message_html(
555 &self,
556 conversation_id: &str,
557 message_id: &str,
558 html: &str,
559 mentions: &[MentionInput],
560 ) -> Result<()> {
561 let conversation = self.resolve(conversation_id).await?;
562 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
563 let target = self.message_target(conversation_id, message_id)?;
564 let mut extras = MessageExtras::default();
565 if let Some(record) = self
566 .store
567 .messages_by_id(conversation_id, &[message_id.to_owned()])?
568 .remove(message_id)
569 {
570 let preserved = crate::stored::edit_preserved(&record);
571 html.push_str(&preserved.images_html);
572 extras.files = preserved.files;
573 extras.kept = preserved.kept;
574 }
575 self.remote
576 .edit_message(&target, &html, &mentions, &extras)
577 .await?;
578 self.refresh_message(conversation_id, message_id).await?;
579 Ok(())
580 }
581
582 pub async fn soft_delete_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
583 let target = self.message_target(conversation_id, message_id)?;
584 let user_id = self.my_user_id().await?;
585 self.remote.soft_delete_message(&user_id, &target).await?;
586 self.refresh_message(conversation_id, message_id).await?;
587 Ok(())
588 }
589
590 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
591 Ok(match self.resolve_stored(conversation_id)? {
592 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
593 Conversation::Channel { team_id } => {
594 let root_id = self
595 .store
596 .messages_by_id(conversation_id, &[message_id.to_owned()])?
597 .remove(message_id)
598 .and_then(|record| record.reply_to_id);
599 MessageTarget::channel(&team_id, conversation_id, message_id, root_id.as_deref())
600 }
601 })
602 }
603
604 pub async fn create_one_on_one(&self, user_id: &str) -> Result<String> {
605 let my_user_id = self.my_user_id().await?;
606 let chat = self.remote.create_one_on_one(&my_user_id, user_id).await?;
607 self.store_new_chat(&chat, &my_user_id)
608 }
609
610 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
611 let my_user_id = self.my_user_id().await?;
612 let chat = self
613 .remote
614 .create_group(&my_user_id, user_ids, topic)
615 .await?;
616 self.store_new_chat(&chat, &my_user_id)
617 }
618
619 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
620 self.store
621 .upsert_chats(&[self.partner_chat_record(chat, my_user_id)])?;
622 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
623 Ok(chat.id.clone())
624 }
625
626 fn seed_sent_images(
627 &self,
628 record: &MessageRecord,
629 html: &str,
630 extras: &MessageExtras,
631 ) -> Result<()> {
632 let uploaded: Vec<_> = crate::stored::images(record)
633 .into_iter()
634 .filter(|image| external_image_url(&image.url).is_none())
635 .collect();
636 let order = hosted_image_order(html, extras);
637 if uploaded.len() != order.len() {
638 return Ok(());
639 }
640 let seeds: Vec<_> = uploaded
641 .iter()
642 .zip(order)
643 .map(|(image, index)| (image.key(), &extras.images[index]))
644 .collect();
645 self.seed_images(&seeds)
646 }
647
648 fn cache_sent(
649 &self,
650 conversation_id: &str,
651 sent: &graph::Message,
652 html: &str,
653 extras: &MessageExtras,
654 ) -> Result<MessageRecord> {
655 let record = message_record(conversation_id, sent)
656 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
657 let _ = self.seed_sent_images(&record, html, extras);
658 self.store.upsert_messages(std::slice::from_ref(&record))?;
659 self.update_chat_preview(std::slice::from_ref(&record))?;
660 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
661 if state
662 .newest_seen
663 .is_some_and(|newest| newest < record.created_at)
664 {
665 state.newest_seen = Some(record.created_at);
666 self.store.set_sync_state(conversation_id, &state)?;
667 }
668 self.announce(conversation_id, true);
669 Ok(record)
670 }
671
672 async fn fetch_channel_message(
673 &self,
674 team_id: &str,
675 channel_id: &str,
676 message_id: &str,
677 ) -> Result<graph::Message> {
678 let known = self
679 .store
680 .messages_by_id(channel_id, &[message_id.to_owned()])?;
681 match known
682 .get(message_id)
683 .and_then(|record| record.reply_to_id.clone())
684 {
685 Some(root_id) => {
686 self.remote
687 .channel_reply(team_id, channel_id, &root_id, message_id)
688 .await
689 }
690 None => {
691 self.remote
692 .channel_message(team_id, channel_id, message_id)
693 .await
694 }
695 }
696 }
697}
698
699fn outgoing(
700 conversation: &Conversation,
701 html: &str,
702 mentions: &[MentionInput],
703) -> Result<(String, Vec<OutgoingMention>)> {
704 if matches!(conversation, Conversation::Chat) {
705 ensure_allowed_in_chat(mentions)?;
706 }
707 Ok(apply_mentions(html, mentions))
708}
709
710fn missing_attachment_id() -> Error {
711 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
712}