BlueGit

ict rusty-teams

Files

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

chat_actions.rs

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