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