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