BlueGit

ict rusty-teams

Files

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

actions.rs

actions.rs 33.0 KiB Download Raw
1use chatsvc::{ConversationRef, read_horizon};
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::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 self.share_attachment(conversation_id, &uploaded).await?;
268 uploaded.reference().ok_or_else(missing_attachment_id)
269 }
270
271 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
272 pub async fn upload_attachment_file(
273 &self,
274 conversation_id: &str,
275 file_name: &str,
276 bytes: &[u8],
277 progress: impl Fn(u8) + Send + Sync,
278 ) -> Result<UploadedFile> {
279 let destination = match self.resolve(conversation_id).await? {
280 Conversation::Chat => UploadDestination::ChatFiles,
281 Conversation::Channel { team_id } => {
282 UploadDestination::Folder(self.channel_folder(&team_id, conversation_id).await?)
283 }
284 };
285 let uploaded = self
286 .remote
287 .upload_file(&destination, file_name, bytes, &progress)
288 .await?;
289 if uploaded.reference().is_none() {
290 let _ = self.remote.delete_file(&uploaded).await;
291 return Err(missing_attachment_id());
292 }
293 Ok(uploaded)
294 }
295
296 /// Read-only for the other chat members; channels need nothing.
297 pub async fn share_attachment(
298 &self,
299 conversation_id: &str,
300 uploaded: &UploadedFile,
301 ) -> Result<()> {
302 if !matches!(self.resolve(conversation_id).await?, Conversation::Chat) {
303 return Ok(());
304 }
305 let other_members = self.other_member_ids(conversation_id).await?;
306 self.remote.share_file(uploaded, &other_members).await
307 }
308
309 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
310 self.remote.delete_file(uploaded).await
311 }
312
313 async fn channel_folder(&self, team_id: &str, channel_id: &str) -> Result<graph::DriveFolder> {
314 let cached = self
315 .channel_folders
316 .lock()
317 .expect("channel folder cache poisoned")
318 .get(channel_id)
319 .cloned();
320 if let Some(folder) = cached {
321 return Ok(folder);
322 }
323 let folder = self
324 .remote
325 .channel_files_folder(team_id, channel_id)
326 .await?;
327 self.channel_folders
328 .lock()
329 .expect("channel folder cache poisoned")
330 .insert(channel_id.to_owned(), folder.clone());
331 Ok(folder)
332 }
333
334 async fn other_member_ids(&self, chat_id: &str) -> Result<Vec<String>> {
335 if chat_id == NOTES_CHAT_ID {
336 return Ok(Vec::new());
337 }
338 let my_user_id = self.my_user_id().await?;
339 let members = self
340 .store
341 .chat(chat_id)?
342 .map(|chat| chat.members)
343 .filter(|members| !members.is_empty())
344 .ok_or_else(|| graph::Error::Upload("Chat members not loaded yet.".into()))?;
345 Ok(members
346 .into_iter()
347 .filter_map(|member| member.user_id)
348 .filter(|user_id| *user_id != my_user_id)
349 .collect())
350 }
351
352 pub async fn refresh_message(
353 &self,
354 conversation_id: &str,
355 message_id: &str,
356 ) -> Result<Option<MessageRecord>> {
357 let fetched = match self.resolve(conversation_id).await? {
358 Conversation::Chat => self.remote.chat_message(conversation_id, message_id).await,
359 Conversation::Channel { team_id } => {
360 self.fetch_channel_message(&team_id, conversation_id, message_id)
361 .await
362 }
363 };
364 let message = match fetched {
365 Ok(message) => message,
366 Err(error) => {
367 self.report(format!("cannot refresh a message: {error}"));
368 return Err(error);
369 }
370 };
371 let Some(record) = message_record(conversation_id, &message) else {
372 return Ok(None);
373 };
374 let mut record = record;
375 self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))
376 .await;
377 let delta = self.ingest(conversation_id, vec![record.clone()])?;
378 self.announce_stored_late(conversation_id, &delta);
379 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
380 self.announce(conversation_id, !delta.is_empty() || links_changed);
381 Ok(Some(record))
382 }
383
384 pub async fn open_post(
385 &self,
386 conversation_id: &str,
387 message_id: &str,
388 ) -> Result<Option<OpenedPost>> {
389 let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
390 return Err(Error::Unsupported("opening a post of a chat"));
391 };
392 let root_ids = [message_id.to_owned()];
393 let (fetched, replies) = tokio::join!(
394 self.fetch_channel_message(&team_id, conversation_id, message_id),
395 self.remote
396 .channel_replies(&team_id, conversation_id, &root_ids)
397 );
398 let message = match fetched {
399 Ok(message) => message,
400 Err(error) => {
401 self.report(format!("cannot open a post: {error}"));
402 return Err(error);
403 }
404 };
405 let Some(record) = message_record(conversation_id, &message) else {
406 return Ok(None);
407 };
408 let replies_loaded = record.reply_to_id.is_none()
409 && replies
410 .as_ref()
411 .is_ok_and(|listings| listings.iter().all(Result::is_ok));
412 let mut records = vec![record];
413 if replies_loaded {
414 records.extend(
415 replies
416 .into_iter()
417 .flatten()
418 .flatten()
419 .flatten()
420 .filter_map(|reply| message_record(conversation_id, &reply)),
421 );
422 }
423 self.apply_chat_emotions(conversation_id, &mut records)
424 .await;
425 let mut record = records[0].clone();
426 let delta = self.ingest(conversation_id, records)?;
427 self.announce_stored_late(conversation_id, &delta);
428 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
429 self.announce(conversation_id, !delta.is_empty() || links_changed);
430 Ok(Some(OpenedPost {
431 record,
432 replies_loaded,
433 }))
434 }
435
436 pub async fn attach_link_preview(
437 &self,
438 conversation_id: &str,
439 message_id: &str,
440 preview: &LinkPreview,
441 ) -> Result<()> {
442 let target = self.message_target(conversation_id, message_id)?;
443 let links_json = preview.links_json();
444 if self
445 .store
446 .set_message_links(conversation_id, message_id, &links_json)?
447 {
448 self.announce(conversation_id, true);
449 }
450 self.remote.set_message_links(&target, &links_json).await
451 }
452
453 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
454 if let Conversation::Channel { .. } = self.resolve(conversation_id).await? {
455 return self.mark_channel_read(conversation_id).await;
456 }
457 let now = Utc::now();
458 let last_message_at = self
459 .store
460 .chat(conversation_id)?
461 .and_then(|chat| chat.last_message_at)
462 .unwrap_or(now);
463 self.remote
464 .set_read_horizon(
465 conversation_id,
466 &read_horizon::read_up_to(last_message_at, now),
467 )
468 .await?;
469 if is_notes_chat(conversation_id) || self.has_unread_bookmark(conversation_id) {
470 self.remote
471 .set_read_bookmark(conversation_id, &read_horizon::cleared_bookmark(now))
472 .await?;
473 }
474 self.store.mark_chat_read(conversation_id, now)?;
475 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
476 Ok(())
477 }
478
479 async fn mark_channel_read(&self, channel_id: &str) -> Result<()> {
480 let now = Utc::now();
481 let last_message_at = self
482 .store
483 .channel(channel_id)?
484 .and_then(|channel| channel.last_message_at)
485 .unwrap_or(now);
486 self.remote
487 .set_read_horizon(
488 channel_id,
489 &chatsvc::read_horizon::read_up_to(last_message_at, now),
490 )
491 .await?;
492 self.store.mark_channel_read(channel_id)?;
493 self.store.clear_channel_mentions(channel_id)?;
494 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
495 Ok(())
496 }
497
498 pub async fn mark_all_channels_read(&self) -> Result<()> {
499 let horizon = self
500 .remote
501 .mark_all_channels_read(Utc::now().timestamp_millis())
502 .await?;
503 *self.app_channel_horizon_ms.lock().unwrap() = horizon.channel_ms;
504 self.store.mark_all_channels_read()?;
505 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
506 Ok(())
507 }
508
509 pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
510 let last_message_at = self
511 .store
512 .chat(chat_id)?
513 .and_then(|chat| chat.last_message_at)
514 .ok_or(Error::Unsupported(
515 "marking a chat without messages as unread",
516 ))?;
517 self.mark_unread_from(chat_id, last_message_at).await
518 }
519
520 pub async fn mark_unread_from(
521 &self,
522 chat_id: &str,
523 message_created_at: DateTime<Utc>,
524 ) -> Result<()> {
525 let last_read_at = message_created_at - Duration::milliseconds(1);
526 let bookmark = read_horizon::bookmark_at(
527 message_created_at,
528 &self.message_id_at(chat_id, message_created_at)?,
529 Utc::now(),
530 );
531 self.remote.set_read_bookmark(chat_id, &bookmark).await?;
532 self.store.mark_chat_unread(chat_id, last_read_at)?;
533 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
534 Ok(())
535 }
536
537 fn has_unread_bookmark(&self, chat_id: &str) -> bool {
538 self.chat_states
539 .lock()
540 .unwrap()
541 .get(chat_id)
542 .is_some_and(|state| state.read.bookmark_message_set)
543 }
544
545 fn message_id_at(&self, chat_id: &str, created_at: DateTime<Utc>) -> Result<String> {
546 Ok(self
547 .store
548 .messages_between(chat_id, created_at, created_at)?
549 .into_iter()
550 .next()
551 .map(|message| message.message_id)
552 .unwrap_or_else(|| created_at.timestamp_millis().to_string()))
553 }
554
555 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
556 self.remote.set_chat_muted(chat_id, muted).await?;
557 self.store.set_chat_muted(chat_id, muted)?;
558 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
559 Ok(())
560 }
561
562 pub async fn set_channel_notifications(
563 &self,
564 channel_id: &str,
565 notifications: store::ChannelNotifications,
566 ) -> Result<()> {
567 self.remote
568 .set_channel_notifications(channel_id, notifications)
569 .await?;
570 self.store
571 .set_channel_notifications(channel_id, notifications)?;
572 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
573 Ok(())
574 }
575
576 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
577 if is_notes_chat(chat_id) {
578 self.remote
579 .set_chat_hidden_at(chat_id, Some(Utc::now().timestamp_millis()))
580 .await?;
581 self.store.remove_chats(&[chat_id.to_owned()])?;
582 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
583 return Ok(());
584 }
585 self.remote
586 .set_chat_hidden_at(chat_id, Some(Utc::now().timestamp_millis()))
587 .await?;
588 let hidden_after = self
589 .store
590 .chat(chat_id)?
591 .and_then(|chat| chat.last_message_at)
592 .unwrap_or_else(Utc::now);
593 self.with_locally_hidden(|locally| locally.hide(chat_id, hidden_after))?;
594 self.store.remove_chats(&[chat_id.to_owned()])?;
595 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
596 Ok(())
597 }
598
599 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
600 if is_notes_chat(chat_id) {
601 self.remote.set_chat_hidden_at(chat_id, None).await?;
602 self.refresh_sidebar_full().await?;
603 return Ok(());
604 }
605 self.remote.set_chat_hidden_at(chat_id, None).await?;
606 let now = Utc::now();
607 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
608 self.refresh_sidebar_full().await?;
609 Ok(())
610 }
611
612 /// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.
613 pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {
614 let last_message_at = self
615 .store
616 .chat(chat_id)?
617 .and_then(|chat| chat.last_message_at);
618 let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());
619 self.remote
620 .clear_chat_history(chat_id, cleared_until_ms)
621 .await?;
622 self.with_locally_hidden(|locally| {
623 locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))
624 })?;
625 self.store.remove_chats(&[chat_id.to_owned()])?;
626 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
627 Ok(())
628 }
629
630 pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {
631 self.remote.set_chat_topic(chat_id, topic).await?;
632 if let Some(mut chat) = self.store.chat(chat_id)? {
633 chat.title = topic.to_owned();
634 self.store.upsert_chats(std::slice::from_ref(&chat))?;
635 }
636 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
637 Ok(())
638 }
639
640 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
641 let user_id = self.my_user_id().await?;
642 self.remote.remove_chat_member(chat_id, &user_id).await?;
643 self.store.remove_chats(&[chat_id.to_owned()])?;
644 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
645 Ok(())
646 }
647
648 pub async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
649 self.remote.remove_chat_member(chat_id, user_id).await?;
650 if let Some(mut chat) = self.store.chat(chat_id)? {
651 chat.members
652 .retain(|member| member.user_id.as_deref() != Some(user_id));
653 self.store.upsert_chats(std::slice::from_ref(&chat))?;
654 }
655 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
656 Ok(())
657 }
658
659 pub async fn add_chat_members(
660 &self,
661 chat_id: &str,
662 people: &[store::MemberRecord],
663 share: chatsvc::HistoryShare,
664 ) -> Result<()> {
665 let user_ids: Vec<String> = people
666 .iter()
667 .filter_map(|person| person.user_id.clone())
668 .collect();
669 self.remote
670 .add_chat_members(chat_id, &user_ids, share)
671 .await?;
672 if let Some(mut chat) = self.store.chat(chat_id)? {
673 crate::roster_event::merge_members(&mut chat.members, people);
674 self.store.upsert_chats(std::slice::from_ref(&chat))?;
675 }
676 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
677 Ok(())
678 }
679
680 pub async fn send_typing(
681 &self,
682 conversation_id: &str,
683 thread_root_id: Option<&str>,
684 active: bool,
685 ) -> Result<()> {
686 let conversation = match (self.resolve(conversation_id).await?, thread_root_id) {
687 (Conversation::Chat, _) => ConversationRef::chat(conversation_id),
688 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
689 (Conversation::Channel { .. }, Some(root_id)) => {
690 ConversationRef::channel_reply(conversation_id, root_id)
691 }
692 };
693 self.remote.send_typing(&conversation, active).await
694 }
695
696 pub async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
697 self.remote.ack_urgent_message(chat_id, message_id).await
698 }
699
700 pub async fn set_reaction(
701 &self,
702 conversation_id: &str,
703 message_id: &str,
704 reaction_type: &str,
705 ) -> Result<()> {
706 let target = self.message_target(conversation_id, message_id)?;
707 self.remote.set_reaction(&target, reaction_type).await?;
708 self.refresh_message(conversation_id, message_id).await?;
709 Ok(())
710 }
711
712 pub async fn unset_reaction(
713 &self,
714 conversation_id: &str,
715 message_id: &str,
716 reaction_type: &str,
717 ) -> Result<()> {
718 let target = self.message_target(conversation_id, message_id)?;
719 self.remote.unset_reaction(&target, reaction_type).await?;
720 self.refresh_message(conversation_id, message_id).await?;
721 Ok(())
722 }
723
724 pub async fn edit_message(
725 &self,
726 conversation_id: &str,
727 message_id: &str,
728 markdown: &str,
729 ) -> Result<()> {
730 self.edit_message_with_mentions(conversation_id, message_id, markdown, &[])
731 .await
732 }
733
734 pub async fn edit_message_with_mentions(
735 &self,
736 conversation_id: &str,
737 message_id: &str,
738 markdown: &str,
739 mentions: &[MentionInput],
740 ) -> Result<()> {
741 self.edit_message_html(
742 conversation_id,
743 message_id,
744 &markdown_to_html(markdown),
745 mentions,
746 )
747 .await
748 }
749
750 pub async fn edit_message_html(
751 &self,
752 conversation_id: &str,
753 message_id: &str,
754 html: &str,
755 mentions: &[MentionInput],
756 ) -> Result<()> {
757 let conversation = self.resolve(conversation_id).await?;
758 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
759 let target = self.message_target(conversation_id, message_id)?;
760 let mut extras = MessageExtras::default();
761 if let Some(record) = self
762 .store
763 .messages_by_id(conversation_id, &[message_id.to_owned()])?
764 .remove(message_id)
765 {
766 let preserved = crate::stored::edit_preserved(&record);
767 html.push_str(&preserved.images_html);
768 extras.files = preserved.files;
769 extras.kept = preserved.kept;
770 }
771 self.remote
772 .edit_message(&target, &html, &mentions, &extras)
773 .await?;
774 self.refresh_message(conversation_id, message_id).await?;
775 Ok(())
776 }
777
778 pub async fn soft_delete_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
779 let target = self.message_target(conversation_id, message_id)?;
780 let user_id = self.my_user_id().await?;
781 self.remote.soft_delete_message(&user_id, &target).await?;
782 self.refresh_message(conversation_id, message_id).await?;
783 Ok(())
784 }
785
786 pub async fn undo_soft_delete_message(
787 &self,
788 conversation_id: &str,
789 message_id: &str,
790 ) -> Result<()> {
791 let target = self.message_target(conversation_id, message_id)?;
792 let user_id = self.my_user_id().await?;
793 self.remote
794 .undo_soft_delete_message(&user_id, &target)
795 .await?;
796 self.refresh_message(conversation_id, message_id).await?;
797 Ok(())
798 }
799
800 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
801 Ok(match self.resolve_stored(conversation_id)? {
802 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
803 Conversation::Channel { team_id } => {
804 let root_id = self
805 .store
806 .messages_by_id(conversation_id, &[message_id.to_owned()])?
807 .remove(message_id)
808 .and_then(|record| record.reply_to_id);
809 MessageTarget::channel(&team_id, conversation_id, message_id, root_id.as_deref())
810 }
811 })
812 }
813
814 pub async fn create_one_on_one(&self, user_id: &str) -> Result<String> {
815 let my_user_id = self.my_user_id().await?;
816 let chat = self.remote.create_one_on_one(&my_user_id, user_id).await?;
817 self.store_new_chat(&chat, &my_user_id)
818 }
819
820 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
821 let my_user_id = self.my_user_id().await?;
822 let chat = self
823 .remote
824 .create_group(&my_user_id, user_ids, topic)
825 .await?;
826 self.store_new_chat(&chat, &my_user_id)
827 }
828
829 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
830 self.store
831 .upsert_chats(&[self.partner_chat_record(chat, my_user_id)])?;
832 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
833 Ok(chat.id.clone())
834 }
835
836 fn seed_sent_images(
837 &self,
838 record: &MessageRecord,
839 html: &str,
840 extras: &MessageExtras,
841 ) -> Result<()> {
842 let uploaded: Vec<_> = crate::stored::images(record)
843 .into_iter()
844 .filter(|image| external_image_url(&image.url).is_none())
845 .collect();
846 let order = hosted_image_order(html, extras);
847 if uploaded.len() != order.len() {
848 return Ok(());
849 }
850 let seeds: Vec<_> = uploaded
851 .iter()
852 .zip(order)
853 .map(|(image, index)| (image.key(), &extras.images[index]))
854 .collect();
855 self.seed_images(&seeds)
856 }
857
858 /// `None` when Teams' shape cannot be written here (channel images or files, team mentions, no quote).
859 async fn quote_reply_via_chatsvc(
860 &self,
861 conversation: &ConversationRef,
862 root_id: Option<&str>,
863 quoted: &MessageRecord,
864 html: &str,
865 mentions: &[OutgoingMention],
866 extras: &MessageExtras,
867 ) -> Result<Option<(graph::Message, String)>> {
868 let in_chat = matches!(conversation, ConversationRef::Chat { .. });
869 if !in_chat && (!extras.images.is_empty() || !extras.files.is_empty()) {
870 return Ok(None);
871 }
872 let Some(quote) = teams_quote(quoted) else {
873 return Ok(None);
874 };
875 if mention_entries(mentions).is_none() {
876 return Ok(None);
877 }
878 let sent = self
879 .send_via_chatsvc(conversation, root_id, html, mentions, extras, Some(&quote))
880 .await?;
881 Ok(Some((sent.message, sent.html)))
882 }
883
884 pub(crate) fn cache_sent(
885 &self,
886 conversation_id: &str,
887 sent: &graph::Message,
888 html: &str,
889 extras: &MessageExtras,
890 ) -> Result<MessageRecord> {
891 let record = message_record(conversation_id, sent)
892 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
893 let _ = self.seed_sent_images(&record, html, extras);
894 self.store.upsert_messages(std::slice::from_ref(&record))?;
895 self.update_chat_preview(std::slice::from_ref(&record))?;
896 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
897 if state
898 .newest_seen
899 .is_some_and(|newest| newest < record.created_at)
900 {
901 state.newest_seen = Some(record.created_at);
902 self.store.set_sync_state(conversation_id, &state)?;
903 }
904 self.announce(conversation_id, true);
905 Ok(record)
906 }
907
908 async fn fetch_channel_message(
909 &self,
910 team_id: &str,
911 channel_id: &str,
912 message_id: &str,
913 ) -> Result<graph::Message> {
914 let known = self
915 .store
916 .messages_by_id(channel_id, &[message_id.to_owned()])?;
917 match known
918 .get(message_id)
919 .and_then(|record| record.reply_to_id.clone())
920 {
921 Some(root_id) => {
922 self.remote
923 .channel_reply(team_id, channel_id, &root_id, message_id)
924 .await
925 }
926 None => {
927 self.remote
928 .channel_message(team_id, channel_id, message_id)
929 .await
930 }
931 }
932 }
933}
934
935#[derive(Debug, Clone)]
936pub struct OpenedPost {
937 pub record: MessageRecord,
938 pub replies_loaded: bool,
939}
940
941pub(crate) fn outgoing(
942 conversation: &Conversation,
943 html: &str,
944 mentions: &[MentionInput],
945) -> Result<(String, Vec<OutgoingMention>)> {
946 if matches!(conversation, Conversation::Chat) {
947 ensure_allowed_in_chat(mentions)?;
948 }
949 Ok(apply_mentions(html, mentions))
950}
951
952fn missing_attachment_id() -> Error {
953 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
954}