BlueGit

ict rusty-teams

Files

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

actions.rs

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