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