BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / chat_actions.rs

chat_actions.rs

chat_actions.rs 17.8 KiB Download Raw
1use std::future::Future;
2
3use chatsvc::HistoryShare;
4use chrono::{DateTime, Duration, Local, Offset, Utc};
5use gpui_kit::*;
6use store::{ChannelNotifications, ChatRecord, MemberRecord};
7use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
8
9use crate::app_state::{AppState, Selection, chat_title};
10use crate::notice::{NoticeAction, short_error, truncated};
11use crate::sidebar_model::{
12 Section, SectionInput, Step, build_sections, next_chat_id, step_id, visible_chat_ids,
13};
14
15pub const TITLE_LIMIT: usize = 40;
16
17impl AppState {
18 pub fn keeps_unread(&self, chat_id: &str) -> bool {
19 self.keep_unread.as_deref() == Some(chat_id)
20 }
21
22 pub fn mark_chat_unread(&mut self, chat_id: &str, cx: &mut Context<Self>) {
23 self.mark_chat_unread_from(chat_id, None, cx);
24 }
25
26 pub fn mark_chat_unread_from(
27 &mut self,
28 chat_id: &str,
29 message_created_at: Option<DateTime<Utc>>,
30 cx: &mut Context<Self>,
31 ) {
32 let Some(chat) = self.chat_record(chat_id) else {
33 return;
34 };
35 let Some(last_message_at) = chat.last_message_at else {
36 return;
37 };
38 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
39 return;
40 };
41 let last_read_at =
42 message_created_at.unwrap_or(last_message_at) - Duration::milliseconds(1);
43 let _ = self.store.mark_chat_unread(chat_id, last_read_at);
44 if self.selection == Some(Selection::Chat(chat_id.to_owned())) {
45 self.keep_unread = Some(chat_id.to_owned());
46 }
47 self.reload_sidebar(cx);
48 let Some(engine) = engine_or_demo else {
49 return;
50 };
51 let owned_id = chat_id.to_owned();
52 let revert_id = owned_id.clone();
53 let restored_read_at = chat.last_read_at.unwrap_or(last_message_at);
54 self.run_chat_action(
55 "Mark as unread",
56 async move {
57 match message_created_at {
58 Some(created_at) => engine.mark_unread_from(&owned_id, created_at).await,
59 None => engine.mark_unread(&owned_id).await,
60 }
61 },
62 move |state, cx| {
63 let _ = state.store.mark_chat_read(&revert_id, restored_read_at);
64 if state.keep_unread.as_deref() == Some(revert_id.as_str()) {
65 state.keep_unread = None;
66 }
67 state.reload_sidebar(cx);
68 },
69 |_, _| {},
70 cx,
71 );
72 }
73
74 pub fn set_chat_muted(&mut self, chat_id: &str, muted: bool, cx: &mut Context<Self>) {
75 if self.chat_record(chat_id).is_none() {
76 return;
77 }
78 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
79 return;
80 };
81 let _ = self.store.set_chat_muted(chat_id, muted);
82 self.reload_sidebar(cx);
83 let Some(engine) = engine_or_demo else {
84 return;
85 };
86 let owned_id = chat_id.to_owned();
87 let revert_id = owned_id.clone();
88 self.run_chat_action(
89 if muted { "Mute" } else { "Unmute" },
90 async move { engine.set_chat_muted(&owned_id, muted).await },
91 move |state, cx| {
92 let _ = state.store.set_chat_muted(&revert_id, !muted);
93 state.reload_sidebar(cx);
94 },
95 |_, _| {},
96 cx,
97 );
98 }
99
100 pub fn set_channel_notifications(
101 &mut self,
102 channel_id: &str,
103 notifications: ChannelNotifications,
104 cx: &mut Context<Self>,
105 ) {
106 let Some(previous) = self.channel_notifications(channel_id) else {
107 return;
108 };
109 if previous == notifications {
110 return;
111 }
112 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
113 return;
114 };
115 let _ = self
116 .store
117 .set_channel_notifications(channel_id, notifications);
118 self.reload_sidebar(cx);
119 let Some(engine) = engine_or_demo else {
120 return;
121 };
122 let owned_id = channel_id.to_owned();
123 let revert_id = owned_id.clone();
124 self.run_chat_action(
125 "Change notifications",
126 async move {
127 engine
128 .set_channel_notifications(&owned_id, notifications)
129 .await
130 },
131 move |state, cx| {
132 let _ = state.store.set_channel_notifications(&revert_id, previous);
133 state.reload_sidebar(cx);
134 },
135 |_, _| {},
136 cx,
137 );
138 }
139
140 pub fn channel_notifications(&self, channel_id: &str) -> Option<ChannelNotifications> {
141 self.sidebar.teams.iter().find_map(|team| {
142 team.channels
143 .iter()
144 .any(|channel| channel.id == channel_id)
145 .then(|| team.channel_notifications(channel_id))
146 })
147 }
148
149 pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
150 let Some(chat) = self.chat_record(chat_id) else {
151 return;
152 };
153 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
154 return;
155 };
156 self.remove_chat_locally(chat_id, cx);
157 let Some(engine) = engine_or_demo else {
158 return;
159 };
160 let owned_id = chat_id.to_owned();
161 let undo_id = owned_id.clone();
162 let text = format!("\"{}\" hidden", truncated(&chat_title(&chat), TITLE_LIMIT));
163 self.run_chat_action(
164 "Hide",
165 async move { engine.hide_chat(&owned_id).await },
166 move |state, cx| state.restore_chat_locally(&chat, cx),
167 move |state, cx| {
168 let undo =
169 NoticeAction::new("Undo", move |state, cx| state.unhide_chat(&undo_id, cx));
170 state.raise_notice(text, Some(undo), cx);
171 },
172 cx,
173 );
174 }
175
176 pub fn unhide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
177 let Some(engine) = self.chat_action_engine(cx).flatten() else {
178 return;
179 };
180 let owned_id = chat_id.to_owned();
181 self.run_chat_action(
182 "Undo",
183 async move { engine.unhide_chat(&owned_id).await },
184 |_, _| {},
185 |_, _| {},
186 cx,
187 );
188 }
189
190 pub fn leave_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
191 let Some(chat) = self.chat_record(chat_id) else {
192 return;
193 };
194 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
195 return;
196 };
197 self.remove_chat_locally(chat_id, cx);
198 let Some(engine) = engine_or_demo else {
199 return;
200 };
201 let owned_id = chat_id.to_owned();
202 self.run_chat_action(
203 "Leave chat",
204 async move { engine.leave_chat(&owned_id).await },
205 move |state, cx| state.restore_chat_locally(&chat, cx),
206 |_, _| {},
207 cx,
208 );
209 }
210
211 pub fn remove_chat_member(&mut self, chat_id: &str, user_id: &str, cx: &mut Context<Self>) {
212 let Some(chat) = self.chat_record(chat_id) else {
213 return;
214 };
215 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
216 return;
217 };
218 let mut without_member = chat.clone();
219 without_member
220 .members
221 .retain(|member| member.user_id.as_deref() != Some(user_id));
222 let _ = self
223 .store
224 .upsert_chats(std::slice::from_ref(&without_member));
225 self.reload_sidebar(cx);
226 let Some(engine) = engine_or_demo else {
227 return;
228 };
229 let (owned_chat_id, owned_user_id) = (chat_id.to_owned(), user_id.to_owned());
230 self.run_chat_action(
231 "Remove from chat",
232 async move {
233 engine
234 .remove_chat_member(&owned_chat_id, &owned_user_id)
235 .await
236 },
237 move |state, cx| state.restore_chat_locally(&chat, cx),
238 |_, _| {},
239 cx,
240 );
241 }
242
243 pub fn add_chat_members(
244 &mut self,
245 chat_id: &str,
246 people: Vec<MemberRecord>,
247 share: HistoryShare,
248 cx: &mut Context<Self>,
249 ) {
250 let Some(chat) = self.chat_record(chat_id) else {
251 return;
252 };
253 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
254 return;
255 };
256 let mut with_members = chat.clone();
257 merge_members(&mut with_members.members, &people);
258 let _ = self.store.upsert_chats(std::slice::from_ref(&with_members));
259 self.reload_sidebar(cx);
260 let Some(engine) = engine_or_demo else {
261 self.add_demo_roster_line(chat_id, &people, share, cx);
262 return;
263 };
264 let owned_chat_id = chat_id.to_owned();
265 self.run_chat_action(
266 "Add people",
267 async move {
268 engine
269 .add_chat_members(&owned_chat_id, &people, share)
270 .await
271 },
272 move |state, cx| state.restore_chat_locally(&chat, cx),
273 |_, _| {},
274 cx,
275 );
276 }
277
278 fn add_demo_roster_line(
279 &mut self,
280 chat_id: &str,
281 people: &[MemberRecord],
282 share: HistoryShare,
283 cx: &mut Context<Self>,
284 ) {
285 let me = self.directory.me.as_ref();
286 let event = RosterEvent {
287 change: RosterChange::Added,
288 initiator_id: me.map(|person| person.user_id.clone()),
289 initiator_name: me.map(|person| person.display_name.clone()),
290 member_ids: people
291 .iter()
292 .filter_map(|person| person.user_id.clone())
293 .collect(),
294 member_names: people
295 .iter()
296 .map(|person| Some(person.display_name.clone()))
297 .collect(),
298 history: match share {
299 HistoryShare::None => SharedHistory::None,
300 HistoryShare::Days(days) => SharedHistory::Days(days),
301 HistoryShare::All => SharedHistory::All,
302 },
303 topic: None,
304 };
305 self.store_demo_roster_line(chat_id, &event, cx);
306 }
307
308 fn store_demo_roster_line(
309 &mut self,
310 chat_id: &str,
311 event: &RosterEvent,
312 cx: &mut Context<Self>,
313 ) {
314 let now = Utc::now();
315 let record = crate::demo::roster_record(
316 chat_id,
317 &format!("demo-roster-{}", now.timestamp_millis()),
318 now,
319 event,
320 );
321 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
322 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
323 cx.notify();
324 }
325
326 /// Teams' "Remove chat history": hidden for me only until a newer message arrives.
327 pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {
328 let Some(chat) = self.chat_record(chat_id) else {
329 return;
330 };
331 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
332 return;
333 };
334 self.remove_chat_locally(chat_id, cx);
335 let Some(engine) = engine_or_demo else {
336 return;
337 };
338 let owned_id = chat_id.to_owned();
339 self.run_chat_action(
340 "Remove chat history",
341 async move { engine.remove_chat_history(&owned_id).await },
342 move |state, cx| state.restore_chat_locally(&chat, cx),
343 |_, _| {},
344 cx,
345 );
346 }
347
348 pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {
349 let Some(chat) = self.chat_record(chat_id) else {
350 return;
351 };
352 let topic = topic.trim().to_owned();
353 if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {
354 return;
355 }
356 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
357 return;
358 };
359 let mut renamed = chat.clone();
360 renamed.title = topic.clone();
361 let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));
362 self.reload_sidebar(cx);
363 let Some(engine) = engine_or_demo else {
364 let me = self.directory.me.as_ref();
365 let event = RosterEvent {
366 change: RosterChange::Renamed,
367 initiator_id: me.map(|person| person.user_id.clone()),
368 initiator_name: me.map(|person| person.display_name.clone()),
369 member_ids: Vec::new(),
370 member_names: Vec::new(),
371 history: SharedHistory::None,
372 topic: (!topic.is_empty()).then(|| topic.clone()),
373 };
374 self.store_demo_roster_line(chat_id, &event, cx);
375 return;
376 };
377 let owned_id = chat_id.to_owned();
378 self.run_chat_action(
379 "Rename group chat",
380 async move { engine.rename_chat(&owned_id, &topic).await },
381 move |state, cx| state.restore_chat_locally(&chat, cx),
382 |_, _| {},
383 cx,
384 );
385 }
386
387 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
388 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
389 self.new_chat_people = people;
390 self.start_new_chat(cx);
391 }
392
393 pub(crate) fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
394 self.sidebar
395 .chats
396 .iter()
397 .find(|chat| chat.id == chat_id)
398 .cloned()
399 }
400
401 /// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
402 pub fn chat_action_engine(
403 &mut self,
404 cx: &mut Context<Self>,
405 ) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
406 if self.mode.read_only {
407 self.raise_notice("Read-only mode: chat not changed".to_owned(), None, cx);
408 return None;
409 }
410 match self.engine.clone() {
411 Some(engine) => Some(Some(engine)),
412 None if self.mode.demo => Some(None),
413 None => None,
414 }
415 }
416
417 fn remove_chat_locally(&mut self, chat_id: &str, cx: &mut Context<Self>) {
418 let was_selected = self.selection == Some(Selection::Chat(chat_id.to_owned()));
419 let next = was_selected
420 .then(|| self.next_chat_after(chat_id))
421 .flatten();
422 let _ = self.store.remove_chats(&[chat_id.to_owned()]);
423 self.reload_sidebar(cx);
424 if was_selected {
425 self.leave_removed_selection(next, cx);
426 }
427 }
428
429 fn leave_removed_selection(&mut self, next: Option<String>, cx: &mut Context<Self>) {
430 match next {
431 Some(next_id) => self.select(Selection::Chat(next_id), cx),
432 None => {
433 self.selection = None;
434 self.keep_unread = None;
435 cx.emit(crate::app_state::AppEvent::Selection);
436 cx.notify();
437 }
438 }
439 }
440
441 pub fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
442 let selected = match &self.selection {
443 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
444 _ => None,
445 };
446 let is_listed =
447 |state: &Self, chat_id: &str| state.sidebar.chats.iter().any(|chat| chat.id == chat_id);
448 let was_listed = selected
449 .as_deref()
450 .is_some_and(|chat_id| is_listed(self, chat_id));
451 let next = selected
452 .as_deref()
453 .filter(|_| was_listed)
454 .and_then(|chat_id| self.next_chat_after(chat_id));
455 self.reload_sidebar(cx);
456 let removed = was_listed
457 && selected
458 .as_deref()
459 .is_some_and(|chat_id| !is_listed(self, chat_id));
460 if removed {
461 self.leave_removed_selection(next, cx);
462 }
463 }
464
465 fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {
466 let _ = self.store.upsert_chats(std::slice::from_ref(chat));
467 let _ = self.store.set_chat_muted(&chat.id, chat.muted);
468 self.reload_sidebar(cx);
469 }
470
471 fn next_chat_after(&self, chat_id: &str) -> Option<String> {
472 next_chat_id(&self.chat_sections(), chat_id)
473 }
474
475 pub fn adjacent_chat_id(&self, step: Step) -> Option<String> {
476 let current = match &self.selection {
477 Some(Selection::Chat(chat_id)) => Some(chat_id.as_str()),
478 _ => None,
479 };
480 step_id(&visible_chat_ids(&self.chat_sections()), current, step)
481 }
482
483 fn chat_sections(&self) -> Vec<Section> {
484 let input = SectionInput {
485 chats: &self.sidebar.chats,
486 directory: &self.directory,
487 collapsed: &self.collapsed,
488 expanded_lists: &self.expanded_lists,
489 typing: &self.typing,
490 now: Utc::now(),
491 offset: Local::now().offset().fix(),
492 };
493 build_sections(&input)
494 }
495
496 pub fn run_chat_action(
497 &mut self,
498 label: &'static str,
499 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
500 revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
501 on_success: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
502 cx: &mut Context<Self>,
503 ) {
504 let receiver = crate::runtime::spawn(call);
505 cx.spawn(async move |this, cx| {
506 let failure = match receiver.await {
507 Ok(Ok(())) => None,
508 Ok(Err(error)) => Some(short_error(&error)),
509 Err(_) => Some("cancelled".to_owned()),
510 };
511 this.update(cx, |state, cx| match failure {
512 None => on_success(state, cx),
513 Some(reason) => {
514 revert(state, cx);
515 state.raise_notice(format!("{label} failed: {reason}"), None, cx);
516 }
517 })
518 .ok();
519 })
520 .detach();
521 }
522}