BlueGit

ict rusty-teams

Files

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

chat_actions.rs

16435fd3 History
chat_actions.rs 15.3 KiB Download Raw
1use std::future::Future;
2
3use chrono::{DateTime, Duration, Local, Offset, Utc};
4use gpui_kit::*;
5use chatsvc::HistoryShare;
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
259 .store
260 .upsert_chats(std::slice::from_ref(&with_members));
261 self.reload_sidebar(cx);
262 let Some(engine) = engine_or_demo else {
263 self.add_demo_roster_line(chat_id, &people, share, cx);
264 return;
265 };
266 let owned_chat_id = chat_id.to_owned();
267 self.run_chat_action(
268 "Add people",
269 async move {
270 engine
271 .add_chat_members(&owned_chat_id, &people, share)
272 .await
273 },
274 move |state, cx| state.restore_chat_locally(&chat, cx),
275 |_, _| {},
276 cx,
277 );
278 }
279
280 fn add_demo_roster_line(
281 &mut self,
282 chat_id: &str,
283 people: &[MemberRecord],
284 share: HistoryShare,
285 cx: &mut Context<Self>,
286 ) {
287 let me = self.directory.me.as_ref();
288 let event = RosterEvent {
289 change: RosterChange::Added,
290 initiator_id: me.map(|person| person.user_id.clone()),
291 initiator_name: me.map(|person| person.display_name.clone()),
292 member_ids: people
293 .iter()
294 .filter_map(|person| person.user_id.clone())
295 .collect(),
296 member_names: people
297 .iter()
298 .map(|person| Some(person.display_name.clone()))
299 .collect(),
300 history: match share {
301 HistoryShare::None => SharedHistory::None,
302 HistoryShare::Days(days) => SharedHistory::Days(days),
303 HistoryShare::All => SharedHistory::All,
304 },
305 };
306 let now = Utc::now();
307 let record = crate::demo::roster_record(
308 chat_id,
309 &format!("demo-roster-{}", now.timestamp_millis()),
310 now,
311 &event,
312 );
313 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
314 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
315 cx.notify();
316 }
317
318 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
319 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
320 self.new_chat_people = people;
321 self.start_new_chat(cx);
322 }
323
324 fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
325 self.sidebar
326 .chats
327 .iter()
328 .find(|chat| chat.id == chat_id)
329 .cloned()
330 }
331
332 /// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
333 pub fn chat_action_engine(
334 &mut self,
335 cx: &mut Context<Self>,
336 ) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
337 if self.mode.read_only {
338 self.raise_notice("Read-only mode: chat not changed".to_owned(), None, cx);
339 return None;
340 }
341 match self.engine.clone() {
342 Some(engine) => Some(Some(engine)),
343 None if self.mode.demo => Some(None),
344 None => None,
345 }
346 }
347
348 fn remove_chat_locally(&mut self, chat_id: &str, cx: &mut Context<Self>) {
349 let was_selected = self.selection == Some(Selection::Chat(chat_id.to_owned()));
350 let next = was_selected
351 .then(|| self.next_chat_after(chat_id))
352 .flatten();
353 let _ = self.store.remove_chats(&[chat_id.to_owned()]);
354 self.reload_sidebar(cx);
355 if was_selected {
356 self.leave_removed_selection(next, cx);
357 }
358 }
359
360 fn leave_removed_selection(&mut self, next: Option<String>, cx: &mut Context<Self>) {
361 match next {
362 Some(next_id) => self.select(Selection::Chat(next_id), cx),
363 None => {
364 self.selection = None;
365 self.keep_unread = None;
366 cx.emit(crate::app_state::AppEvent::Selection);
367 cx.notify();
368 }
369 }
370 }
371
372 pub fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
373 let selected = match &self.selection {
374 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
375 _ => None,
376 };
377 let is_listed =
378 |state: &Self, chat_id: &str| state.sidebar.chats.iter().any(|chat| chat.id == chat_id);
379 let was_listed = selected
380 .as_deref()
381 .is_some_and(|chat_id| is_listed(self, chat_id));
382 let next = selected
383 .as_deref()
384 .filter(|_| was_listed)
385 .and_then(|chat_id| self.next_chat_after(chat_id));
386 self.reload_sidebar(cx);
387 let removed = was_listed
388 && selected
389 .as_deref()
390 .is_some_and(|chat_id| !is_listed(self, chat_id));
391 if removed {
392 self.leave_removed_selection(next, cx);
393 }
394 }
395
396 fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {
397 let _ = self.store.upsert_chats(std::slice::from_ref(chat));
398 let _ = self.store.set_chat_muted(&chat.id, chat.muted);
399 self.reload_sidebar(cx);
400 }
401
402 fn next_chat_after(&self, chat_id: &str) -> Option<String> {
403 next_chat_id(&self.chat_sections(), chat_id)
404 }
405
406 pub fn adjacent_chat_id(&self, step: Step) -> Option<String> {
407 let current = match &self.selection {
408 Some(Selection::Chat(chat_id)) => Some(chat_id.as_str()),
409 _ => None,
410 };
411 step_id(&visible_chat_ids(&self.chat_sections()), current, step)
412 }
413
414 fn chat_sections(&self) -> Vec<Section> {
415 let input = SectionInput {
416 chats: &self.sidebar.chats,
417 directory: &self.directory,
418 collapsed: &self.collapsed,
419 expanded_lists: &self.expanded_lists,
420 typing: &self.typing,
421 now: Utc::now(),
422 offset: Local::now().offset().fix(),
423 };
424 build_sections(&input)
425 }
426
427 pub fn run_chat_action(
428 &mut self,
429 label: &'static str,
430 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
431 revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
432 on_success: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
433 cx: &mut Context<Self>,
434 ) {
435 let receiver = crate::runtime::spawn(call);
436 cx.spawn(async move |this, cx| {
437 let failure = match receiver.await {
438 Ok(Ok(())) => None,
439 Ok(Err(error)) => Some(short_error(&error)),
440 Err(_) => Some("cancelled".to_owned()),
441 };
442 this.update(cx, |state, cx| match failure {
443 None => on_success(state, cx),
444 Some(reason) => {
445 revert(state, cx);
446 state.raise_notice(format!("{label} failed: {reason}"), None, cx);
447 }
448 })
449 .ok();
450 })
451 .detach();
452 }
453}