BlueGit

ict rusty-teams

Files

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

actions.rs

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