BlueGit

ict rusty-teams

Files

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

actions.rs

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