BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / conversation / recap.rs

recap.rs

recap.rs 19.9 KiB Download Raw
1use std::collections::HashMap;
2use std::io::Write as _;
3use std::path::PathBuf;
4use std::rc::Rc;
5
6use chatsvc::{
7 Attendance, Occurrence, Recap, RecordingDetails, TranscriptFormat, TranscriptTurn,
8};
9use chrono::Utc;
10use gpui_kit::component::button::{Button, ButtonVariants as _};
11use gpui_kit::component::dialog::DialogFooter;
12use gpui_kit::component::input::{InputEvent, InputState};
13use gpui_kit::component::WindowExt as _;
14use gpui_kit::*;
15
16use super::ConversationView;
17use crate::app_state::Selection;
18use crate::channel_files::SharedContent;
19use crate::demo_recap;
20use crate::downloads::{self, DownloadState};
21use crate::notice::short_error;
22use crate::recap::{DELETE_QUESTION, Load, save_name};
23use crate::runtime;
24use crate::views::channel_tabs::{ChannelPane, render_meeting_bar};
25use crate::views::recap_tab::{RecapCommand, RecapDownload, RecapRun, RecapView, render_recap};
26use crate::views::shared_tab::{SharedCommand, SharedRun};
27
28const SEARCH_PLACEHOLDER: &str = "Search transcript";
29const RECORDING_EXTENSION: &str = "mp4";
30
31pub(super) fn search_input(
32 window: &mut Window,
33 cx: &mut Context<ConversationView>,
34) -> Entity<InputState> {
35 cx.new(|cx| InputState::new(window, cx).placeholder(SEARCH_PLACEHOLDER))
36}
37
38pub(super) struct RecapState {
39 listing: Load<Vec<Occurrence>>,
40 selected: usize,
41 details: Load<RecordingDetails>,
42 transcript: Load<Vec<TranscriptTurn>>,
43 attendance: Load<Attendance>,
44 query: String,
45 downloads: HashMap<RecapDownload, DownloadState>,
46 generation: u64,
47}
48
49impl Default for RecapState {
50 fn default() -> Self {
51 RecapState {
52 listing: Load::Loading,
53 selected: 0,
54 details: Load::Loading,
55 transcript: Load::Loading,
56 attendance: Load::Loading,
57 query: String::new(),
58 downloads: HashMap::new(),
59 generation: 0,
60 }
61 }
62}
63
64enum SaveEvent {
65 Progress(u8),
66 Finished(Result<PathBuf, String>),
67}
68
69impl ConversationView {
70 fn is_meeting_chat(&self, cx: &App) -> bool {
71 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|current| &current.selection)
72 else {
73 return false;
74 };
75 self.app
76 .read(cx)
77 .sidebar
78 .chats
79 .iter()
80 .any(|chat| &chat.id == chat_id && chat.kind.eq_ignore_ascii_case("meeting"))
81 }
82
83 fn occurrences(&self) -> &[Occurrence] {
84 self.recap.listing.ready().map_or(&[], Vec::as_slice)
85 }
86
87 fn selected_occurrence(&self) -> Option<Occurrence> {
88 self.occurrences().get(self.recap.selected).cloned()
89 }
90
91 pub(super) fn recap_active(&self) -> bool {
92 self.pane == ChannelPane::Recap && !self.occurrences().is_empty()
93 }
94
95 pub(super) fn on_recap_search_event(
96 &mut self,
97 input: &Entity<InputState>,
98 event: &InputEvent,
99 _: &mut Window,
100 cx: &mut Context<Self>,
101 ) {
102 if matches!(event, InputEvent::Change) {
103 self.recap.query = input.read(cx).value().to_string();
104 cx.notify();
105 }
106 }
107
108 pub(super) fn reset_recap(&mut self, cx: &mut Context<Self>) {
109 self.recap = RecapState {
110 generation: self.recap.generation + 1,
111 ..RecapState::default()
112 };
113 if !self.is_meeting_chat(cx) {
114 return;
115 }
116 let Some(conversation_id) = self.conversation_id() else {
117 return;
118 };
119 let state = self.app.read(cx);
120 let (demo, engine) = (state.mode.demo, state.engine.clone());
121 if demo {
122 self.recap.listing = Load::Ready(demo_recap::occurrences(&conversation_id, Utc::now()));
123 return;
124 }
125 let Some(engine) = engine else {
126 return;
127 };
128 let generation = self.recap.generation;
129 let receiver = runtime::spawn(async move {
130 Recap::new(engine.remote().session())
131 .occurrences(&conversation_id)
132 .await
133 });
134 cx.spawn(async move |this, cx| {
135 let outcome = match receiver.await {
136 Ok(Ok(occurrences)) => Ok(occurrences),
137 Ok(Err(error)) => Err(short_error(&error)),
138 Err(error) => Err(short_error(&error)),
139 };
140 this.update(cx, |this, cx| {
141 if generation != this.recap.generation {
142 return;
143 }
144 this.recap.listing = match outcome {
145 Ok(occurrences) => Load::Ready(occurrences),
146 Err(reason) => Load::Failed(reason),
147 };
148 if this.pane == ChannelPane::Recap {
149 this.select_occurrence(0, cx);
150 }
151 cx.notify();
152 })
153 .ok();
154 })
155 .detach();
156 }
157
158 pub(super) fn open_recap_pane(&mut self, cx: &mut Context<Self>) {
159 self.refresh_shared_items(cx);
160 if matches!(self.recap.details, Load::Loading) {
161 self.select_occurrence(0, cx);
162 }
163 }
164
165 fn select_occurrence(&mut self, index: usize, cx: &mut Context<Self>) {
166 let Some(occurrence) = self.occurrences().get(index).cloned() else {
167 return;
168 };
169 self.recap.selected = index;
170 self.recap.details = Load::Loading;
171 self.recap.transcript = Load::Loading;
172 self.recap.attendance = Load::Loading;
173 self.recap.downloads.clear();
174 self.recap.generation += 1;
175 let generation = self.recap.generation;
176 cx.notify();
177 let state = self.app.read(cx);
178 let (demo, engine) = (state.mode.demo, state.engine.clone());
179 if demo {
180 let now = Utc::now();
181 self.recap.details = Load::Ready(demo_recap::details(&occurrence, now));
182 self.recap.transcript = Load::Ready(demo_recap::transcript());
183 self.recap.attendance = Load::Ready(demo_recap::attendance(now));
184 return;
185 }
186 let (Some(engine), Some(conversation_id)) = (engine, self.conversation_id()) else {
187 return;
188 };
189 let attendance_engine = engine.clone();
190 let loaded = runtime::spawn(async move {
191 let recap = Recap::new(engine.remote().session());
192 let details = recap.details(&occurrence).await?;
193 let transcript = recap.transcript(&details).await.ok();
194 Ok::<_, chatsvc::TranscriptError>((details, transcript))
195 });
196 let attendance = runtime::spawn(async move {
197 Recap::new(attendance_engine.remote().session())
198 .attendance(&conversation_id)
199 .await
200 });
201 cx.spawn(async move |this, cx| {
202 let loaded = match loaded.await {
203 Ok(Ok(loaded)) => Ok(loaded),
204 Ok(Err(error)) => Err(short_error(&error)),
205 Err(error) => Err(short_error(&error)),
206 };
207 this.update(cx, |this, cx| {
208 if generation != this.recap.generation {
209 return;
210 }
211 match loaded {
212 Ok((details, transcript)) => {
213 this.recap.details = Load::Ready(details);
214 this.recap.transcript = Load::Ready(transcript.unwrap_or_default());
215 }
216 Err(reason) => {
217 this.recap.details = Load::Failed(reason.clone());
218 this.recap.transcript = Load::Failed(reason);
219 }
220 }
221 cx.notify();
222 })
223 .ok();
224 })
225 .detach();
226 cx.spawn(async move |this, cx| {
227 let outcome = match attendance.await {
228 Ok(Ok(attendance)) => Ok(attendance),
229 Ok(Err(error)) => Err(short_error(&error)),
230 Err(error) => Err(short_error(&error)),
231 };
232 this.update(cx, |this, cx| {
233 if generation != this.recap.generation {
234 return;
235 }
236 this.recap.attendance = match outcome {
237 Ok(attendance) => Load::Ready(attendance),
238 Err(reason) => Load::Failed(reason),
239 };
240 cx.notify();
241 })
242 .ok();
243 })
244 .detach();
245 }
246
247 pub(super) fn render_meeting_tab_bar(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
248 if self.occurrences().is_empty() || !self.is_meeting_chat(cx) {
249 return None;
250 }
251 let view = cx.weak_entity();
252 let select = Rc::new(move |pane, cx: &mut App| {
253 view.update(cx, |this, cx| this.select_pane(pane, cx)).ok();
254 });
255 Some(render_meeting_bar(self.pane, select))
256 }
257
258 pub(super) fn render_recap(&self, cx: &mut Context<Self>) -> AnyElement {
259 let view = cx.weak_entity();
260 let run: RecapRun = Rc::new(move |command, window, cx| {
261 view.update(cx, |this, cx| this.run_recap(command, window, cx))
262 .ok();
263 });
264 let file_indices: Rc<Vec<usize>> = Rc::new(
265 self.shared
266 .items
267 .iter()
268 .enumerate()
269 .filter(|(_, item)| matches!(item.content, SharedContent::File(_)))
270 .map(|(index, _)| index)
271 .collect(),
272 );
273 let file_states = self.item_download_states();
274 let files = file_indices
275 .iter()
276 .map(|index| self.shared.items[*index].clone())
277 .collect::<Vec<_>>();
278 let file_labels = file_indices
279 .iter()
280 .map(|index| {
281 crate::views::shared_tab::download_label(
282 file_states.get(*index).and_then(Option::as_ref),
283 )
284 })
285 .collect();
286 let file_run: SharedRun = {
287 let view = cx.weak_entity();
288 Rc::new(move |command, window, cx| {
289 let command = match command {
290 SharedCommand::OpenItem(index) => SharedCommand::OpenItem(file_indices[index]),
291 SharedCommand::JumpToPost(index) => {
292 SharedCommand::JumpToPost(file_indices[index])
293 }
294 other => other,
295 };
296 view.update(cx, |this, cx| {
297 if matches!(command, SharedCommand::JumpToPost(_)) {
298 this.pane = ChannelPane::Posts;
299 }
300 this.run_shared(command, window, cx)
301 })
302 .ok();
303 })
304 };
305 let can_delete = self.can_delete_recording(cx);
306 render_recap(
307 RecapView {
308 occurrences: self.occurrences(),
309 selected: self.recap.selected,
310 details: &self.recap.details,
311 transcript: &self.recap.transcript,
312 attendance: &self.recap.attendance,
313 search: &self.recap_search,
314 query: &self.recap.query,
315 can_delete,
316 recording_state: self.recap.downloads.get(&RecapDownload::Recording),
317 vtt_state: self
318 .recap
319 .downloads
320 .get(&RecapDownload::Transcript(TranscriptFormat::Vtt)),
321 docx_state: self
322 .recap
323 .downloads
324 .get(&RecapDownload::Transcript(TranscriptFormat::Docx)),
325 files: &files,
326 file_labels,
327 file_run,
328 now: Utc::now(),
329 },
330 &run,
331 )
332 }
333
334 fn can_delete_recording(&self, cx: &App) -> bool {
335 let my_user_id = self.app.read(cx).directory.me.as_ref().map(|me| me.user_id.as_str());
336 match (self.selected_occurrence(), my_user_id) {
337 (Some(occurrence), Some(my_user_id)) => {
338 occurrence.organizer_id.as_deref() == Some(my_user_id)
339 }
340 _ => false,
341 }
342 }
343
344 fn run_recap(&mut self, command: RecapCommand, window: &mut Window, cx: &mut Context<Self>) {
345 match command {
346 RecapCommand::Occurrence(index) => self.select_occurrence(index, cx),
347 RecapCommand::Retry => self.select_occurrence(self.recap.selected, cx),
348 RecapCommand::Play => {
349 if let Some(occurrence) = self.selected_occurrence() {
350 cx.open_url(&occurrence.recording_url);
351 }
352 }
353 RecapCommand::Download(download) => self.pick_save_target(download, cx),
354 RecapCommand::AskDelete => self.confirm_delete(window, cx),
355 }
356 }
357
358 fn confirm_delete(&mut self, window: &mut Window, cx: &mut Context<Self>) {
359 let view = cx.weak_entity();
360 window.open_alert_dialog(cx, move |alert, _, _| {
361 let view = view.clone();
362 let cancel = Button::new("recap-delete-cancel")
363 .label("Cancel")
364 .on_click(|_, window, cx| window.close_dialog(cx));
365 let delete = Button::new("recap-delete-confirm")
366 .label("Delete")
367 .danger()
368 .on_click(move |_, window, cx| {
369 view.update(cx, |this, cx| this.delete_recording(cx)).ok();
370 window.close_dialog(cx);
371 });
372 alert
373 .title(DELETE_QUESTION)
374 .footer(DialogFooter::new().child(cancel).child(delete))
375 .on_ok(|_, _, _| false)
376 });
377 }
378
379 fn delete_recording(&mut self, cx: &mut Context<Self>) {
380 let (Some(occurrence), Some(details)) = (
381 self.selected_occurrence(),
382 self.recap.details.ready().cloned(),
383 ) else {
384 return;
385 };
386 let state = self.app.read(cx);
387 let (demo, engine) = (state.mode.demo, state.engine.clone());
388 if demo {
389 self.finish_delete(&occurrence, Ok(()), cx);
390 return;
391 }
392 let Some(engine) = engine else {
393 return;
394 };
395 let receiver = runtime::spawn(async move {
396 Recap::new(engine.remote().session())
397 .delete_recording(&details)
398 .await
399 });
400 cx.spawn(async move |this, cx| {
401 let outcome = match receiver.await {
402 Ok(Ok(())) => Ok(()),
403 Ok(Err(error)) => Err(short_error(&error)),
404 Err(error) => Err(short_error(&error)),
405 };
406 this.update(cx, |this, cx| this.finish_delete(&occurrence, outcome, cx))
407 .ok();
408 })
409 .detach();
410 }
411
412 fn finish_delete(
413 &mut self,
414 occurrence: &Occurrence,
415 outcome: Result<(), String>,
416 cx: &mut Context<Self>,
417 ) {
418 if let Err(reason) = outcome {
419 self.notice = Some(format!("Recording not deleted: {reason}"));
420 cx.notify();
421 return;
422 }
423 let remaining: Vec<Occurrence> = self
424 .occurrences()
425 .iter()
426 .filter(|other| other.message_id != occurrence.message_id)
427 .cloned()
428 .collect();
429 let empty = remaining.is_empty();
430 self.recap.listing = Load::Ready(remaining);
431 if empty {
432 self.pane = ChannelPane::Posts;
433 cx.notify();
434 } else {
435 self.select_occurrence(0, cx);
436 }
437 }
438
439 fn pick_save_target(&mut self, download: RecapDownload, cx: &mut Context<Self>) {
440 let Some(occurrence) = self.selected_occurrence() else {
441 return;
442 };
443 if matches!(
444 self.recap.downloads.get(&download),
445 Some(DownloadState::Saving(_))
446 ) {
447 return;
448 }
449 let extension = match download {
450 RecapDownload::Recording => RECORDING_EXTENSION,
451 RecapDownload::Transcript(format) => format.query(),
452 };
453 let name = save_name(&occurrence, extension);
454 let receiver = cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name));
455 cx.spawn(async move |this, cx| {
456 if let Ok(Ok(Some(target))) = receiver.await {
457 this.update(cx, |this, cx| this.save_to(download, occurrence, target, cx))
458 .ok();
459 }
460 })
461 .detach();
462 }
463
464 fn save_to(
465 &mut self,
466 download: RecapDownload,
467 occurrence: Occurrence,
468 target: PathBuf,
469 cx: &mut Context<Self>,
470 ) {
471 self.recap
472 .downloads
473 .insert(download, DownloadState::Saving(0));
474 cx.notify();
475 let generation = self.recap.generation;
476 let state = self.app.read(cx);
477 let (demo, engine) = (state.mode.demo, state.engine.clone());
478 let details = self.recap.details.ready().cloned();
479 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<SaveEvent>();
480 if demo {
481 let outcome = std::fs::write(&target, demo_recap::DEMO_FILE_BYTES)
482 .map(|_| target)
483 .map_err(|error| short_error(&error));
484 self.recap.downloads.insert(download, finished_state(outcome));
485 return;
486 }
487 let (Some(engine), Some(details)) = (engine, details) else {
488 self.recap
489 .downloads
490 .insert(download, DownloadState::Failed("not connected".to_owned()));
491 return;
492 };
493 drop(runtime::spawn(async move {
494 let outcome = save_download(&engine, download, &occurrence, &details, target, &sender)
495 .await;
496 let _ = sender.send(SaveEvent::Finished(outcome));
497 }));
498 cx.spawn(async move |this, cx| {
499 while let Some(event) = receiver.recv().await {
500 let updated = this.update(cx, |this, cx| {
501 if generation == this.recap.generation {
502 match event {
503 SaveEvent::Progress(percent) => {
504 this.recap
505 .downloads
506 .insert(download, DownloadState::Saving(percent));
507 }
508 SaveEvent::Finished(outcome) => {
509 this.recap.downloads.insert(download, finished_state(outcome));
510 }
511 }
512 }
513 cx.notify();
514 });
515 if updated.is_err() {
516 return;
517 }
518 }
519 })
520 .detach();
521 }
522}
523
524fn finished_state(outcome: Result<PathBuf, String>) -> DownloadState {
525 match outcome {
526 Ok(path) => DownloadState::Saved(path),
527 Err(reason) => DownloadState::Failed(reason),
528 }
529}
530
531async fn save_download(
532 engine: &crate::backend::Engine,
533 download: RecapDownload,
534 occurrence: &Occurrence,
535 details: &RecordingDetails,
536 target: PathBuf,
537 events: &tokio::sync::mpsc::UnboundedSender<SaveEvent>,
538) -> Result<PathBuf, String> {
539 match download {
540 RecapDownload::Transcript(format) => {
541 let bytes = Recap::new(engine.remote().session())
542 .transcript_file(details, format)
543 .await
544 .map_err(|error| short_error(&error))?;
545 std::fs::write(&target, bytes).map_err(|error| short_error(&error))?;
546 }
547 RecapDownload::Recording => {
548 let mut file = std::fs::File::create(&target).map_err(|error| short_error(&error))?;
549 let progress = |percent| {
550 let _ = events.send(SaveEvent::Progress(percent));
551 };
552 let result = engine
553 .download_file(
554 &occurrence.recording_url,
555 |bytes: &[u8]| file.write_all(bytes),
556 progress,
557 )
558 .await;
559 if let Err(error) = result {
560 drop(file);
561 let _ = std::fs::remove_file(&target);
562 return Err(short_error(&error));
563 }
564 }
565 }
566 Ok(target)
567}