BlueGit

ict rusty-teams

Files

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

chat_actions.rs

chat_actions.rs 17.3 KiB Download Raw
1use std::future::Future;
2
3use chatsvc::HistoryShare;
4use chrono::{DateTime, Duration, 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 app_name: None,
306 };
307 self.store_demo_roster_line(chat_id, &event, cx);
308 }
309
310 fn store_demo_roster_line(
311 &mut self,
312 chat_id: &str,
313 event: &RosterEvent,
314 cx: &mut Context<Self>,
315 ) {
316 let now = Utc::now();
317 let record = crate::demo::roster_record(
318 chat_id,
319 &format!("demo-roster-{}", now.timestamp_millis()),
320 now,
321 event,
322 );
323 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
324 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
325 cx.notify();
326 }
327
328 /// Teams' "Remove chat history": hidden for me only until a newer message arrives.
329 pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {
330 let Some(chat) = self.chat_record(chat_id) else {
331 return;
332 };
333 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
334 return;
335 };
336 self.remove_chat_locally(chat_id, cx);
337 let Some(engine) = engine_or_demo else {
338 return;
339 };
340 let owned_id = chat_id.to_owned();
341 self.run_chat_action(
342 "Remove chat history",
343 async move { engine.remove_chat_history(&owned_id).await },
344 move |state, cx| state.restore_chat_locally(&chat, cx),
345 |_, _| {},
346 cx,
347 );
348 }
349
350 pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {
351 let Some(chat) = self.chat_record(chat_id) else {
352 return;
353 };
354 let topic = topic.trim().to_owned();
355 if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {
356 return;
357 }
358 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
359 return;
360 };
361 let mut renamed = chat.clone();
362 renamed.title = topic.clone();
363 let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));
364 self.reload_sidebar(cx);
365 let Some(engine) = engine_or_demo else {
366 let me = self.directory.me.as_ref();
367 let event = RosterEvent {
368 change: RosterChange::Renamed,
369 initiator_id: me.map(|person| person.user_id.clone()),
370 initiator_name: me.map(|person| person.display_name.clone()),
371 member_ids: Vec::new(),
372 member_names: Vec::new(),
373 history: SharedHistory::None,
374 topic: (!topic.is_empty()).then(|| topic.clone()),
375 app_name: None,
376 };
377 self.store_demo_roster_line(chat_id, &event, cx);
378 return;
379 };
380 let owned_id = chat_id.to_owned();
381 self.run_chat_action(
382 "Rename group chat",
383 async move { engine.rename_chat(&owned_id, &topic).await },
384 move |state, cx| state.restore_chat_locally(&chat, cx),
385 |_, _| {},
386 cx,
387 );
388 }
389
390 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
391 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
392 self.new_chat_people = people;
393 self.start_new_chat(cx);
394 }
395
396 pub(crate) fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
397 self.sidebar
398 .chats
399 .iter()
400 .find(|chat| chat.id == chat_id)
401 .cloned()
402 }
403
404 /// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
405 pub fn chat_action_engine(
406 &mut self,
407 cx: &mut Context<Self>,
408 ) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
409 if self.mode.read_only {
410 self.raise_notice("Read-only mode: chat not changed".to_owned(), None, cx);
411 return None;
412 }
413 match self.engine.clone() {
414 Some(engine) => Some(Some(engine)),
415 None if self.mode.demo => Some(None),
416 None => None,
417 }
418 }
419
420 fn remove_chat_locally(&mut self, chat_id: &str, cx: &mut Context<Self>) {
421 let was_selected = self.selection == Some(Selection::Chat(chat_id.to_owned()));
422 let next = was_selected
423 .then(|| self.next_chat_after(chat_id))
424 .flatten();
425 let _ = self.store.remove_chats(&[chat_id.to_owned()]);
426 self.reload_sidebar(cx);
427 if was_selected {
428 self.leave_removed_selection(next, cx);
429 }
430 }
431
432 pub(crate) fn leave_removed_selection(&mut self, next: Option<String>, cx: &mut Context<Self>) {
433 match next {
434 Some(next_id) => self.select(Selection::Chat(next_id), cx),
435 None => {
436 self.selection = None;
437 self.keep_unread = None;
438 cx.emit(crate::app_state::AppEvent::Selection);
439 cx.notify();
440 }
441 }
442 }
443
444 fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {
445 let _ = self.store.upsert_chats(std::slice::from_ref(chat));
446 let _ = self.store.set_chat_muted(&chat.id, chat.muted);
447 self.reload_sidebar(cx);
448 }
449
450 pub(crate) fn next_chat_after(&self, chat_id: &str) -> Option<String> {
451 next_chat_id(&self.chat_sections(), chat_id)
452 }
453
454 pub fn adjacent_chat_id(&self, step: Step) -> Option<String> {
455 let current = match &self.selection {
456 Some(Selection::Chat(chat_id)) => Some(chat_id.as_str()),
457 _ => None,
458 };
459 step_id(&visible_chat_ids(&self.chat_sections()), current, step)
460 }
461
462 pub fn adjacent_unread_chat_id(&self, step: Step) -> Option<String> {
463 let current = match &self.selection {
464 Some(Selection::Chat(chat_id)) => Some(chat_id.as_str()),
465 _ => None,
466 };
467 step_unread_id(&self.chat_sections(), current, step)
468 }
469
470 fn chat_sections(&self) -> Vec<Section> {
471 let input = SectionInput {
472 chats: &self.sidebar.chats,
473 directory: &self.directory,
474 collapsed: &self.collapsed,
475 expanded_lists: &self.expanded_lists,
476 typing: &self.typing,
477 now: Utc::now(),
478 offset: app_base::format::Zone::Local,
479 };
480 build_sections(&input)
481 }
482
483 pub fn run_chat_action(
484 &mut self,
485 label: &'static str,
486 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
487 revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
488 on_success: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
489 cx: &mut Context<Self>,
490 ) {
491 let receiver = crate::runtime::spawn(call);
492 cx.spawn(async move |this, cx| {
493 let failure = match receiver.await {
494 Ok(Ok(())) => None,
495 Ok(Err(error)) => Some(short_error(&error)),
496 Err(_) => Some("cancelled".to_owned()),
497 };
498 this.update(cx, |state, cx| match failure {
499 None => on_success(state, cx),
500 Some(reason) => {
501 revert(state, cx);
502 state.raise_notice(format!("{label} failed: {reason}"), None, cx);
503 }
504 })
505 .ok();
506 })
507 .detach();
508 }
509}