BlueGit

ict rusty-teams

Files

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

actions.rs

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