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