BlueGit

ict rusty-teams

Files

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

actions.rs

actions.rs 21.4 KiB Download Raw
1use chatsvc::ConversationRef;
2use chrono::{DateTime, Duration, Utc};
3use graph::{
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
5};
6use store::MessageRecord;
7
8use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9use crate::error::{Error, Result};
10use crate::links::LinkPreview;
11use crate::mapping::{chat_record, message_record};
12use crate::markdown::markdown_to_html;
13use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
14use crate::remote::Remote;
15
16impl<R: Remote> SyncEngine<R> {
17 pub async fn send_message(
18 &self,
19 conversation_id: &str,
20 markdown: &str,
21 thread_root_id: Option<&str>,
22 ) -> Result<MessageRecord> {
23 self.send_message_with_mentions(conversation_id, markdown, thread_root_id, &[])
24 .await
25 }
26
27 pub async fn send_message_with_mentions(
28 &self,
29 conversation_id: &str,
30 markdown: &str,
31 thread_root_id: Option<&str>,
32 mentions: &[MentionInput],
33 ) -> Result<MessageRecord> {
34 self.send_message_with_extras(
35 conversation_id,
36 &markdown_to_html(markdown),
37 thread_root_id,
38 mentions,
39 &MessageExtras::default(),
40 )
41 .await
42 }
43
44 /// `html` is the message body; mentions are matched as `@name` in it.
45 pub async fn send_message_with_extras(
46 &self,
47 conversation_id: &str,
48 html: &str,
49 thread_root_id: Option<&str>,
50 mentions: &[MentionInput],
51 extras: &MessageExtras,
52 ) -> Result<MessageRecord> {
53 let conversation = self.resolve(conversation_id)?;
54 let (html, mentions) = outgoing(&conversation, html, mentions)?;
55 let sent = match (conversation, thread_root_id) {
56 (Conversation::Chat, None) => {
57 self.remote
58 .send_chat_message(conversation_id, &html, &mentions, extras)
59 .await?
60 }
61 (Conversation::Channel { team_id }, Some(root_id)) => {
62 self.remote
63 .reply_to_channel_message(
64 &team_id,
65 conversation_id,
66 root_id,
67 &html,
68 &mentions,
69 extras,
70 )
71 .await?
72 }
73 (Conversation::Chat, Some(_)) => {
74 return Err(Error::Unsupported("a thread reply in a chat"));
75 }
76 (Conversation::Channel { .. }, None) => {
77 return Err(Error::Unsupported(
78 "a channel send without a thread root; use post_to_channel",
79 ));
80 }
81 };
82 self.cache_sent(conversation_id, &sent)
83 }
84
85 /// Chat: quoted reply (Graph beta `replyWithQuote`). Channel: reply in the thread of `message_id`.
86 pub async fn reply_to(
87 &self,
88 conversation_id: &str,
89 message_id: &str,
90 markdown: &str,
91 ) -> Result<MessageRecord> {
92 self.reply_to_with_mentions(conversation_id, message_id, markdown, &[])
93 .await
94 }
95
96 pub async fn reply_to_with_mentions(
97 &self,
98 conversation_id: &str,
99 message_id: &str,
100 markdown: &str,
101 mentions: &[MentionInput],
102 ) -> Result<MessageRecord> {
103 self.reply_to_with_extras(
104 conversation_id,
105 message_id,
106 &markdown_to_html(markdown),
107 mentions,
108 &MessageExtras::default(),
109 )
110 .await
111 }
112
113 pub async fn reply_to_with_extras(
114 &self,
115 conversation_id: &str,
116 message_id: &str,
117 html: &str,
118 mentions: &[MentionInput],
119 extras: &MessageExtras,
120 ) -> Result<MessageRecord> {
121 let conversation = self.resolve(conversation_id)?;
122 let (html, mentions) = outgoing(&conversation, html, mentions)?;
123 let sent = match conversation {
124 Conversation::Chat => {
125 self.remote
126 .reply_with_quote(conversation_id, message_id, &html, &mentions, extras)
127 .await?
128 }
129 Conversation::Channel { team_id } => {
130 let root_id = self
131 .store
132 .messages_by_id(conversation_id, &[message_id.to_owned()])?
133 .remove(message_id)
134 .and_then(|record| record.reply_to_id)
135 .unwrap_or_else(|| message_id.to_owned());
136 self.remote
137 .reply_to_channel_message(
138 &team_id,
139 conversation_id,
140 &root_id,
141 &html,
142 &mentions,
143 extras,
144 )
145 .await?
146 }
147 };
148 self.cache_sent(conversation_id, &sent)
149 }
150
151 /// Own and not deleted. Chat messages, channel posts and channel replies alike.
152 pub fn can_edit(&self, record: &MessageRecord) -> bool {
153 self.is_own(record)
154 }
155
156 pub fn can_delete(&self, record: &MessageRecord) -> bool {
157 self.is_own(record)
158 }
159
160 fn is_own(&self, record: &MessageRecord) -> bool {
161 let my_user_id = self
162 .store
163 .meta(META_USER_ID)
164 .ok()
165 .flatten()
166 .unwrap_or_default();
167 crate::stored::can_edit(record, &my_user_id)
168 }
169
170 pub async fn post_to_channel(
171 &self,
172 channel_id: &str,
173 markdown: &str,
174 subject: Option<&str>,
175 ) -> Result<MessageRecord> {
176 self.post_to_channel_with_mentions(channel_id, markdown, subject, &[])
177 .await
178 }
179
180 pub async fn post_to_channel_with_mentions(
181 &self,
182 channel_id: &str,
183 markdown: &str,
184 subject: Option<&str>,
185 mentions: &[MentionInput],
186 ) -> Result<MessageRecord> {
187 self.post_to_channel_with_extras(
188 channel_id,
189 &markdown_to_html(markdown),
190 subject,
191 mentions,
192 &MessageExtras::default(),
193 )
194 .await
195 }
196
197 pub async fn post_to_channel_with_extras(
198 &self,
199 channel_id: &str,
200 html: &str,
201 subject: Option<&str>,
202 mentions: &[MentionInput],
203 extras: &MessageExtras,
204 ) -> Result<MessageRecord> {
205 let conversation = self.resolve(channel_id)?;
206 let Conversation::Channel { team_id } = &conversation else {
207 return Err(Error::Unsupported("posting a root message to a chat"));
208 };
209 let (html, mentions) = outgoing(&conversation, html, mentions)?;
210 let sent = self
211 .remote
212 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
213 .await?;
214 self.cache_sent(channel_id, &sent)
215 }
216
217 /// Upload then share; the app uses the two steps apart so a failed share does not upload again.
218 pub async fn upload_attachment(
219 &self,
220 conversation_id: &str,
221 file_name: &str,
222 bytes: &[u8],
223 progress: impl Fn(u8) + Send + Sync,
224 ) -> Result<FileReference> {
225 let uploaded = self
226 .upload_attachment_file(conversation_id, file_name, bytes, progress)
227 .await?;
228 self.share_attachment(conversation_id, &uploaded).await?;
229 uploaded.reference().ok_or_else(missing_attachment_id)
230 }
231
232 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
233 pub async fn upload_attachment_file(
234 &self,
235 conversation_id: &str,
236 file_name: &str,
237 bytes: &[u8],
238 progress: impl Fn(u8) + Send + Sync,
239 ) -> Result<UploadedFile> {
240 let destination = match self.resolve(conversation_id)? {
241 Conversation::Chat => UploadDestination::ChatFiles,
242 Conversation::Channel { team_id } => {
243 UploadDestination::Folder(self.channel_folder(&team_id, conversation_id).await?)
244 }
245 };
246 let uploaded = self
247 .remote
248 .upload_file(&destination, file_name, bytes, &progress)
249 .await?;
250 if uploaded.reference().is_none() {
251 let _ = self.remote.delete_file(&uploaded).await;
252 return Err(missing_attachment_id());
253 }
254 Ok(uploaded)
255 }
256
257 /// Read-only for the other chat members; channels need nothing.
258 pub async fn share_attachment(
259 &self,
260 conversation_id: &str,
261 uploaded: &UploadedFile,
262 ) -> Result<()> {
263 if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
264 return Ok(());
265 }
266 let other_members = self.other_member_ids(conversation_id).await?;
267 self.remote.share_file(uploaded, &other_members).await
268 }
269
270 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
271 self.remote.delete_file(uploaded).await
272 }
273
274 async fn channel_folder(&self, team_id: &str, channel_id: &str) -> Result<graph::DriveFolder> {
275 let cached = self
276 .channel_folders
277 .lock()
278 .expect("channel folder cache poisoned")
279 .get(channel_id)
280 .cloned();
281 if let Some(folder) = cached {
282 return Ok(folder);
283 }
284 let folder = self
285 .remote
286 .channel_files_folder(team_id, channel_id)
287 .await?;
288 self.channel_folders
289 .lock()
290 .expect("channel folder cache poisoned")
291 .insert(channel_id.to_owned(), folder.clone());
292 Ok(folder)
293 }
294
295 async fn other_member_ids(&self, chat_id: &str) -> Result<Vec<String>> {
296 let my_user_id = self.my_user_id().await?;
297 let members = self
298 .store
299 .chat(chat_id)?
300 .map(|chat| chat.members)
301 .filter(|members| !members.is_empty())
302 .ok_or_else(|| graph::Error::Upload("Chat members not loaded yet.".into()))?;
303 Ok(members
304 .into_iter()
305 .filter_map(|member| member.user_id)
306 .filter(|user_id| *user_id != my_user_id)
307 .collect())
308 }
309
310 pub async fn refresh_message(
311 &self,
312 conversation_id: &str,
313 message_id: &str,
314 ) -> Result<Option<MessageRecord>> {
315 let fetched = match self.resolve(conversation_id)? {
316 Conversation::Chat => self.remote.chat_message(conversation_id, message_id).await,
317 Conversation::Channel { team_id } => {
318 self.fetch_channel_message(&team_id, conversation_id, message_id)
319 .await
320 }
321 };
322 let message = match fetched {
323 Ok(message) => message,
324 Err(error) => {
325 self.report(format!("cannot refresh a message: {error}"));
326 return Err(error);
327 }
328 };
329 let Some(record) = message_record(conversation_id, &message) else {
330 return Ok(None);
331 };
332 let mut record = record;
333 let delta = self.ingest(conversation_id, vec![record.clone()])?;
334 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
335 self.announce(conversation_id, !delta.is_empty() || links_changed);
336 Ok(Some(record))
337 }
338
339 pub async fn attach_link_preview(
340 &self,
341 conversation_id: &str,
342 message_id: &str,
343 preview: &LinkPreview,
344 ) -> Result<()> {
345 let target = self.message_target(conversation_id, message_id)?;
346 let links_json = preview.links_json();
347 self.remote.set_message_links(&target, &links_json).await?;
348 if self
349 .store
350 .set_message_links(conversation_id, message_id, &links_json)?
351 {
352 self.announce(conversation_id, true);
353 }
354 Ok(())
355 }
356
357 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
358 if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
359 return Err(Error::Unsupported("marking a channel as read"));
360 }
361 let user_id = self.my_user_id().await?;
362 let tenant_id = self.my_tenant_id(conversation_id).await?;
363 self.remote
364 .mark_chat_read(conversation_id, &user_id, &tenant_id)
365 .await?;
366 self.store.mark_chat_read(conversation_id, Utc::now())?;
367 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
368 Ok(())
369 }
370
371 pub async fn mark_unread(&self, chat_id: &str) -> Result<()> {
372 let last_message_at = self
373 .store
374 .chat(chat_id)?
375 .and_then(|chat| chat.last_message_at)
376 .ok_or(Error::Unsupported(
377 "marking a chat without messages as unread",
378 ))?;
379 self.mark_unread_from(chat_id, last_message_at).await
380 }
381
382 pub async fn mark_unread_from(
383 &self,
384 chat_id: &str,
385 message_created_at: DateTime<Utc>,
386 ) -> Result<()> {
387 let last_read_at = message_created_at - Duration::milliseconds(1);
388 let user_id = self.my_user_id().await?;
389 let tenant_id = self.my_tenant_id(chat_id).await?;
390 self.remote
391 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
392 .await?;
393 self.store.mark_chat_unread(chat_id, last_read_at)?;
394 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
395 Ok(())
396 }
397
398 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
399 self.remote.set_chat_muted(chat_id, muted).await?;
400 self.store.set_chat_muted(chat_id, muted)?;
401 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
402 Ok(())
403 }
404
405 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
406 let user_id = self.my_user_id().await?;
407 let tenant_id = self.my_tenant_id(chat_id).await?;
408 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
409 self.store.remove_chats(&[chat_id.to_owned()])?;
410 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
411 Ok(())
412 }
413
414 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
415 let user_id = self.my_user_id().await?;
416 let tenant_id = self.my_tenant_id(chat_id).await?;
417 self.remote
418 .unhide_chat(chat_id, &user_id, &tenant_id)
419 .await?;
420 self.refresh_sidebar_full().await?;
421 Ok(())
422 }
423
424 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
425 let user_id = self.my_user_id().await?;
426 self.remote.leave_chat(chat_id, &user_id).await?;
427 self.store.remove_chats(&[chat_id.to_owned()])?;
428 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
429 Ok(())
430 }
431
432 pub async fn send_typing(
433 &self,
434 conversation_id: &str,
435 thread_root_id: Option<&str>,
436 active: bool,
437 ) -> Result<()> {
438 let conversation = match (self.resolve(conversation_id)?, thread_root_id) {
439 (Conversation::Chat, _) => ConversationRef::chat(conversation_id),
440 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
441 (Conversation::Channel { .. }, Some(root_id)) => {
442 ConversationRef::channel_reply(conversation_id, root_id)
443 }
444 };
445 self.remote.send_typing(&conversation, active).await
446 }
447
448 pub async fn set_reaction(
449 &self,
450 conversation_id: &str,
451 message_id: &str,
452 reaction_type: &str,
453 ) -> Result<()> {
454 let target = self.message_target(conversation_id, message_id)?;
455 self.remote.set_reaction(&target, reaction_type).await?;
456 self.refresh_message(conversation_id, message_id).await?;
457 Ok(())
458 }
459
460 pub async fn unset_reaction(
461 &self,
462 conversation_id: &str,
463 message_id: &str,
464 reaction_type: &str,
465 ) -> Result<()> {
466 let target = self.message_target(conversation_id, message_id)?;
467 self.remote.unset_reaction(&target, reaction_type).await?;
468 self.refresh_message(conversation_id, message_id).await?;
469 Ok(())
470 }
471
472 pub async fn edit_message(
473 &self,
474 conversation_id: &str,
475 message_id: &str,
476 markdown: &str,
477 ) -> Result<()> {
478 self.edit_message_with_mentions(conversation_id, message_id, markdown, &[])
479 .await
480 }
481
482 pub async fn edit_message_with_mentions(
483 &self,
484 conversation_id: &str,
485 message_id: &str,
486 markdown: &str,
487 mentions: &[MentionInput],
488 ) -> Result<()> {
489 self.edit_message_html(
490 conversation_id,
491 message_id,
492 &markdown_to_html(markdown),
493 mentions,
494 )
495 .await
496 }
497
498 pub async fn edit_message_html(
499 &self,
500 conversation_id: &str,
501 message_id: &str,
502 html: &str,
503 mentions: &[MentionInput],
504 ) -> Result<()> {
505 let conversation = self.resolve(conversation_id)?;
506 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
507 let target = self.message_target(conversation_id, message_id)?;
508 let mut extras = MessageExtras::default();
509 if let Some(record) = self
510 .store
511 .messages_by_id(conversation_id, &[message_id.to_owned()])?
512 .remove(message_id)
513 {
514 let preserved = crate::stored::edit_preserved(&record);
515 html.push_str(&preserved.images_html);
516 extras.files = preserved.files;
517 extras.kept = preserved.kept;
518 }
519 self.remote
520 .edit_message(&target, &html, &mentions, &extras)
521 .await?;
522 self.refresh_message(conversation_id, message_id).await?;
523 Ok(())
524 }
525
526 pub async fn soft_delete_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
527 let target = self.message_target(conversation_id, message_id)?;
528 let user_id = self.my_user_id().await?;
529 self.remote.soft_delete_message(&user_id, &target).await?;
530 self.refresh_message(conversation_id, message_id).await?;
531 Ok(())
532 }
533
534 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
535 Ok(match self.resolve(conversation_id)? {
536 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
537 Conversation::Channel { team_id } => {
538 let root_id = self
539 .store
540 .messages_by_id(conversation_id, &[message_id.to_owned()])?
541 .remove(message_id)
542 .and_then(|record| record.reply_to_id);
543 MessageTarget::channel(&team_id, conversation_id, message_id, root_id.as_deref())
544 }
545 })
546 }
547
548 pub async fn create_one_on_one(&self, user_id: &str) -> Result<String> {
549 let my_user_id = self.my_user_id().await?;
550 let chat = self.remote.create_one_on_one(&my_user_id, user_id).await?;
551 self.store_new_chat(&chat, &my_user_id)
552 }
553
554 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
555 let my_user_id = self.my_user_id().await?;
556 let chat = self
557 .remote
558 .create_group(&my_user_id, user_ids, topic)
559 .await?;
560 self.store_new_chat(&chat, &my_user_id)
561 }
562
563 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
564 if let Some(record) = chat_record(chat, my_user_id) {
565 self.store.upsert_chats(&[record])?;
566 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
567 }
568 Ok(chat.id.clone())
569 }
570
571 fn cache_sent(&self, conversation_id: &str, sent: &graph::Message) -> Result<MessageRecord> {
572 let record = message_record(conversation_id, sent)
573 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
574 self.store.upsert_messages(std::slice::from_ref(&record))?;
575 self.update_chat_preview(std::slice::from_ref(&record))?;
576 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
577 if state
578 .newest_seen
579 .is_some_and(|newest| newest < record.created_at)
580 {
581 state.newest_seen = Some(record.created_at);
582 self.store.set_sync_state(conversation_id, &state)?;
583 }
584 self.announce(conversation_id, true);
585 Ok(record)
586 }
587
588 async fn fetch_channel_message(
589 &self,
590 team_id: &str,
591 channel_id: &str,
592 message_id: &str,
593 ) -> Result<graph::Message> {
594 let known = self
595 .store
596 .messages_by_id(channel_id, &[message_id.to_owned()])?;
597 match known
598 .get(message_id)
599 .and_then(|record| record.reply_to_id.clone())
600 {
601 Some(root_id) => {
602 self.remote
603 .channel_reply(team_id, channel_id, &root_id, message_id)
604 .await
605 }
606 None => {
607 self.remote
608 .channel_message(team_id, channel_id, message_id)
609 .await
610 }
611 }
612 }
613}
614
615fn outgoing(
616 conversation: &Conversation,
617 html: &str,
618 mentions: &[MentionInput],
619) -> Result<(String, Vec<OutgoingMention>)> {
620 if matches!(conversation, Conversation::Chat) {
621 ensure_allowed_in_chat(mentions)?;
622 }
623 Ok(apply_mentions(html, mentions))
624}
625
626fn missing_attachment_id() -> Error {
627 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
628}