BlueGit

ict rusty-teams

Files

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

actions.rs

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