BlueGit

ict rusty-teams

Files

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

actions.rs

actions.rs 35.0 KiB Download Raw
1use chatsvc::{ConversationRef, read_horizon};
2use chrono::{DateTime, Duration, Utc};
3use graph::{
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, Recipient, UploadDestination,
5 UploadedFile, 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::hidden_chats::cleared_until_ms;
13use crate::links::LinkPreview;
14use crate::mapping::message_record;
15use crate::markdown::markdown_to_html;
16use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
17use crate::notes_chat::is_notes_chat;
18use crate::remote::Remote;
19use crate::scheduled::NOTES_CHAT_ID;
20use crate::teams_quote::{mention_entries, teams_quote};
21
22impl<R: Remote> SyncEngine<R> {
23 pub async fn send_message(
24 &self,
25 conversation_id: &str,
26 markdown: &str,
27 thread_root_id: Option<&str>,
28 ) -> Result<MessageRecord> {
29 self.send_message_with_mentions(conversation_id, markdown, thread_root_id, &[])
30 .await
31 }
32
33 pub async fn send_message_with_mentions(
34 &self,
35 conversation_id: &str,
36 markdown: &str,
37 thread_root_id: Option<&str>,
38 mentions: &[MentionInput],
39 ) -> Result<MessageRecord> {
40 self.send_message_with_extras(
41 conversation_id,
42 &markdown_to_html(markdown),
43 thread_root_id,
44 mentions,
45 &MessageExtras::default(),
46 )
47 .await
48 }
49
50 /// `html` is the message body; mentions are matched as `@name` in it.
51 pub async fn send_message_with_extras(
52 &self,
53 conversation_id: &str,
54 html: &str,
55 thread_root_id: Option<&str>,
56 mentions: &[MentionInput],
57 extras: &MessageExtras,
58 ) -> Result<MessageRecord> {
59 let conversation = self.resolve(conversation_id).await?;
60 let (html, mentions) = outgoing(&conversation, html, mentions)?;
61 let sent = match (conversation, thread_root_id) {
62 (Conversation::Chat, None) => {
63 let sent = self
64 .send_via_chatsvc(
65 &ConversationRef::chat(conversation_id),
66 None,
67 &html,
68 &mentions,
69 extras,
70 None,
71 )
72 .await?;
73 return self.cache_sent(conversation_id, &sent.message, &html, extras);
74 }
75 (Conversation::Channel { team_id }, Some(root_id)) => {
76 self.remote
77 .reply_to_channel_message(
78 &team_id,
79 conversation_id,
80 root_id,
81 &html,
82 &mentions,
83 extras,
84 )
85 .await?
86 }
87 (Conversation::Chat, Some(_)) => {
88 return Err(Error::Unsupported("a thread reply in a chat"));
89 }
90 (Conversation::Channel { .. }, None) => {
91 return Err(Error::Unsupported(
92 "a channel send without a thread root; use post_to_channel",
93 ));
94 }
95 };
96 self.cache_sent(conversation_id, &sent, &html, extras)
97 }
98
99 /// Quoted reply in Teams' chatsvc shape; channels answer in the thread of `message_id`.
100 pub async fn reply_to(
101 &self,
102 conversation_id: &str,
103 message_id: &str,
104 markdown: &str,
105 ) -> Result<MessageRecord> {
106 self.reply_to_with_mentions(conversation_id, message_id, markdown, &[])
107 .await
108 }
109
110 pub async fn reply_to_with_mentions(
111 &self,
112 conversation_id: &str,
113 message_id: &str,
114 markdown: &str,
115 mentions: &[MentionInput],
116 ) -> Result<MessageRecord> {
117 self.reply_to_with_extras(
118 conversation_id,
119 message_id,
120 &markdown_to_html(markdown),
121 mentions,
122 &MessageExtras::default(),
123 )
124 .await
125 }
126
127 pub async fn reply_to_with_extras(
128 &self,
129 conversation_id: &str,
130 message_id: &str,
131 html: &str,
132 mentions: &[MentionInput],
133 extras: &MessageExtras,
134 ) -> Result<MessageRecord> {
135 let conversation = self.resolve(conversation_id).await?;
136 let (html, mentions) = outgoing(&conversation, html, mentions)?;
137 let quoted = self
138 .store
139 .messages_by_id(conversation_id, &[message_id.to_owned()])?
140 .remove(message_id);
141 let (chatsvc_conversation, root_id) = match &conversation {
142 Conversation::Chat => (ConversationRef::chat(conversation_id), None),
143 Conversation::Channel { .. } => {
144 let root_id = quoted
145 .as_ref()
146 .and_then(|record| record.reply_to_id.clone())
147 .unwrap_or_else(|| message_id.to_owned());
148 (
149 ConversationRef::channel_reply(conversation_id, &root_id),
150 Some(root_id),
151 )
152 }
153 };
154 if let Some(quoted) = &quoted
155 && let Some((sent, html)) = self
156 .quote_reply_via_chatsvc(
157 &chatsvc_conversation,
158 root_id.as_deref(),
159 quoted,
160 &html,
161 &mentions,
162 extras,
163 )
164 .await?
165 {
166 return self.cache_sent(conversation_id, &sent, &html, extras);
167 }
168 let sent = match (&conversation, &root_id) {
169 (Conversation::Channel { team_id }, Some(root_id)) => {
170 self.remote
171 .reply_to_channel_message(
172 team_id,
173 conversation_id,
174 root_id,
175 &html,
176 &mentions,
177 extras,
178 )
179 .await?
180 }
181 _ => {
182 self.send_via_chatsvc(&chatsvc_conversation, None, &html, &mentions, extras, None)
183 .await?
184 .message
185 }
186 };
187 self.cache_sent(conversation_id, &sent, &html, extras)
188 }
189
190 /// Own and not deleted. Chat messages, channel posts and channel replies alike.
191 pub fn can_edit(&self, record: &MessageRecord) -> bool {
192 self.is_own(record)
193 }
194
195 pub fn can_delete(&self, record: &MessageRecord) -> bool {
196 self.is_own(record)
197 }
198
199 fn is_own(&self, record: &MessageRecord) -> bool {
200 let my_user_id = self
201 .store
202 .meta(META_USER_ID)
203 .ok()
204 .flatten()
205 .unwrap_or_default();
206 crate::stored::can_edit(record, &my_user_id)
207 }
208
209 pub async fn post_to_channel(
210 &self,
211 channel_id: &str,
212 markdown: &str,
213 subject: Option<&str>,
214 ) -> Result<MessageRecord> {
215 self.post_to_channel_with_mentions(channel_id, markdown, subject, &[])
216 .await
217 }
218
219 pub async fn post_to_channel_with_mentions(
220 &self,
221 channel_id: &str,
222 markdown: &str,
223 subject: Option<&str>,
224 mentions: &[MentionInput],
225 ) -> Result<MessageRecord> {
226 self.post_to_channel_with_extras(
227 channel_id,
228 &markdown_to_html(markdown),
229 subject,
230 mentions,
231 &MessageExtras::default(),
232 )
233 .await
234 }
235
236 pub async fn post_to_channel_with_extras(
237 &self,
238 channel_id: &str,
239 html: &str,
240 subject: Option<&str>,
241 mentions: &[MentionInput],
242 extras: &MessageExtras,
243 ) -> Result<MessageRecord> {
244 let conversation = self.resolve(channel_id).await?;
245 let Conversation::Channel { team_id } = &conversation else {
246 return Err(Error::Unsupported("posting a root message to a chat"));
247 };
248 let (html, mentions) = outgoing(&conversation, html, mentions)?;
249 let sent = self
250 .remote
251 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
252 .await?;
253 self.cache_sent(channel_id, &sent, &html, extras)
254 }
255
256 /// Upload then share; the app uses the two steps apart so a failed share does not upload again.
257 pub async fn upload_attachment(
258 &self,
259 conversation_id: &str,
260 file_name: &str,
261 bytes: &[u8],
262 progress: impl Fn(u8) + Send + Sync,
263 ) -> Result<FileReference> {
264 let uploaded = self
265 .upload_attachment_file(conversation_id, file_name, bytes, progress)
266 .await?;
267 let link = self.share_attachment(conversation_id, &uploaded).await?;
268 let mut reference = uploaded.reference().ok_or_else(missing_attachment_id)?;
269 if let Some(link) = link.filter(|link| !link.is_empty()) {
270 reference.content_url = link;
271 }
272 Ok(reference)
273 }
274
275 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
276 pub async fn upload_attachment_file(
277 &self,
278 conversation_id: &str,
279 file_name: &str,
280 bytes: &[u8],
281 progress: impl Fn(u8) + Send + Sync,
282 ) -> Result<UploadedFile> {
283 let destination = match self.resolve(conversation_id).await? {
284 Conversation::Chat => UploadDestination::ChatFiles,
285 Conversation::Channel { team_id } => {
286 UploadDestination::Folder(self.channel_folder(&team_id, conversation_id).await?)
287 }
288 };
289 let uploaded = self
290 .remote
291 .upload_file(&destination, file_name, bytes, &progress)
292 .await?;
293 if uploaded.reference().is_none() {
294 let _ = self.remote.delete_file(&uploaded).await;
295 return Err(missing_attachment_id());
296 }
297 Ok(uploaded)
298 }
299
300 /// Read-only for the other chat members; channels need nothing.
301 /// `Some` is a sharing link that the chat message should carry instead of the item URL.
302 pub async fn share_attachment(
303 &self,
304 conversation_id: &str,
305 uploaded: &UploadedFile,
306 ) -> Result<Option<String>> {
307 if !matches!(self.resolve(conversation_id).await?, Conversation::Chat) {
308 return Ok(None);
309 }
310 let other_members = self.other_member_ids(conversation_id).await?;
311 let recipients = if uploaded.home_drive {
312 let emails = self.member_emails(conversation_id, &other_members).await?;
313 // Bots and members Graph lists without an email cannot be invited in the home
314 // tenant. Sending then would post a file nobody can open, with no notice.
315 if emails.is_empty() && !other_members.is_empty() {
316 return Err(graph::Error::SharingDenied(
317 "no chat member has an email the home tenant can invite".into(),
318 )
319 .into());
320 }
321 emails
322 } else {
323 other_members.into_iter().map(Recipient::ObjectId).collect()
324 };
325 self.remote.share_file(uploaded, &recipients).await
326 }
327
328 /// The home tenant does not know the guest org's user ids, so a file there is shared by email.
329 /// Members without an email, such as bots, cannot be invited and are left out.
330 async fn member_emails(&self, chat_id: &str, user_ids: &[String]) -> Result<Vec<Recipient>> {
331 let members = self.remote.chat_members(chat_id).await?;
332 Ok(members
333 .into_iter()
334 .filter(|member| {
335 member
336 .user_id
337 .as_ref()
338 .is_some_and(|user_id| user_ids.contains(user_id))
339 })
340 .filter_map(|member| member.email.map(Recipient::Email))
341 .collect())
342 }
343
344 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
345 self.remote.delete_file(uploaded).await
346 }
347
348 async fn channel_folder(&self, team_id: &str, channel_id: &str) -> Result<graph::DriveFolder> {
349 let cached = self
350 .channel_folders
351 .lock()
352 .expect("channel folder cache poisoned")
353 .get(channel_id)
354 .cloned();
355 if let Some(folder) = cached {
356 return Ok(folder);
357 }
358 let folder = self
359 .remote
360 .channel_files_folder(team_id, channel_id)
361 .await?;
362 self.channel_folders
363 .lock()
364 .expect("channel folder cache poisoned")
365 .insert(channel_id.to_owned(), folder.clone());
366 Ok(folder)
367 }
368
369 async fn other_member_ids(&self, chat_id: &str) -> Result<Vec<String>> {
370 if chat_id == NOTES_CHAT_ID {
371 return Ok(Vec::new());
372 }
373 let my_user_id = self.my_user_id().await?;
374 let members = self
375 .store
376 .chat(chat_id)?
377 .map(|chat| chat.members)
378 .filter(|members| !members.is_empty())
379 .ok_or_else(|| graph::Error::Upload("Chat members not loaded yet.".into()))?;
380 Ok(members
381 .into_iter()
382 .filter_map(|member| member.user_id)
383 .filter(|user_id| *user_id != my_user_id)
384 .collect())
385 }
386
387 pub async fn refresh_message(
388 &self,
389 conversation_id: &str,
390 message_id: &str,
391 ) -> Result<Option<MessageRecord>> {
392 let fetched = match self.resolve(conversation_id).await? {
393 Conversation::Chat => self.remote.chat_message(conversation_id, message_id).await,
394 Conversation::Channel { team_id } => {
395 self.fetch_channel_message(&team_id, conversation_id, message_id)
396 .await
397 }
398 };
399 let message = match fetched {
400 Ok(message) => message,
401 Err(error) => {
402 self.report(format!("cannot refresh a message: {error}"));
403 return Err(error);
404 }
405 };
406 let Some(record) = message_record(conversation_id, &message) else {
407 return Ok(None);
408 };
409 let mut record = record;
410 self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))
411 .await;
412 let delta = self.ingest(conversation_id, vec![record.clone()])?;
413 self.announce_stored_late(conversation_id, &delta);
414 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
415 self.announce(conversation_id, !delta.is_empty() || links_changed);
416 Ok(Some(record))
417 }
418
419 pub async fn open_post(
420 &self,
421 conversation_id: &str,
422 message_id: &str,
423 ) -> Result<Option<OpenedPost>> {
424 let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
425 return Err(Error::Unsupported("opening a post of a chat"));
426 };
427 let root_ids = [message_id.to_owned()];
428 let (fetched, replies) = tokio::join!(
429 self.fetch_channel_message(&team_id, conversation_id, message_id),
430 self.remote
431 .channel_replies(&team_id, conversation_id, &root_ids)
432 );
433 let message = match fetched {
434 Ok(message) => message,
435 Err(error) => {
436 self.report(format!("cannot open a post: {error}"));
437 return Err(error);
438 }
439 };
440 let Some(record) = message_record(conversation_id, &message) else {
441 return Ok(None);
442 };
443 let replies_loaded = record.reply_to_id.is_none()
444 && replies
445 .as_ref()
446 .is_ok_and(|listings| listings.iter().all(Result::is_ok));
447 let mut records = vec![record];
448 if replies_loaded {
449 records.extend(
450 replies
451 .into_iter()
452 .flatten()
453 .flatten()
454 .flatten()
455 .filter_map(|reply| message_record(conversation_id, &reply)),
456 );
457 }
458 self.apply_chat_emotions(conversation_id, &mut records)
459 .await;
460 let mut record = records[0].clone();
461 let delta = self.ingest(conversation_id, records)?;
462 self.announce_stored_late(conversation_id, &delta);
463 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
464 self.announce(conversation_id, !delta.is_empty() || links_changed);
465 Ok(Some(OpenedPost {
466 record,
467 replies_loaded,
468 }))
469 }
470
471 pub async fn attach_link_preview(
472 &self,
473 conversation_id: &str,
474 message_id: &str,
475 preview: &LinkPreview,
476 ) -> Result<()> {
477 let target = self.message_target(conversation_id, message_id)?;
478 let links_json = preview.links_json();
479 if self
480 .store
481 .set_message_links(conversation_id, message_id, &links_json)?
482 {
483 self.announce(conversation_id, true);
484 }
485 self.remote.set_message_links(&target, &links_json).await
486 }
487
488 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
489 if let Conversation::Channel { .. } = self.resolve(conversation_id).await? {
490 return self.mark_channel_read(conversation_id).await;
491 }
492 let now = Utc::now();
493 let last_message_at = self
494 .store
495 .chat(conversation_id)?
496 .and_then(|chat| chat.last_message_at)
497 .unwrap_or(now);
498 self.remote
499 .set_read_horizon(
500 conversation_id,
501 &read_horizon::read_up_to(last_message_at, now),
502 )
503 .await?;
504 if is_notes_chat(conversation_id) || self.has_unread_bookmark(conversation_id) {
505 self.remote
506 .set_read_bookmark(conversation_id, &read_horizon::cleared_bookmark(now))
507 .await?;
508 }
509 self.store.mark_chat_read(conversation_id, now)?;
510 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
511 Ok(())
512 }
513
514 async fn mark_channel_read(&self, channel_id: &str) -> Result<()> {
515 let now = Utc::now();
516 let last_message_at = self
517 .store
518 .channel(channel_id)?
519 .and_then(|channel| channel.last_message_at)
520 .unwrap_or(now);
521 self.remote
522 .set_read_horizon(
523 channel_id,
524 &chatsvc::read_horizon::read_up_to(last_message_at, now),
525 )
526 .await?;
527 self.store.mark_channel_read(channel_id)?;
528 self.store.clear_channel_mentions(channel_id)?;
529 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
530 Ok(())
531 }
532
533 pub async fn mark_all_channels_read(&self) -> Result<()> {
534 let horizon = self
535 .remote
536 .mark_all_channels_read(Utc::now().timestamp_millis())
537 .await?;
538 *self.app_channel_horizon_ms.lock().unwrap() = horizon.channel_ms;
539 self.store.mark_all_channels_read()?;
540 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
541 Ok(())
542 }
543
544 pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
545 let last_message_at = self
546 .store
547 .chat(chat_id)?
548 .and_then(|chat| chat.last_message_at)
549 .ok_or(Error::Unsupported(
550 "marking a chat without messages as unread",
551 ))?;
552 self.mark_unread_from(chat_id, last_message_at).await
553 }
554
555 pub async fn mark_unread_from(
556 &self,
557 chat_id: &str,
558 message_created_at: DateTime<Utc>,
559 ) -> Result<()> {
560 let last_read_at = message_created_at - Duration::milliseconds(1);
561 let bookmark = read_horizon::bookmark_at(
562 message_created_at,
563 &self.message_id_at(chat_id, message_created_at)?,
564 Utc::now(),
565 );
566 self.remote.set_read_bookmark(chat_id, &bookmark).await?;
567 self.store.mark_chat_unread(chat_id, last_read_at)?;
568 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
569 Ok(())
570 }
571
572 fn has_unread_bookmark(&self, chat_id: &str) -> bool {
573 self.chat_states
574 .lock()
575 .unwrap()
576 .get(chat_id)
577 .is_some_and(|state| state.read.bookmark_message_set)
578 }
579
580 fn message_id_at(&self, chat_id: &str, created_at: DateTime<Utc>) -> Result<String> {
581 Ok(self
582 .store
583 .messages_between(chat_id, created_at, created_at)?
584 .into_iter()
585 .next()
586 .map(|message| message.message_id)
587 .unwrap_or_else(|| created_at.timestamp_millis().to_string()))
588 }
589
590 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
591 self.remote.set_chat_muted(chat_id, muted).await?;
592 self.store.set_chat_muted(chat_id, muted)?;
593 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
594 Ok(())
595 }
596
597 pub async fn set_channel_notifications(
598 &self,
599 channel_id: &str,
600 notifications: store::ChannelNotifications,
601 ) -> Result<()> {
602 self.remote
603 .set_channel_notifications(channel_id, notifications)
604 .await?;
605 self.store
606 .set_channel_notifications(channel_id, notifications)?;
607 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
608 Ok(())
609 }
610
611 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
612 if is_notes_chat(chat_id) {
613 self.remote
614 .set_chat_hidden_at(chat_id, Some(Utc::now().timestamp_millis()))
615 .await?;
616 self.store.remove_chats(&[chat_id.to_owned()])?;
617 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
618 return Ok(());
619 }
620 self.remote
621 .set_chat_hidden_at(chat_id, Some(Utc::now().timestamp_millis()))
622 .await?;
623 let hidden_after = self
624 .store
625 .chat(chat_id)?
626 .and_then(|chat| chat.last_message_at)
627 .unwrap_or_else(Utc::now);
628 self.with_locally_hidden(|locally| locally.hide(chat_id, hidden_after))?;
629 self.store.remove_chats(&[chat_id.to_owned()])?;
630 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
631 Ok(())
632 }
633
634 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
635 if is_notes_chat(chat_id) {
636 self.remote.set_chat_hidden_at(chat_id, None).await?;
637 self.refresh_sidebar_full().await?;
638 return Ok(());
639 }
640 self.remote.set_chat_hidden_at(chat_id, None).await?;
641 let now = Utc::now();
642 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
643 self.refresh_sidebar_full().await?;
644 Ok(())
645 }
646
647 /// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.
648 pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {
649 let last_message_at = self
650 .store
651 .chat(chat_id)?
652 .and_then(|chat| chat.last_message_at);
653 let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());
654 self.remote
655 .clear_chat_history(chat_id, cleared_until_ms)
656 .await?;
657 self.with_locally_hidden(|locally| {
658 locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))
659 })?;
660 self.store.remove_chats(&[chat_id.to_owned()])?;
661 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
662 Ok(())
663 }
664
665 pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {
666 self.remote.set_chat_topic(chat_id, topic).await?;
667 if let Some(mut chat) = self.store.chat(chat_id)? {
668 chat.title = topic.to_owned();
669 self.store.upsert_chats(std::slice::from_ref(&chat))?;
670 }
671 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
672 Ok(())
673 }
674
675 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
676 let user_id = self.my_user_id().await?;
677 self.remote.remove_chat_member(chat_id, &user_id).await?;
678 self.store.remove_chats(&[chat_id.to_owned()])?;
679 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
680 Ok(())
681 }
682
683 pub async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
684 self.remote.remove_chat_member(chat_id, user_id).await?;
685 if let Some(mut chat) = self.store.chat(chat_id)? {
686 chat.members
687 .retain(|member| member.user_id.as_deref() != Some(user_id));
688 self.store.upsert_chats(std::slice::from_ref(&chat))?;
689 }
690 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
691 Ok(())
692 }
693
694 pub async fn add_chat_members(
695 &self,
696 chat_id: &str,
697 people: &[store::MemberRecord],
698 share: chatsvc::HistoryShare,
699 ) -> Result<()> {
700 let user_ids: Vec<String> = people
701 .iter()
702 .filter_map(|person| person.user_id.clone())
703 .collect();
704 self.remote
705 .add_chat_members(chat_id, &user_ids, share)
706 .await?;
707 if let Some(mut chat) = self.store.chat(chat_id)? {
708 crate::roster_event::merge_members(&mut chat.members, people);
709 self.store.upsert_chats(std::slice::from_ref(&chat))?;
710 }
711 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
712 Ok(())
713 }
714
715 pub async fn send_typing(
716 &self,
717 conversation_id: &str,
718 thread_root_id: Option<&str>,
719 active: bool,
720 ) -> Result<()> {
721 let conversation = match (self.resolve(conversation_id).await?, thread_root_id) {
722 (Conversation::Chat, _) => ConversationRef::chat(conversation_id),
723 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
724 (Conversation::Channel { .. }, Some(root_id)) => {
725 ConversationRef::channel_reply(conversation_id, root_id)
726 }
727 };
728 self.remote.send_typing(&conversation, active).await
729 }
730
731 pub async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
732 self.remote.ack_urgent_message(chat_id, message_id).await
733 }
734
735 pub async fn set_reaction(
736 &self,
737 conversation_id: &str,
738 message_id: &str,
739 reaction_type: &str,
740 ) -> Result<()> {
741 let target = self.message_target(conversation_id, message_id)?;
742 self.remote.set_reaction(&target, reaction_type).await?;
743 self.refresh_message(conversation_id, message_id).await?;
744 Ok(())
745 }
746
747 pub async fn unset_reaction(
748 &self,
749 conversation_id: &str,
750 message_id: &str,
751 reaction_type: &str,
752 ) -> Result<()> {
753 let target = self.message_target(conversation_id, message_id)?;
754 self.remote.unset_reaction(&target, reaction_type).await?;
755 self.refresh_message(conversation_id, message_id).await?;
756 Ok(())
757 }
758
759 pub async fn edit_message(
760 &self,
761 conversation_id: &str,
762 message_id: &str,
763 markdown: &str,
764 ) -> Result<()> {
765 self.edit_message_with_mentions(conversation_id, message_id, markdown, &[])
766 .await
767 }
768
769 pub async fn edit_message_with_mentions(
770 &self,
771 conversation_id: &str,
772 message_id: &str,
773 markdown: &str,
774 mentions: &[MentionInput],
775 ) -> Result<()> {
776 self.edit_message_html(
777 conversation_id,
778 message_id,
779 &markdown_to_html(markdown),
780 mentions,
781 )
782 .await
783 }
784
785 pub async fn edit_message_html(
786 &self,
787 conversation_id: &str,
788 message_id: &str,
789 html: &str,
790 mentions: &[MentionInput],
791 ) -> Result<()> {
792 let conversation = self.resolve(conversation_id).await?;
793 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
794 let target = self.message_target(conversation_id, message_id)?;
795 let mut extras = MessageExtras::default();
796 let mut subject = None;
797 if let Some(record) = self
798 .store
799 .messages_by_id(conversation_id, &[message_id.to_owned()])?
800 .remove(message_id)
801 {
802 let preserved = crate::stored::edit_preserved(&record);
803 html.push_str(&preserved.images_html);
804 extras.files = preserved.files;
805 extras.kept = preserved.kept;
806 subject = record.subject;
807 }
808 match subject {
809 Some(subject) => {
810 self.remote
811 .edit_post(&target, &html, &mentions, &extras, &subject)
812 .await?
813 }
814 None => {
815 self.remote
816 .edit_message(&target, &html, &mentions, &extras)
817 .await?
818 }
819 }
820 self.refresh_message(conversation_id, message_id).await?;
821 Ok(())
822 }
823
824 pub async fn soft_delete_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
825 let target = self.message_target(conversation_id, message_id)?;
826 let user_id = self.my_user_id().await?;
827 self.remote.soft_delete_message(&user_id, &target).await?;
828 self.refresh_message(conversation_id, message_id).await?;
829 Ok(())
830 }
831
832 pub async fn undo_soft_delete_message(
833 &self,
834 conversation_id: &str,
835 message_id: &str,
836 ) -> Result<()> {
837 let target = self.message_target(conversation_id, message_id)?;
838 let user_id = self.my_user_id().await?;
839 self.remote
840 .undo_soft_delete_message(&user_id, &target)
841 .await?;
842 self.refresh_message(conversation_id, message_id).await?;
843 Ok(())
844 }
845
846 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
847 Ok(match self.resolve_stored(conversation_id)? {
848 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
849 Conversation::Channel { team_id } => {
850 let root_id = self
851 .store
852 .messages_by_id(conversation_id, &[message_id.to_owned()])?
853 .remove(message_id)
854 .and_then(|record| record.reply_to_id);
855 MessageTarget::channel(&team_id, conversation_id, message_id, root_id.as_deref())
856 }
857 })
858 }
859
860 pub async fn create_one_on_one(&self, user_id: &str) -> Result<String> {
861 let my_user_id = self.my_user_id().await?;
862 let chat = self.remote.create_one_on_one(&my_user_id, user_id).await?;
863 self.store_new_chat(&chat, &my_user_id)
864 }
865
866 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
867 let my_user_id = self.my_user_id().await?;
868 let chat = self
869 .remote
870 .create_group(&my_user_id, user_ids, topic)
871 .await?;
872 self.store_new_chat(&chat, &my_user_id)
873 }
874
875 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
876 self.store
877 .upsert_chats(&[self.partner_chat_record(chat, my_user_id)])?;
878 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
879 Ok(chat.id.clone())
880 }
881
882 fn seed_sent_images(
883 &self,
884 record: &MessageRecord,
885 html: &str,
886 extras: &MessageExtras,
887 ) -> Result<()> {
888 let uploaded: Vec<_> = crate::stored::images(record)
889 .into_iter()
890 .filter(|image| external_image_url(&image.url).is_none())
891 .collect();
892 let order = hosted_image_order(html, extras);
893 if uploaded.len() != order.len() {
894 return Ok(());
895 }
896 let seeds: Vec<_> = uploaded
897 .iter()
898 .zip(order)
899 .map(|(image, index)| (image.key(), &extras.images[index]))
900 .collect();
901 self.seed_images(&seeds)
902 }
903
904 /// `None` when Teams' shape cannot be written here (channel images or files, team mentions, no quote).
905 async fn quote_reply_via_chatsvc(
906 &self,
907 conversation: &ConversationRef,
908 root_id: Option<&str>,
909 quoted: &MessageRecord,
910 html: &str,
911 mentions: &[OutgoingMention],
912 extras: &MessageExtras,
913 ) -> Result<Option<(graph::Message, String)>> {
914 let in_chat = matches!(conversation, ConversationRef::Chat { .. });
915 if !in_chat && (!extras.images.is_empty() || !extras.files.is_empty()) {
916 return Ok(None);
917 }
918 let Some(quote) = teams_quote(quoted) else {
919 return Ok(None);
920 };
921 if mention_entries(mentions).is_none() {
922 return Ok(None);
923 }
924 let sent = self
925 .send_via_chatsvc(conversation, root_id, html, mentions, extras, Some(&quote))
926 .await?;
927 Ok(Some((sent.message, sent.html)))
928 }
929
930 pub(crate) fn cache_sent(
931 &self,
932 conversation_id: &str,
933 sent: &graph::Message,
934 html: &str,
935 extras: &MessageExtras,
936 ) -> Result<MessageRecord> {
937 let record = message_record(conversation_id, sent)
938 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
939 let _ = self.seed_sent_images(&record, html, extras);
940 self.store.upsert_messages(std::slice::from_ref(&record))?;
941 self.update_chat_preview(std::slice::from_ref(&record))?;
942 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
943 if state
944 .newest_seen
945 .is_some_and(|newest| newest < record.created_at)
946 {
947 state.newest_seen = Some(record.created_at);
948 self.store.set_sync_state(conversation_id, &state)?;
949 }
950 self.announce(conversation_id, true);
951 Ok(record)
952 }
953
954 async fn fetch_channel_message(
955 &self,
956 team_id: &str,
957 channel_id: &str,
958 message_id: &str,
959 ) -> Result<graph::Message> {
960 let known = self
961 .store
962 .messages_by_id(channel_id, &[message_id.to_owned()])?;
963 match known
964 .get(message_id)
965 .and_then(|record| record.reply_to_id.clone())
966 {
967 Some(root_id) => {
968 self.remote
969 .channel_reply(team_id, channel_id, &root_id, message_id)
970 .await
971 }
972 None => {
973 self.remote
974 .channel_message(team_id, channel_id, message_id)
975 .await
976 }
977 }
978 }
979}
980
981#[derive(Debug, Clone)]
982pub struct OpenedPost {
983 pub record: MessageRecord,
984 pub replies_loaded: bool,
985}
986
987pub(crate) fn outgoing(
988 conversation: &Conversation,
989 html: &str,
990 mentions: &[MentionInput],
991) -> Result<(String, Vec<OutgoingMention>)> {
992 if matches!(conversation, Conversation::Chat) {
993 ensure_allowed_in_chat(mentions)?;
994 }
995 Ok(apply_mentions(html, mentions))
996}
997
998fn missing_attachment_id() -> Error {
999 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
1000}