BlueGit

ict rusty-teams

Files

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

actions.rs

actions.rs 21.2 KiB Download Raw
1use chatsvc::ConversationRef;
2use chrono::{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 let last_read_at = last_message_at - Duration::milliseconds(1);
380 let user_id = self.my_user_id().await?;
381 let tenant_id = self.my_tenant_id(chat_id).await?;
382 self.remote
383 .mark_chat_unread(chat_id, &user_id, &tenant_id, last_read_at)
384 .await?;
385 self.store.mark_chat_unread(chat_id, last_read_at)?;
386 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
387 Ok(())
388 }
389
390 pub async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
391 self.remote.set_chat_muted(chat_id, muted).await?;
392 self.store.set_chat_muted(chat_id, muted)?;
393 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
394 Ok(())
395 }
396
397 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
398 let user_id = self.my_user_id().await?;
399 let tenant_id = self.my_tenant_id(chat_id).await?;
400 self.remote.hide_chat(chat_id, &user_id, &tenant_id).await?;
401 self.store.remove_chats(&[chat_id.to_owned()])?;
402 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
403 Ok(())
404 }
405
406 pub async fn unhide_chat(&self, chat_id: &str) -> Result<()> {
407 let user_id = self.my_user_id().await?;
408 let tenant_id = self.my_tenant_id(chat_id).await?;
409 self.remote
410 .unhide_chat(chat_id, &user_id, &tenant_id)
411 .await?;
412 self.refresh_sidebar_full().await?;
413 Ok(())
414 }
415
416 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
417 let user_id = self.my_user_id().await?;
418 self.remote.leave_chat(chat_id, &user_id).await?;
419 self.store.remove_chats(&[chat_id.to_owned()])?;
420 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
421 Ok(())
422 }
423
424 pub async fn send_typing(
425 &self,
426 conversation_id: &str,
427 thread_root_id: Option<&str>,
428 active: bool,
429 ) -> Result<()> {
430 let conversation = match (self.resolve(conversation_id)?, thread_root_id) {
431 (Conversation::Chat, _) => ConversationRef::chat(conversation_id),
432 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
433 (Conversation::Channel { .. }, Some(root_id)) => {
434 ConversationRef::channel_reply(conversation_id, root_id)
435 }
436 };
437 self.remote.send_typing(&conversation, active).await
438 }
439
440 pub async fn set_reaction(
441 &self,
442 conversation_id: &str,
443 message_id: &str,
444 reaction_type: &str,
445 ) -> Result<()> {
446 let target = self.message_target(conversation_id, message_id)?;
447 self.remote.set_reaction(&target, reaction_type).await?;
448 self.refresh_message(conversation_id, message_id).await?;
449 Ok(())
450 }
451
452 pub async fn unset_reaction(
453 &self,
454 conversation_id: &str,
455 message_id: &str,
456 reaction_type: &str,
457 ) -> Result<()> {
458 let target = self.message_target(conversation_id, message_id)?;
459 self.remote.unset_reaction(&target, reaction_type).await?;
460 self.refresh_message(conversation_id, message_id).await?;
461 Ok(())
462 }
463
464 pub async fn edit_message(
465 &self,
466 conversation_id: &str,
467 message_id: &str,
468 markdown: &str,
469 ) -> Result<()> {
470 self.edit_message_with_mentions(conversation_id, message_id, markdown, &[])
471 .await
472 }
473
474 pub async fn edit_message_with_mentions(
475 &self,
476 conversation_id: &str,
477 message_id: &str,
478 markdown: &str,
479 mentions: &[MentionInput],
480 ) -> Result<()> {
481 self.edit_message_html(
482 conversation_id,
483 message_id,
484 &markdown_to_html(markdown),
485 mentions,
486 )
487 .await
488 }
489
490 pub async fn edit_message_html(
491 &self,
492 conversation_id: &str,
493 message_id: &str,
494 html: &str,
495 mentions: &[MentionInput],
496 ) -> Result<()> {
497 let conversation = self.resolve(conversation_id)?;
498 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
499 let target = self.message_target(conversation_id, message_id)?;
500 let mut extras = MessageExtras::default();
501 if let Some(record) = self
502 .store
503 .messages_by_id(conversation_id, &[message_id.to_owned()])?
504 .remove(message_id)
505 {
506 let preserved = crate::stored::edit_preserved(&record);
507 html.push_str(&preserved.images_html);
508 extras.files = preserved.files;
509 extras.kept = preserved.kept;
510 }
511 self.remote
512 .edit_message(&target, &html, &mentions, &extras)
513 .await?;
514 self.refresh_message(conversation_id, message_id).await?;
515 Ok(())
516 }
517
518 pub async fn soft_delete_message(&self, conversation_id: &str, message_id: &str) -> Result<()> {
519 let target = self.message_target(conversation_id, message_id)?;
520 let user_id = self.my_user_id().await?;
521 self.remote.soft_delete_message(&user_id, &target).await?;
522 self.refresh_message(conversation_id, message_id).await?;
523 Ok(())
524 }
525
526 fn message_target(&self, conversation_id: &str, message_id: &str) -> Result<MessageTarget> {
527 Ok(match self.resolve(conversation_id)? {
528 Conversation::Chat => MessageTarget::chat(conversation_id, message_id),
529 Conversation::Channel { team_id } => {
530 let root_id = self
531 .store
532 .messages_by_id(conversation_id, &[message_id.to_owned()])?
533 .remove(message_id)
534 .and_then(|record| record.reply_to_id);
535 MessageTarget::channel(&team_id, conversation_id, message_id, root_id.as_deref())
536 }
537 })
538 }
539
540 pub async fn create_one_on_one(&self, user_id: &str) -> Result<String> {
541 let my_user_id = self.my_user_id().await?;
542 let chat = self.remote.create_one_on_one(&my_user_id, user_id).await?;
543 self.store_new_chat(&chat, &my_user_id)
544 }
545
546 pub async fn create_group(&self, user_ids: &[String], topic: Option<&str>) -> Result<String> {
547 let my_user_id = self.my_user_id().await?;
548 let chat = self
549 .remote
550 .create_group(&my_user_id, user_ids, topic)
551 .await?;
552 self.store_new_chat(&chat, &my_user_id)
553 }
554
555 fn store_new_chat(&self, chat: &graph::Chat, my_user_id: &str) -> Result<String> {
556 if let Some(record) = chat_record(chat, my_user_id) {
557 self.store.upsert_chats(&[record])?;
558 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
559 }
560 Ok(chat.id.clone())
561 }
562
563 fn cache_sent(&self, conversation_id: &str, sent: &graph::Message) -> Result<MessageRecord> {
564 let record = message_record(conversation_id, sent)
565 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
566 self.store.upsert_messages(std::slice::from_ref(&record))?;
567 self.update_chat_preview(std::slice::from_ref(&record))?;
568 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
569 if state
570 .newest_seen
571 .is_some_and(|newest| newest < record.created_at)
572 {
573 state.newest_seen = Some(record.created_at);
574 self.store.set_sync_state(conversation_id, &state)?;
575 }
576 self.announce(conversation_id, true);
577 Ok(record)
578 }
579
580 async fn fetch_channel_message(
581 &self,
582 team_id: &str,
583 channel_id: &str,
584 message_id: &str,
585 ) -> Result<graph::Message> {
586 let known = self
587 .store
588 .messages_by_id(channel_id, &[message_id.to_owned()])?;
589 match known
590 .get(message_id)
591 .and_then(|record| record.reply_to_id.clone())
592 {
593 Some(root_id) => {
594 self.remote
595 .channel_reply(team_id, channel_id, &root_id, message_id)
596 .await
597 }
598 None => {
599 self.remote
600 .channel_message(team_id, channel_id, message_id)
601 .await
602 }
603 }
604 }
605}
606
607fn outgoing(
608 conversation: &Conversation,
609 html: &str,
610 mentions: &[MentionInput],
611) -> Result<(String, Vec<OutgoingMention>)> {
612 if matches!(conversation, Conversation::Chat) {
613 ensure_allowed_in_chat(mentions)?;
614 }
615 Ok(apply_mentions(html, mentions))
616}
617
618fn missing_attachment_id() -> Error {
619 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
620}