BlueGit

ict rusty-teams

Files

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

actions.rs

actions.rs 28.9 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 ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
584 self.remote.ack_urgent_message(chat_id, message_id).await
585 }
586
587 pub async fn set_reaction(
588 &self,
589 conversation_id: &str,
590 message_id: &str,
591 reaction_type: &str,
592 ) -> Result<()> {
593 let target = self.message_target(conversation_id, message_id)?;
594 self.remote.set_reaction(&target, reaction_type).await?;
595 self.refresh_message(conversation_id, message_id).await?;
596 Ok(())
597 }
598
599 pub async fn unset_reaction(
600 &self,
601 conversation_id: &str,
602 message_id: &str,
603 reaction_type: &str,
604 ) -> Result<()> {
605 let target = self.message_target(conversation_id, message_id)?;
606 self.remote.unset_reaction(&target, reaction_type).await?;
607 self.refresh_message(conversation_id, message_id).await?;
608 Ok(())
609 }
610
611 pub async fn edit_message(
612 &self,
613 conversation_id: &str,
614 message_id: &str,
615 markdown: &str,
616 ) -> Result<()> {
617 self.edit_message_with_mentions(conversation_id, message_id, markdown, &[])
618 .await
619 }
620
621 pub async fn edit_message_with_mentions(
622 &self,
623 conversation_id: &str,
624 message_id: &str,
625 markdown: &str,
626 mentions: &[MentionInput],
627 ) -> Result<()> {
628 self.edit_message_html(
629 conversation_id,
630 message_id,
631 &markdown_to_html(markdown),
632 mentions,
633 )
634 .await
635 }
636
637 pub async fn edit_message_html(
638 &self,
639 conversation_id: &str,
640 message_id: &str,
641 html: &str,
642 mentions: &[MentionInput],
643 ) -> Result<()> {
644 let conversation = self.resolve(conversation_id).await?;
645 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
646 let target = self.message_target(conversation_id, message_id)?;
647 let mut extras = MessageExtras::default();
648 if let Some(record) = self
649 .store
650 .messages_by_id(conversation_id, &[message_id.to_owned()])?
651 .remove(message_id)
652 {
653 let preserved = crate::stored::edit_preserved(&record);
654 html.push_str(&preserved.images_html);
655 extras.files = preserved.files;
656 extras.kept = preserved.kept;
657 }
658 self.remote
659 .edit_message(&target, &html, &mentions, &extras)
660 .await?;
661 self.refresh_message(conversation_id, message_id).await?;
662 Ok(())
663 }
664
665 pub async fn soft_delete_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
666 let target = self.message_target(conversation_id, message_id)?;
667 let user_id = self.my_user_id().await?;
668 self.remote.soft_delete_message(&user_id, &target).await?;
669 self.refresh_message(conversation_id, message_id).await?;
670 Ok(())
671 }
672
673 pub async fn undo_soft_delete_message(
674 &self,
675 conversation_id: &str,
676 message_id: &str,
677 ) -> Result<()> {
678 let target = self.message_target(conversation_id, message_id)?;
679 let user_id = self.my_user_id().await?;
680 self.remote
681 .undo_soft_delete_message(&user_id, &target)
682 .await?;
683 self.refresh_message(conversation_id, message_id).await?;
684 Ok(())
685 }
686
687 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
688 Ok(match self.resolve_stored(conversation_id)? {
689 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
690 Conversation::Channel { team_id } => {
691 let root_id = self
692 .store
693 .messages_by_id(conversation_id, &[message_id.to_owned()])?
694 .remove(message_id)
695 .and_then(|record| record.reply_to_id);
696 MessageTarget::channel(&team_id, conversation_id, message_id, root_id.as_deref())
697 }
698 })
699 }
700
701 pub async fn create_one_on_one(&self, user_id: &str) -> Result<String> {
702 let my_user_id = self.my_user_id().await?;
703 let chat = self.remote.create_one_on_one(&my_user_id, user_id).await?;
704 self.store_new_chat(&chat, &my_user_id)
705 }
706
707 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
708 let my_user_id = self.my_user_id().await?;
709 let chat = self
710 .remote
711 .create_group(&my_user_id, user_ids, topic)
712 .await?;
713 self.store_new_chat(&chat, &my_user_id)
714 }
715
716 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
717 self.store
718 .upsert_chats(&[self.partner_chat_record(chat, my_user_id)])?;
719 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
720 Ok(chat.id.clone())
721 }
722
723 fn seed_sent_images(
724 &self,
725 record: &MessageRecord,
726 html: &str,
727 extras: &MessageExtras,
728 ) -> Result<()> {
729 let uploaded: Vec<_> = crate::stored::images(record)
730 .into_iter()
731 .filter(|image| external_image_url(&image.url).is_none())
732 .collect();
733 let order = hosted_image_order(html, extras);
734 if uploaded.len() != order.len() {
735 return Ok(());
736 }
737 let seeds: Vec<_> = uploaded
738 .iter()
739 .zip(order)
740 .map(|(image, index)| (image.key(), &extras.images[index]))
741 .collect();
742 self.seed_images(&seeds)
743 }
744
745 fn cache_sent(
746 &self,
747 conversation_id: &str,
748 sent: &graph::Message,
749 html: &str,
750 extras: &MessageExtras,
751 ) -> Result<MessageRecord> {
752 let record = message_record(conversation_id, sent)
753 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
754 let _ = self.seed_sent_images(&record, html, extras);
755 self.store.upsert_messages(std::slice::from_ref(&record))?;
756 self.update_chat_preview(std::slice::from_ref(&record))?;
757 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
758 if state
759 .newest_seen
760 .is_some_and(|newest| newest < record.created_at)
761 {
762 state.newest_seen = Some(record.created_at);
763 self.store.set_sync_state(conversation_id, &state)?;
764 }
765 self.announce(conversation_id, true);
766 Ok(record)
767 }
768
769 async fn fetch_channel_message(
770 &self,
771 team_id: &str,
772 channel_id: &str,
773 message_id: &str,
774 ) -> Result<graph::Message> {
775 let known = self
776 .store
777 .messages_by_id(channel_id, &[message_id.to_owned()])?;
778 match known
779 .get(message_id)
780 .and_then(|record| record.reply_to_id.clone())
781 {
782 Some(root_id) => {
783 self.remote
784 .channel_reply(team_id, channel_id, &root_id, message_id)
785 .await
786 }
787 None => {
788 self.remote
789 .channel_message(team_id, channel_id, message_id)
790 .await
791 }
792 }
793 }
794}
795
796fn outgoing(
797 conversation: &Conversation,
798 html: &str,
799 mentions: &[MentionInput],
800) -> Result<(String, Vec<OutgoingMention>)> {
801 if matches!(conversation, Conversation::Chat) {
802 ensure_allowed_in_chat(mentions)?;
803 }
804 Ok(apply_mentions(html, mentions))
805}
806
807/// The `messageReference` attachment Graph's chat `replyWithQuote` produces; channels have no such action.
808fn quote_reference(record: &MessageRecord) -> KeptAttachment {
809 let sender = record.sender_id.as_ref().map(|user_id| {
810 serde_json::json!({
811 "application": null,
812 "device": null,
813 "user": {
814 "userIdentityType": "aadUser",
815 "id": user_id,
816 "displayName": record.sender_name,
817 },
818 })
819 });
820 let content = serde_json::json!({
821 "messageId": record.message_id,
822 "messagePreview": preview_text(&record.body_html).unwrap_or_default(),
823 "messageSender": sender,
824 });
825 KeptAttachment {
826 id: record.message_id.clone(),
827 content_type: Some(MESSAGE_REFERENCE.to_owned()),
828 content: Some(content.to_string()),
829 content_url: None,
830 name: None,
831 }
832}
833
834fn missing_attachment_id() -> Error {
835 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
836}