BlueGit

ict rusty-teams

Files

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

actions.rs

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