| 1 | use std::collections::HashSet; |
| 2 | |
| 3 | use chrono::{DateTime, Local, Utc}; |
| 4 | use gpui_kit::*; |
| 5 | use store::MessageRecord; |
| 6 | use teams_core::{PinnedMessage, SavedMessage}; |
| 7 | |
| 8 | use crate::app_state::{AppEvent, AppState, Selection, selection_for}; |
| 9 | use crate::channel_menu::{post_pin_failure, post_pin_notice}; |
| 10 | use crate::format; |
| 11 | use crate::forward_selection::FORWARD_SELECTION_LIMIT; |
| 12 | use crate::image_view_gallery::ViewerRequest; |
| 13 | use crate::notice::short_error; |
| 14 | use crate::rows::{message_text, reply_excerpt}; |
| 15 | use crate::runtime; |
| 16 | |
| 17 | #[derive(Default)] |
| 18 | pub struct SavedSet { |
| 19 | items: Vec<SavedMessage>, |
| 20 | keys: HashSet<(String, String)>, |
| 21 | } |
| 22 | |
| 23 | impl SavedSet { |
| 24 | pub fn items(&self) -> &[SavedMessage] { |
| 25 | &self.items |
| 26 | } |
| 27 | |
| 28 | pub fn contains(&self, conversation_id: &str, message_id: &str) -> bool { |
| 29 | self.keys |
| 30 | .contains(&(conversation_id.to_owned(), message_id.to_owned())) |
| 31 | } |
| 32 | |
| 33 | pub fn replace(&mut self, items: Vec<SavedMessage>) { |
| 34 | self.keys = items.iter().map(saved_key).collect(); |
| 35 | self.items = items; |
| 36 | } |
| 37 | |
| 38 | pub fn insert(&mut self, item: SavedMessage) { |
| 39 | if self.keys.insert(saved_key(&item)) { |
| 40 | self.items.insert(0, item); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub fn remove(&mut self, conversation_id: &str, message_id: &str) -> Option<SavedMessage> { |
| 45 | let key = (conversation_id.to_owned(), message_id.to_owned()); |
| 46 | if !self.keys.remove(&key) { |
| 47 | return None; |
| 48 | } |
| 49 | let position = self.items.iter().position(|item| saved_key(item) == key)?; |
| 50 | Some(self.items.remove(position)) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | fn saved_key(item: &SavedMessage) -> (String, String) { |
| 55 | (item.conversation_id.clone(), item.message_id.clone()) |
| 56 | } |
| 57 | |
| 58 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 59 | pub struct ForwardSource { |
| 60 | pub conversation_id: String, |
| 61 | /// 1 to 5 messages, oldest first. |
| 62 | pub messages: Vec<ForwardItem>, |
| 63 | } |
| 64 | |
| 65 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 66 | pub struct ForwardItem { |
| 67 | pub message_id: String, |
| 68 | pub author: String, |
| 69 | pub time: String, |
| 70 | pub text: String, |
| 71 | } |
| 72 | |
| 73 | impl ForwardSource { |
| 74 | pub fn message_ids(&self) -> Vec<String> { |
| 75 | self.messages |
| 76 | .iter() |
| 77 | .map(|item| item.message_id.clone()) |
| 78 | .collect() |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage { |
| 83 | SavedMessage { |
| 84 | conversation_id: record.conversation_id.clone(), |
| 85 | message_id: record.message_id.clone(), |
| 86 | root_id: record |
| 87 | .reply_to_id |
| 88 | .clone() |
| 89 | .filter(|_| is_channel) |
| 90 | .unwrap_or_else(|| record.message_id.clone()), |
| 91 | author_id: record.sender_id.clone(), |
| 92 | author_name: record.sender_name.clone(), |
| 93 | preview: reply_excerpt(record), |
| 94 | saved_at: Utc::now(), |
| 95 | topic: None, |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | impl AppState { |
| 100 | pub fn message_record(&self, conversation_id: &str, message_id: &str) -> Option<MessageRecord> { |
| 101 | self.store |
| 102 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 103 | .ok()? |
| 104 | .remove(message_id) |
| 105 | .filter(|record| !record.deleted) |
| 106 | } |
| 107 | |
| 108 | pub fn is_saved(&self, conversation_id: &str, message_id: &str) -> bool { |
| 109 | self.saved.contains(conversation_id, message_id) |
| 110 | } |
| 111 | |
| 112 | pub fn pinned_messages(&self, chat_id: &str) -> &[PinnedMessage] { |
| 113 | self.pins.get(chat_id).map_or(&[], Vec::as_slice) |
| 114 | } |
| 115 | |
| 116 | pub fn is_pinned(&self, chat_id: &str, message_id: &str) -> bool { |
| 117 | self.pinned_messages(chat_id) |
| 118 | .iter() |
| 119 | .any(|pin| pin.message_id == message_id) |
| 120 | } |
| 121 | |
| 122 | pub fn refresh_saved(&mut self, cx: &mut Context<Self>) { |
| 123 | let Some(engine) = self.engine.clone() else { |
| 124 | return; |
| 125 | }; |
| 126 | let receiver = runtime::spawn(async move { engine.list_saved().await }); |
| 127 | cx.spawn(async move |this, cx| { |
| 128 | if let Ok(Ok(items)) = receiver.await { |
| 129 | this.update(cx, |state, cx| { |
| 130 | state.saved.replace(items); |
| 131 | cx.emit(AppEvent::Saved); |
| 132 | cx.notify(); |
| 133 | }) |
| 134 | .ok(); |
| 135 | } |
| 136 | }) |
| 137 | .detach(); |
| 138 | } |
| 139 | |
| 140 | pub fn toggle_saved( |
| 141 | &mut self, |
| 142 | conversation_id: &str, |
| 143 | message_id: &str, |
| 144 | cx: &mut Context<Self>, |
| 145 | ) { |
| 146 | let existing = self |
| 147 | .saved |
| 148 | .items() |
| 149 | .iter() |
| 150 | .find(|item| item.conversation_id == conversation_id && item.message_id == message_id) |
| 151 | .cloned(); |
| 152 | match existing { |
| 153 | Some(entry) => self.set_saved(entry, false, cx), |
| 154 | None => { |
| 155 | let Some(record) = self.message_record(conversation_id, message_id) else { |
| 156 | return; |
| 157 | }; |
| 158 | let is_channel = matches!( |
| 159 | selection_for(&self.sidebar, conversation_id), |
| 160 | Some(Selection::Channel(_)) |
| 161 | ); |
| 162 | self.set_saved(saved_entry(&record, is_channel), true, cx); |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | pub fn set_saved(&mut self, entry: SavedMessage, saved: bool, cx: &mut Context<Self>) { |
| 168 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 169 | return; |
| 170 | }; |
| 171 | let restore = if saved { |
| 172 | self.saved.insert(entry.clone()); |
| 173 | None |
| 174 | } else { |
| 175 | self.saved.remove(&entry.conversation_id, &entry.message_id) |
| 176 | }; |
| 177 | cx.emit(AppEvent::Saved); |
| 178 | cx.notify(); |
| 179 | let Some(engine) = engine_or_demo else { |
| 180 | return; |
| 181 | }; |
| 182 | let (conversation_id, message_id) = |
| 183 | (entry.conversation_id.clone(), entry.message_id.clone()); |
| 184 | let root_id = (entry.root_id != entry.message_id).then(|| entry.root_id.clone()); |
| 185 | self.run_chat_action( |
| 186 | if saved { "Save" } else { "Unsave" }, |
| 187 | async move { |
| 188 | engine |
| 189 | .set_saved(&conversation_id, &message_id, root_id.as_deref(), saved) |
| 190 | .await |
| 191 | }, |
| 192 | move |state, cx| { |
| 193 | if saved { |
| 194 | state |
| 195 | .saved |
| 196 | .remove(&entry.conversation_id, &entry.message_id); |
| 197 | } else { |
| 198 | state.saved.insert(restore.unwrap_or(entry)); |
| 199 | } |
| 200 | cx.emit(AppEvent::Saved); |
| 201 | cx.notify(); |
| 202 | }, |
| 203 | |_, _| {}, |
| 204 | cx, |
| 205 | ); |
| 206 | } |
| 207 | |
| 208 | pub fn refresh_pins(&mut self, chat_id: &str, cx: &mut Context<Self>) { |
| 209 | let Some(engine) = self.engine.clone() else { |
| 210 | return; |
| 211 | }; |
| 212 | let chat_id = chat_id.to_owned(); |
| 213 | let requested_id = chat_id.clone(); |
| 214 | let receiver = runtime::spawn(async move { engine.chat_pins(&requested_id).await }); |
| 215 | cx.spawn(async move |this, cx| { |
| 216 | if let Ok(Ok(pins)) = receiver.await { |
| 217 | this.update(cx, |state, cx| state.store_pins(&chat_id, pins, cx)) |
| 218 | .ok(); |
| 219 | } |
| 220 | }) |
| 221 | .detach(); |
| 222 | } |
| 223 | |
| 224 | fn store_pins(&mut self, chat_id: &str, pins: Vec<PinnedMessage>, cx: &mut Context<Self>) { |
| 225 | self.pins.insert(chat_id.to_owned(), pins); |
| 226 | cx.emit(AppEvent::Pins(chat_id.to_owned())); |
| 227 | cx.notify(); |
| 228 | } |
| 229 | |
| 230 | pub fn toggle_pinned(&mut self, chat_id: &str, message_id: &str, cx: &mut Context<Self>) { |
| 231 | let pinned = self.is_pinned(chat_id, message_id); |
| 232 | self.set_pinned(chat_id, message_id, !pinned, cx); |
| 233 | } |
| 234 | |
| 235 | pub fn set_pinned( |
| 236 | &mut self, |
| 237 | chat_id: &str, |
| 238 | message_id: &str, |
| 239 | pinned: bool, |
| 240 | cx: &mut Context<Self>, |
| 241 | ) { |
| 242 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 243 | return; |
| 244 | }; |
| 245 | let channel = self.channel_name(chat_id).is_some(); |
| 246 | let previous = self.pinned_messages(chat_id).to_vec(); |
| 247 | let parent_id = previous |
| 248 | .iter() |
| 249 | .find(|pin| pin.message_id == message_id) |
| 250 | .and_then(|pin| pin.parent_id.clone()); |
| 251 | let mut updated: Vec<PinnedMessage> = previous |
| 252 | .iter() |
| 253 | .filter(|pin| pin.message_id != message_id) |
| 254 | .cloned() |
| 255 | .collect(); |
| 256 | if pinned { |
| 257 | updated.insert( |
| 258 | 0, |
| 259 | PinnedMessage { |
| 260 | message_id: message_id.to_owned(), |
| 261 | pinned_at: Some(Utc::now()), |
| 262 | parent_id: None, |
| 263 | }, |
| 264 | ); |
| 265 | } |
| 266 | self.store_pins(chat_id, updated, cx); |
| 267 | let Some(engine) = engine_or_demo else { |
| 268 | if channel { |
| 269 | self.raise_notice(post_pin_notice(pinned).to_owned(), None, cx); |
| 270 | } |
| 271 | return; |
| 272 | }; |
| 273 | let (owned_chat, owned_message, revert_chat) = ( |
| 274 | chat_id.to_owned(), |
| 275 | message_id.to_owned(), |
| 276 | chat_id.to_owned(), |
| 277 | ); |
| 278 | let call = async move { |
| 279 | if pinned { |
| 280 | engine.pin_message(&owned_chat, &owned_message).await |
| 281 | } else { |
| 282 | engine |
| 283 | .unpin_message(&owned_chat, &owned_message, parent_id.as_deref()) |
| 284 | .await |
| 285 | } |
| 286 | }; |
| 287 | let revert = move |state: &mut Self, cx: &mut Context<Self>| { |
| 288 | state.store_pins(&revert_chat, previous, cx) |
| 289 | }; |
| 290 | if channel { |
| 291 | self.run_channel_action( |
| 292 | post_pin_failure(pinned), |
| 293 | call, |
| 294 | revert, |
| 295 | Some(post_pin_notice(pinned)), |
| 296 | cx, |
| 297 | ); |
| 298 | } else { |
| 299 | self.run_chat_action( |
| 300 | if pinned { "Pin" } else { "Unpin" }, |
| 301 | call, |
| 302 | revert, |
| 303 | |_, _| {}, |
| 304 | cx, |
| 305 | ); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | pub fn copy_message_link( |
| 310 | &mut self, |
| 311 | conversation_id: &str, |
| 312 | message_id: &str, |
| 313 | cx: &mut Context<Self>, |
| 314 | ) { |
| 315 | let Some(engine) = self.engine.clone() else { |
| 316 | if !self.mode.demo { |
| 317 | return; |
| 318 | } |
| 319 | let link = teams_core::chat_message_link(conversation_id, message_id, None); |
| 320 | cx.write_to_clipboard(ClipboardItem::new_string(link)); |
| 321 | self.raise_notice("Link copied".to_owned(), None, cx); |
| 322 | return; |
| 323 | }; |
| 324 | let (conversation_id, message_id) = (conversation_id.to_owned(), message_id.to_owned()); |
| 325 | let receiver = |
| 326 | runtime::spawn(async move { engine.message_link(&conversation_id, &message_id).await }); |
| 327 | cx.spawn(async move |this, cx| { |
| 328 | let outcome = match receiver.await { |
| 329 | Ok(Ok(link)) => Ok(link), |
| 330 | Ok(Err(error)) => Err(short_error(&error)), |
| 331 | Err(_) => Err("cancelled".to_owned()), |
| 332 | }; |
| 333 | this.update(cx, |state, cx| match outcome { |
| 334 | Ok(link) => { |
| 335 | cx.write_to_clipboard(ClipboardItem::new_string(link)); |
| 336 | state.raise_notice("Link copied".to_owned(), None, cx); |
| 337 | } |
| 338 | Err(reason) => state.raise_notice(format!("Copy link failed: {reason}"), None, cx), |
| 339 | }) |
| 340 | .ok(); |
| 341 | }) |
| 342 | .detach(); |
| 343 | } |
| 344 | |
| 345 | pub fn request_forward( |
| 346 | &mut self, |
| 347 | conversation_id: &str, |
| 348 | message_id: &str, |
| 349 | cx: &mut Context<Self>, |
| 350 | ) { |
| 351 | self.request_forward_messages(conversation_id, &[message_id.to_owned()], cx); |
| 352 | } |
| 353 | |
| 354 | pub fn request_forward_messages( |
| 355 | &mut self, |
| 356 | conversation_id: &str, |
| 357 | message_ids: &[String], |
| 358 | cx: &mut Context<Self>, |
| 359 | ) { |
| 360 | if self.mode.read_only { |
| 361 | self.raise_notice("Read-only mode: message not forwarded".to_owned(), None, cx); |
| 362 | return; |
| 363 | } |
| 364 | let mut records: Vec<MessageRecord> = message_ids |
| 365 | .iter() |
| 366 | .filter_map(|message_id| self.message_record(conversation_id, message_id)) |
| 367 | .collect(); |
| 368 | if records.is_empty() { |
| 369 | return; |
| 370 | } |
| 371 | records.sort_by_key(|record| record.created_at); |
| 372 | records.truncate(FORWARD_SELECTION_LIMIT); |
| 373 | let now = Local::now(); |
| 374 | self.forward_request = Some(ForwardSource { |
| 375 | conversation_id: records[0].conversation_id.clone(), |
| 376 | messages: records |
| 377 | .iter() |
| 378 | .map(|record| ForwardItem { |
| 379 | message_id: record.message_id.clone(), |
| 380 | author: record |
| 381 | .sender_name |
| 382 | .clone() |
| 383 | .unwrap_or_else(|| "Unknown".to_owned()), |
| 384 | time: forward_time(record.created_at, now), |
| 385 | text: message_text(record), |
| 386 | }) |
| 387 | .collect(), |
| 388 | }); |
| 389 | cx.emit(AppEvent::Forward); |
| 390 | cx.notify(); |
| 391 | } |
| 392 | |
| 393 | pub fn request_image_viewer(&mut self, request: ViewerRequest, cx: &mut Context<Self>) { |
| 394 | self.image_viewer_request = Some(request); |
| 395 | cx.emit(AppEvent::ImageViewer); |
| 396 | cx.notify(); |
| 397 | } |
| 398 | |
| 399 | pub fn take_image_viewer_request(&mut self) -> Option<ViewerRequest> { |
| 400 | self.image_viewer_request.take() |
| 401 | } |
| 402 | |
| 403 | pub fn take_forward_request(&mut self) -> Option<ForwardSource> { |
| 404 | self.forward_request.take() |
| 405 | } |
| 406 | |
| 407 | pub fn forward_locally( |
| 408 | &mut self, |
| 409 | source: &ForwardSource, |
| 410 | target: &Selection, |
| 411 | comment: &str, |
| 412 | cx: &mut Context<Self>, |
| 413 | ) { |
| 414 | let Selection::Chat(chat_id) = target else { |
| 415 | return; |
| 416 | }; |
| 417 | let Some(chat) = self.sidebar.chats.iter().find(|chat| &chat.id == chat_id) else { |
| 418 | return; |
| 419 | }; |
| 420 | let (chat, record) = |
| 421 | crate::demo::forwarded_message(chat, source, comment, chrono::Utc::now()); |
| 422 | let _ = self.store.upsert_chats(&[chat]); |
| 423 | let _ = self.store.upsert_messages(&[record]); |
| 424 | self.reload_sidebar(cx); |
| 425 | cx.emit(AppEvent::Messages(chat_id.clone())); |
| 426 | } |
| 427 | |
| 428 | pub fn mark_unread_from_message( |
| 429 | &mut self, |
| 430 | chat_id: &str, |
| 431 | message_id: &str, |
| 432 | cx: &mut Context<Self>, |
| 433 | ) { |
| 434 | let Some(record) = self.message_record(chat_id, message_id) else { |
| 435 | return; |
| 436 | }; |
| 437 | self.mark_chat_unread_from(chat_id, Some(record.created_at), cx); |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | fn forward_time(time: DateTime<Utc>, now: DateTime<Local>) -> String { |
| 442 | format::list_time_label(time, now.date_naive(), app_base::format::Zone::Local) |
| 443 | } |
| 444 | |
| 445 | #[cfg(test)] |
| 446 | mod tests { |
| 447 | use chrono::{TimeZone, Utc}; |
| 448 | use teams_core::SavedMessage; |
| 449 | |
| 450 | use super::SavedSet; |
| 451 | |
| 452 | fn saved(message_id: &str) -> SavedMessage { |
| 453 | SavedMessage { |
| 454 | conversation_id: "chat".into(), |
| 455 | message_id: message_id.into(), |
| 456 | root_id: message_id.into(), |
| 457 | author_id: None, |
| 458 | author_name: None, |
| 459 | preview: "text".into(), |
| 460 | saved_at: Utc.with_ymd_and_hms(2026, 10, 9, 8, 0, 0).unwrap(), |
| 461 | topic: None, |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | #[test] |
| 466 | fn saving_then_unsaving_a_message_updates_the_lookup() { |
| 467 | let mut set = SavedSet::default(); |
| 468 | set.insert(saved("m1")); |
| 469 | assert!(set.contains("chat", "m1")); |
| 470 | assert!(!set.contains("other", "m1")); |
| 471 | assert!(set.remove("chat", "m1").is_some()); |
| 472 | assert!(!set.contains("chat", "m1")); |
| 473 | assert!(set.items().is_empty()); |
| 474 | } |
| 475 | |
| 476 | #[test] |
| 477 | fn newest_saved_message_comes_first() { |
| 478 | let mut set = SavedSet::default(); |
| 479 | set.insert(saved("m1")); |
| 480 | set.insert(saved("m2")); |
| 481 | set.insert(saved("m2")); |
| 482 | let ids: Vec<&str> = set |
| 483 | .items() |
| 484 | .iter() |
| 485 | .map(|item| item.message_id.as_str()) |
| 486 | .collect(); |
| 487 | assert_eq!(ids, vec!["m2", "m1"]); |
| 488 | } |
| 489 | |
| 490 | #[test] |
| 491 | fn replacing_the_set_rebuilds_the_lookup() { |
| 492 | let mut set = SavedSet::default(); |
| 493 | set.insert(saved("m1")); |
| 494 | set.replace(vec![saved("m2")]); |
| 495 | assert!(!set.contains("chat", "m1")); |
| 496 | assert!(set.contains("chat", "m2")); |
| 497 | assert_eq!( |
| 498 | set.remove("chat", "m2").map(|item| item.message_id), |
| 499 | Some("m2".into()) |
| 500 | ); |
| 501 | assert_eq!(set.remove("chat", "m2"), None); |
| 502 | } |
| 503 | } |