BlueGit

ict rusty-teams

Files

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

actions.rs

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