BlueGit

ict rusty-teams

Files

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

actions.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
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)
416 .await;
417 let mut record = records[0].clone();
418 let delta = self.ingest(conversation_id, records)?;
419 self.announce_stored_late(conversation_id, &delta);
420 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
421 self.announce(conversation_id, !delta.is_empty() || links_changed);
422 Ok(Some(OpenedPost {
423 record,
424 replies_loaded,
425 }))
426 }
427
428 pub async fn attach_link_preview(
429 &self,
430 conversation_id: &str,
431 message_id: &str,
432 preview: &LinkPreview,
433 ) -> Result<()> {
434 let target = self.message_target(conversation_id, message_id)?;
435 let links_json = preview.links_json();
436 self.remote.set_message_links(&target, &links_json).await?;
437 if self
438 .store
439 .set_message_links(conversation_id, message_id, &links_json)?
440 {
441 self.announce(conversation_id, true);
442 }
443 Ok(())
444 }
445
446 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
447 if let Conversation::Channel { .. } = self.resolve(conversation_id).await? {
448 return self.mark_channel_read(conversation_id).await;
449 }
450 let user_id = self.my_user_id().await?;
451 let tenant_id = self.my_tenant_id(conversation_id).await?;
452 self.remote
453 .mark_chat_read(conversation_id, &user_id, &tenant_id)
454 .await?;
455 let now = Utc::now();
456 if is_notes_chat(conversation_id) {
457 self.remote
458 .set_read_bookmark(conversation_id, &read_horizon::cleared_bookmark(now))
459 .await?;
460 }
461 self.store.mark_chat_read(conversation_id, now)?;
462 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
463 Ok(())
464 }
465
466 async fn mark_channel_read(&self, channel_id: &str) -> Result<()> {
467 let now = Utc::now();
468 let last_message_at = self
469 .store
470 .channel(channel_id)?
471 .and_then(|channel| channel.last_message_at)
472 .unwrap_or(now);
473 self.remote
474 .set_read_horizon(
475 channel_id,
476 &chatsvc::read_horizon::read_up_to(last_message_at, now),
477 )
478 .await?;
479 self.store.mark_channel_read(channel_id)?;
480 self.store.clear_channel_mentions(channel_id)?;
481 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
482 Ok(())
483 }
484
485 pub async fn mark_all_channels_read(&self) -> Result<()> {
486 let horizon = self
487 .remote
488 .mark_all_channels_read(Utc::now().timestamp_millis())
489 .await?;
490 *self.app_channel_horizon_ms.lock().unwrap() = horizon.channel_ms;
491 self.store.mark_all_channels_read()?;
492 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
493 Ok(())
494 }
495
496 pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
497 let last_message_at = self
498 .store
499 .chat(chat_id)?
500 .and_then(|chat| chat.last_message_at)
501 .ok_or(Error::Unsupported(
502 "marking a chat without messages as unread",
503 ))?;
504 self.mark_unread_from(chat_id, last_message_at).await
505 }
506
507 pub async fn mark_unread_from(
508 &self,
509 chat_id: &str,
510 message_created_at: DateTime<Utc>,
511 ) -> Result<()> {
512 let last_read_at = message_created_at - Duration::milliseconds(1);
513 if is_notes_chat(chat_id) {
514 let bookmark = read_horizon::bookmark_at(
515 message_created_at,
516 &self.message_id_at(chat_id, message_created_at)?,
517 Utc::now(),
518 );
519 self.remote.set_read_bookmark(chat_id, &bookmark).await?;
520 } else {
521 let user_id = self.my_user_id().await?;
522 let tenant_id = self.my_tenant_id(chat_id).await?;
523 self.remote
524 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
525 .await?;
526 }
527 self.store.mark_chat_unread(chat_id, last_read_at)?;
528 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
529 Ok(())
530 }
531
532 fn message_id_at(&self, chat_id: &str, created_at: DateTime<Utc>) -> Result<String> {
533 Ok(self
534 .store
535 .messages_between(chat_id, created_at, created_at)?
536 .into_iter()
537 .next()
538 .map(|message| message.message_id)
539 .unwrap_or_else(|| created_at.timestamp_millis().to_string()))
540 }
541
542 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
543 self.remote.set_chat_muted(chat_id, muted).await?;
544 self.store.set_chat_muted(chat_id, muted)?;
545 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
546 Ok(())
547 }
548
549 pub async fn set_channel_notifications(
550 &self,
551 channel_id: &str,
552 notifications: store::ChannelNotifications,
553 ) -> Result<()> {
554 self.remote
555 .set_channel_notifications(channel_id, notifications)
556 .await?;
557 self.store
558 .set_channel_notifications(channel_id, notifications)?;
559 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
560 Ok(())
561 }
562
563 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
564 if is_notes_chat(chat_id) {
565 self.remote
566 .set_chat_hidden_at(chat_id, Some(Utc::now().timestamp_millis()))
567 .await?;
568 self.store.remove_chats(&[chat_id.to_owned()])?;
569 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
570 return Ok(());
571 }
572 let user_id = self.my_user_id().await?;
573 let tenant_id = self.my_tenant_id(chat_id).await?;
574 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
575 let hidden_after = self
576 .store
577 .chat(chat_id)?
578 .and_then(|chat| chat.last_message_at)
579 .unwrap_or_else(Utc::now);
580 self.with_locally_hidden(|locally| locally.hide(chat_id, hidden_after))?;
581 self.store.remove_chats(&[chat_id.to_owned()])?;
582 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
583 Ok(())
584 }
585
586 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
587 if is_notes_chat(chat_id) {
588 self.remote.set_chat_hidden_at(chat_id, None).await?;
589 self.refresh_sidebar_full().await?;
590 return Ok(());
591 }
592 let user_id = self.my_user_id().await?;
593 let tenant_id = self.my_tenant_id(chat_id).await?;
594 self.remote
595 .unhide_chat(chat_id, &user_id, &tenant_id)
596 .await?;
597 let now = Utc::now();
598 self.with_locally_hidden(|locally| locally.unhide(chat_id, now))?;
599 self.refresh_sidebar_full().await?;
600 Ok(())
601 }
602
603 /// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.
604 pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {
605 let last_message_at = self
606 .store
607 .chat(chat_id)?
608 .and_then(|chat| chat.last_message_at);
609 let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());
610 self.remote
611 .clear_chat_history(chat_id, cleared_until_ms)
612 .await?;
613 self.with_locally_hidden(|locally| {
614 locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))
615 })?;
616 self.store.remove_chats(&[chat_id.to_owned()])?;
617 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
618 Ok(())
619 }
620
621 pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {
622 self.remote.set_chat_topic(chat_id, topic).await?;
623 if let Some(mut chat) = self.store.chat(chat_id)? {
624 chat.title = topic.to_owned();
625 self.store.upsert_chats(std::slice::from_ref(&chat))?;
626 }
627 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
628 Ok(())
629 }
630
631 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
632 let user_id = self.my_user_id().await?;
633 self.remote.remove_chat_member(chat_id, &user_id).await?;
634 self.store.remove_chats(&[chat_id.to_owned()])?;
635 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
636 Ok(())
637 }
638
639 pub async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> {
640 self.remote.remove_chat_member(chat_id, user_id).await?;
641 if let Some(mut chat) = self.store.chat(chat_id)? {
642 chat.members
643 .retain(|member| member.user_id.as_deref() != Some(user_id));
644 self.store.upsert_chats(std::slice::from_ref(&chat))?;
645 }
646 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
647 Ok(())
648 }
649
650 pub async fn add_chat_members(
651 &self,
652 chat_id: &str,
653 people: &[store::MemberRecord],
654 share: chatsvc::HistoryShare,
655 ) -> Result<()> {
656 let user_ids: Vec<String> = people
657 .iter()
658 .filter_map(|person| person.user_id.clone())
659 .collect();
660 self.remote
661 .add_chat_members(chat_id, &user_ids, share)
662 .await?;
663 if let Some(mut chat) = self.store.chat(chat_id)? {
664 crate::roster_event::merge_members(&mut chat.members, people);
665 self.store.upsert_chats(std::slice::from_ref(&chat))?;
666 }
667 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
668 Ok(())
669 }
670
671 pub async fn send_typing(
672 &self,
673 conversation_id: &str,
674 thread_root_id: Option<&str>,
675 active: bool,
676 ) -> Result<()> {
677 let conversation = match (self.resolve(conversation_id).await?, thread_root_id) {
678 (Conversation::Chat, _) => ConversationRef::chat(conversation_id),
679 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
680 (Conversation::Channel { .. }, Some(root_id)) => {
681 ConversationRef::channel_reply(conversation_id, root_id)
682 }
683 };
684 self.remote.send_typing(&conversation, active).await
685 }
686
687 pub async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
688 self.remote.ack_urgent_message(chat_id, message_id).await
689 }
690
691 pub async fn set_reaction(
692 &self,
693 conversation_id: &str,
694 message_id: &str,
695 reaction_type: &str,
696 ) -> Result<()> {
697 let target = self.message_target(conversation_id, message_id)?;
698 self.remote.set_reaction(&target, reaction_type).await?;
699 self.refresh_message(conversation_id, message_id).await?;
700 Ok(())
701 }
702
703 pub async fn unset_reaction(
704 &self,
705 conversation_id: &str,
706 message_id: &str,
707 reaction_type: &str,
708 ) -> Result<()> {
709 let target = self.message_target(conversation_id, message_id)?;
710 self.remote.unset_reaction(&target, reaction_type).await?;
711 self.refresh_message(conversation_id, message_id).await?;
712 Ok(())
713 }
714
715 pub async fn edit_message(
716 &self,
717 conversation_id: &str,
718 message_id: &str,
719 markdown: &str,
720 ) -> Result<()> {
721 self.edit_message_with_mentions(conversation_id, message_id, markdown, &[])
722 .await
723 }
724
725 pub async fn edit_message_with_mentions(
726 &self,
727 conversation_id: &str,
728 message_id: &str,
729 markdown: &str,
730 mentions: &[MentionInput],
731 ) -> Result<()> {
732 self.edit_message_html(
733 conversation_id,
734 message_id,
735 &markdown_to_html(markdown),
736 mentions,
737 )
738 .await
739 }
740
741 pub async fn edit_message_html(
742 &self,
743 conversation_id: &str,
744 message_id: &str,
745 html: &str,
746 mentions: &[MentionInput],
747 ) -> Result<()> {
748 let conversation = self.resolve(conversation_id).await?;
749 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
750 let target = self.message_target(conversation_id, message_id)?;
751 let mut extras = MessageExtras::default();
752 if let Some(record) = self
753 .store
754 .messages_by_id(conversation_id, &[message_id.to_owned()])?
755 .remove(message_id)
756 {
757 let preserved = crate::stored::edit_preserved(&record);
758 html.push_str(&preserved.images_html);
759 extras.files = preserved.files;
760 extras.kept = preserved.kept;
761 }
762 self.remote
763 .edit_message(&target, &html, &mentions, &extras)
764 .await?;
765 self.refresh_message(conversation_id, message_id).await?;
766 Ok(())
767 }
768
769 pub async fn soft_delete_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
770 let target = self.message_target(conversation_id, message_id)?;
771 let user_id = self.my_user_id().await?;
772 self.remote.soft_delete_message(&user_id, &target).await?;
773 self.refresh_message(conversation_id, message_id).await?;
774 Ok(())
775 }
776
777 pub async fn undo_soft_delete_message(
778 &self,
779 conversation_id: &str,
780 message_id: &str,
781 ) -> Result<()> {
782 let target = self.message_target(conversation_id, message_id)?;
783 let user_id = self.my_user_id().await?;
784 self.remote
785 .undo_soft_delete_message(&user_id, &target)
786 .await?;
787 self.refresh_message(conversation_id, message_id).await?;
788 Ok(())
789 }
790
791 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
792 Ok(match self.resolve_stored(conversation_id)? {
793 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
794 Conversation::Channel { team_id } => {
795 let root_id = self
796 .store
797 .messages_by_id(conversation_id, &[message_id.to_owned()])?
798 .remove(message_id)
799 .and_then(|record| record.reply_to_id);
800 MessageTarget::channel(&team_id, conversation_id, message_id, root_id.as_deref())
801 }
802 })
803 }
804
805 pub async fn create_one_on_one(&self, user_id: &str) -> Result<String> {
806 let my_user_id = self.my_user_id().await?;
807 let chat = self.remote.create_one_on_one(&my_user_id, user_id).await?;
808 self.store_new_chat(&chat, &my_user_id)
809 }
810
811 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
812 let my_user_id = self.my_user_id().await?;
813 let chat = self
814 .remote
815 .create_group(&my_user_id, user_ids, topic)
816 .await?;
817 self.store_new_chat(&chat, &my_user_id)
818 }
819
820 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
821 self.store
822 .upsert_chats(&[self.partner_chat_record(chat, my_user_id)])?;
823 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
824 Ok(chat.id.clone())
825 }
826
827 fn seed_sent_images(
828 &self,
829 record: &MessageRecord,
830 html: &str,
831 extras: &MessageExtras,
832 ) -> Result<()> {
833 let uploaded: Vec<_> = crate::stored::images(record)
834 .into_iter()
835 .filter(|image| external_image_url(&image.url).is_none())
836 .collect();
837 let order = hosted_image_order(html, extras);
838 if uploaded.len() != order.len() {
839 return Ok(());
840 }
841 let seeds: Vec<_> = uploaded
842 .iter()
843 .zip(order)
844 .map(|(image, index)| (image.key(), &extras.images[index]))
845 .collect();
846 self.seed_images(&seeds)
847 }
848
849 /// `None` when Teams' shape cannot be written here (images, files, team mentions, no quote).
850 async fn quote_reply_via_chatsvc(
851 &self,
852 conversation: &ConversationRef,
853 root_id: Option<&str>,
854 quoted: &MessageRecord,
855 html: &str,
856 mentions: &[OutgoingMention],
857 extras: &MessageExtras,
858 ) -> Result<Option<(graph::Message, String)>> {
859 if !extras.images.is_empty() || !extras.files.is_empty() {
860 return Ok(None);
861 }
862 let Some(quote) = teams_quote(quoted) else {
863 return Ok(None);
864 };
865 let Some(properties) = quote_reply_properties(&quote, mentions, extras.importance) else {
866 return Ok(None);
867 };
868 self.ensure_display_name().await?;
869 let me = self
870 .me()
871 .ok_or(Error::Unsupported("a quote reply before sign-in"))?;
872 let content = format!("{}{}", quote.html, chatsvc_mention_html(html, mentions));
873 let message_id = self
874 .remote
875 .post_chatsvc_message(conversation, &content, &me.display_name, &properties)
876 .await?;
877 let created_at = message_id
878 .parse::<i64>()
879 .ok()
880 .and_then(DateTime::from_timestamp_millis)
881 .unwrap_or_else(Utc::now);
882 let cached_html = format!("{}{html}", quote.html);
883 let sent = serde_json::from_value(serde_json::json!({
884 "id": message_id,
885 "messageType": "message",
886 "createdDateTime": created_at.to_rfc3339(),
887 "replyToId": root_id,
888 "importance": extras.importance,
889 "from": {"user": {"id": me.user_id, "displayName": me.display_name}},
890 "body": {"contentType": "html", "content": cached_html},
891 "mentions": mentions.iter().map(OutgoingMention::to_json).collect::<Vec<_>>(),
892 }))
893 .map_err(|_| Error::Unsupported("a chatsvc reply without a message shape"))?;
894 Ok(Some((sent, cached_html)))
895 }
896
897 pub(crate) fn cache_sent(
898 &self,
899 conversation_id: &str,
900 sent: &graph::Message,
901 html: &str,
902 extras: &MessageExtras,
903 ) -> Result<MessageRecord> {
904 let record = message_record(conversation_id, sent)
905 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
906 let _ = self.seed_sent_images(&record, html, extras);
907 self.store.upsert_messages(std::slice::from_ref(&record))?;
908 self.update_chat_preview(std::slice::from_ref(&record))?;
909 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
910 if state
911 .newest_seen
912 .is_some_and(|newest| newest < record.created_at)
913 {
914 state.newest_seen = Some(record.created_at);
915 self.store.set_sync_state(conversation_id, &state)?;
916 }
917 self.announce(conversation_id, true);
918 Ok(record)
919 }
920
921 async fn fetch_channel_message(
922 &self,
923 team_id: &str,
924 channel_id: &str,
925 message_id: &str,
926 ) -> Result<graph::Message> {
927 let known = self
928 .store
929 .messages_by_id(channel_id, &[message_id.to_owned()])?;
930 match known
931 .get(message_id)
932 .and_then(|record| record.reply_to_id.clone())
933 {
934 Some(root_id) => {
935 self.remote
936 .channel_reply(team_id, channel_id, &root_id, message_id)
937 .await
938 }
939 None => {
940 self.remote
941 .channel_message(team_id, channel_id, message_id)
942 .await
943 }
944 }
945 }
946}
947
948#[derive(Debug, Clone)]
949pub struct OpenedPost {
950 pub record: MessageRecord,
951 pub replies_loaded: bool,
952}
953
954pub(crate) fn outgoing(
955 conversation: &Conversation,
956 html: &str,
957 mentions: &[MentionInput],
958) -> Result<(String, Vec<OutgoingMention>)> {
959 if matches!(conversation, Conversation::Chat) {
960 ensure_allowed_in_chat(mentions)?;
961 }
962 Ok(apply_mentions(html, mentions))
963}
964
965fn missing_attachment_id() -> Error {
966 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
967}