BlueGit

ict rusty-teams

Files

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

recap.rs

recap.rs 20.8 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 /// Teams opens a meeting chat recording in the Recap tab at its occurrence and plays any
159 /// other recording (channel meetings) in the browser.
160 pub(super) fn open_recording(
161 &mut self,
162 message_id: &str,
163 url: Option<&str>,
164 cx: &mut Context<Self>,
165 ) {
166 let occurrence = self
167 .occurrences()
168 .iter()
169 .position(|occurrence| occurrence.message_id == message_id);
170 match (occurrence, url) {
171 (Some(index), _) if self.is_meeting_chat(cx) => {
172 self.select_pane(ChannelPane::Recap, cx);
173 if self.recap.selected != index {
174 self.select_occurrence(index, cx);
175 }
176 }
177 (_, Some(url)) => cx.open_url(url),
178 (_, None) => {}
179 }
180 }
181
182 pub(super) fn open_recap_pane(&mut self, cx: &mut Context<Self>) {
183 self.refresh_shared_items(cx);
184 if matches!(self.recap.details, Load::Loading) {
185 self.select_occurrence(0, cx);
186 }
187 }
188
189 fn select_occurrence(&mut self, index: usize, cx: &mut Context<Self>) {
190 let Some(occurrence) = self.occurrences().get(index).cloned() else {
191 return;
192 };
193 self.recap.selected = index;
194 self.recap.details = Load::Loading;
195 self.recap.transcript = Load::Loading;
196 self.recap.attendance = Load::Loading;
197 self.recap.downloads.clear();
198 self.recap.generation += 1;
199 let generation = self.recap.generation;
200 cx.notify();
201 let state = self.app.read(cx);
202 let (demo, engine) = (state.mode.demo, state.engine.clone());
203 if demo {
204 let now = Utc::now();
205 self.recap.details = Load::Ready(demo_recap::details(&occurrence, now));
206 self.recap.transcript = Load::Ready(demo_recap::transcript());
207 self.recap.attendance = Load::Ready(demo_recap::attendance(now));
208 return;
209 }
210 let (Some(engine), Some(conversation_id)) = (engine, self.conversation_id()) else {
211 return;
212 };
213 let attendance_engine = engine.clone();
214 let loaded = runtime::spawn(async move {
215 let recap = Recap::new(engine.remote().session());
216 let details = recap.details(&occurrence).await?;
217 let transcript = recap.transcript(&details).await.ok();
218 Ok::<_, chatsvc::TranscriptError>((details, transcript))
219 });
220 let attendance = runtime::spawn(async move {
221 Recap::new(attendance_engine.remote().session())
222 .attendance(&conversation_id)
223 .await
224 });
225 cx.spawn(async move |this, cx| {
226 let loaded = match loaded.await {
227 Ok(Ok(loaded)) => Ok(loaded),
228 Ok(Err(error)) => Err(short_error(&error)),
229 Err(error) => Err(short_error(&error)),
230 };
231 this.update(cx, |this, cx| {
232 if generation != this.recap.generation {
233 return;
234 }
235 match loaded {
236 Ok((details, transcript)) => {
237 this.recap.details = Load::Ready(details);
238 this.recap.transcript = Load::Ready(transcript.unwrap_or_default());
239 }
240 Err(reason) => {
241 this.recap.details = Load::Failed(reason.clone());
242 this.recap.transcript = Load::Failed(reason);
243 }
244 }
245 cx.notify();
246 })
247 .ok();
248 })
249 .detach();
250 cx.spawn(async move |this, cx| {
251 let outcome = match attendance.await {
252 Ok(Ok(attendance)) => Ok(attendance),
253 Ok(Err(error)) => Err(short_error(&error)),
254 Err(error) => Err(short_error(&error)),
255 };
256 this.update(cx, |this, cx| {
257 if generation != this.recap.generation {
258 return;
259 }
260 this.recap.attendance = match outcome {
261 Ok(attendance) => Load::Ready(attendance),
262 Err(reason) => Load::Failed(reason),
263 };
264 cx.notify();
265 })
266 .ok();
267 })
268 .detach();
269 }
270
271 pub(super) fn render_meeting_tab_bar(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
272 if self.occurrences().is_empty() || !self.is_meeting_chat(cx) {
273 return None;
274 }
275 let view = cx.weak_entity();
276 let select = Rc::new(move |pane, cx: &mut App| {
277 view.update(cx, |this, cx| this.select_pane(pane, cx)).ok();
278 });
279 Some(render_meeting_bar(self.pane, select))
280 }
281
282 pub(super) fn render_recap(&self, cx: &mut Context<Self>) -> AnyElement {
283 let view = cx.weak_entity();
284 let run: RecapRun = Rc::new(move |command, window, cx| {
285 view.update(cx, |this, cx| this.run_recap(command, window, cx))
286 .ok();
287 });
288 let file_indices: Rc<Vec<usize>> = Rc::new(
289 self.shared
290 .items
291 .iter()
292 .enumerate()
293 .filter(|(_, item)| matches!(item.content, SharedContent::File(_)))
294 .map(|(index, _)| index)
295 .collect(),
296 );
297 let file_states = self.item_download_states();
298 let files = file_indices
299 .iter()
300 .map(|index| self.shared.items[*index].clone())
301 .collect::<Vec<_>>();
302 let file_labels = file_indices
303 .iter()
304 .map(|index| {
305 crate::views::shared_tab::download_label(
306 file_states.get(*index).and_then(Option::as_ref),
307 )
308 })
309 .collect();
310 let file_run: SharedRun = {
311 let view = cx.weak_entity();
312 Rc::new(move |command, window, cx| {
313 let command = match command {
314 SharedCommand::OpenItem(index) => SharedCommand::OpenItem(file_indices[index]),
315 SharedCommand::JumpToPost(index) => {
316 SharedCommand::JumpToPost(file_indices[index])
317 }
318 other => other,
319 };
320 view.update(cx, |this, cx| {
321 if matches!(command, SharedCommand::JumpToPost(_)) {
322 this.pane = ChannelPane::Posts;
323 }
324 this.run_shared(command, window, cx)
325 })
326 .ok();
327 })
328 };
329 let can_delete = self.can_delete_recording(cx);
330 render_recap(
331 RecapView {
332 occurrences: self.occurrences(),
333 selected: self.recap.selected,
334 details: &self.recap.details,
335 transcript: &self.recap.transcript,
336 attendance: &self.recap.attendance,
337 search: &self.recap_search,
338 query: &self.recap.query,
339 can_delete,
340 recording_state: self.recap.downloads.get(&RecapDownload::Recording),
341 vtt_state: self
342 .recap
343 .downloads
344 .get(&RecapDownload::Transcript(TranscriptFormat::Vtt)),
345 docx_state: self
346 .recap
347 .downloads
348 .get(&RecapDownload::Transcript(TranscriptFormat::Docx)),
349 files: &files,
350 file_labels,
351 file_run,
352 now: Utc::now(),
353 },
354 &run,
355 )
356 }
357
358 fn can_delete_recording(&self, cx: &App) -> bool {
359 let my_user_id = self.app.read(cx).directory.me.as_ref().map(|me| me.user_id.as_str());
360 match (self.selected_occurrence(), my_user_id) {
361 (Some(occurrence), Some(my_user_id)) => {
362 occurrence.organizer_id.as_deref() == Some(my_user_id)
363 }
364 _ => false,
365 }
366 }
367
368 fn run_recap(&mut self, command: RecapCommand, window: &mut Window, cx: &mut Context<Self>) {
369 match command {
370 RecapCommand::Occurrence(index) => self.select_occurrence(index, cx),
371 RecapCommand::Retry => self.select_occurrence(self.recap.selected, cx),
372 RecapCommand::Play => {
373 if let Some(occurrence) = self.selected_occurrence() {
374 cx.open_url(&occurrence.recording_url);
375 }
376 }
377 RecapCommand::Download(download) => self.pick_save_target(download, cx),
378 RecapCommand::AskDelete => self.confirm_delete(window, cx),
379 }
380 }
381
382 fn confirm_delete(&mut self, window: &mut Window, cx: &mut Context<Self>) {
383 let view = cx.weak_entity();
384 window.open_alert_dialog(cx, move |alert, _, _| {
385 let view = view.clone();
386 let cancel = Button::new("recap-delete-cancel")
387 .label("Cancel")
388 .on_click(|_, window, cx| window.close_dialog(cx));
389 let delete = Button::new("recap-delete-confirm")
390 .label("Delete")
391 .danger()
392 .on_click(move |_, window, cx| {
393 view.update(cx, |this, cx| this.delete_recording(cx)).ok();
394 window.close_dialog(cx);
395 });
396 alert
397 .title(DELETE_QUESTION)
398 .footer(DialogFooter::new().child(cancel).child(delete))
399 .on_ok(|_, _, _| false)
400 });
401 }
402
403 fn delete_recording(&mut self, cx: &mut Context<Self>) {
404 let (Some(occurrence), Some(details)) = (
405 self.selected_occurrence(),
406 self.recap.details.ready().cloned(),
407 ) else {
408 return;
409 };
410 let state = self.app.read(cx);
411 let (demo, engine) = (state.mode.demo, state.engine.clone());
412 if demo {
413 self.finish_delete(&occurrence, Ok(()), cx);
414 return;
415 }
416 let Some(engine) = engine else {
417 return;
418 };
419 let receiver = runtime::spawn(async move {
420 Recap::new(engine.remote().session())
421 .delete_recording(&details)
422 .await
423 });
424 cx.spawn(async move |this, cx| {
425 let outcome = match receiver.await {
426 Ok(Ok(())) => Ok(()),
427 Ok(Err(error)) => Err(short_error(&error)),
428 Err(error) => Err(short_error(&error)),
429 };
430 this.update(cx, |this, cx| this.finish_delete(&occurrence, outcome, cx))
431 .ok();
432 })
433 .detach();
434 }
435
436 fn finish_delete(
437 &mut self,
438 occurrence: &Occurrence,
439 outcome: Result<(), String>,
440 cx: &mut Context<Self>,
441 ) {
442 if let Err(reason) = outcome {
443 self.notice = Some(format!("Recording not deleted: {reason}"));
444 cx.notify();
445 return;
446 }
447 let remaining: Vec<Occurrence> = self
448 .occurrences()
449 .iter()
450 .filter(|other| other.message_id != occurrence.message_id)
451 .cloned()
452 .collect();
453 let empty = remaining.is_empty();
454 self.recap.listing = Load::Ready(remaining);
455 if empty {
456 self.pane = ChannelPane::Posts;
457 cx.notify();
458 } else {
459 self.select_occurrence(0, cx);
460 }
461 }
462
463 fn pick_save_target(&mut self, download: RecapDownload, cx: &mut Context<Self>) {
464 let Some(occurrence) = self.selected_occurrence() else {
465 return;
466 };
467 if matches!(
468 self.recap.downloads.get(&download),
469 Some(DownloadState::Saving(_))
470 ) {
471 return;
472 }
473 let extension = match download {
474 RecapDownload::Recording => RECORDING_EXTENSION,
475 RecapDownload::Transcript(format) => format.query(),
476 };
477 let name = save_name(&occurrence, extension);
478 let receiver = cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name));
479 cx.spawn(async move |this, cx| {
480 if let Ok(Ok(Some(target))) = receiver.await {
481 this.update(cx, |this, cx| this.save_to(download, occurrence, target, cx))
482 .ok();
483 }
484 })
485 .detach();
486 }
487
488 fn save_to(
489 &mut self,
490 download: RecapDownload,
491 occurrence: Occurrence,
492 target: PathBuf,
493 cx: &mut Context<Self>,
494 ) {
495 self.recap
496 .downloads
497 .insert(download, DownloadState::Saving(0));
498 cx.notify();
499 let generation = self.recap.generation;
500 let state = self.app.read(cx);
501 let (demo, engine) = (state.mode.demo, state.engine.clone());
502 let details = self.recap.details.ready().cloned();
503 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<SaveEvent>();
504 if demo {
505 let outcome = std::fs::write(&target, demo_recap::DEMO_FILE_BYTES)
506 .map(|_| target)
507 .map_err(|error| short_error(&error));
508 self.recap.downloads.insert(download, finished_state(outcome));
509 return;
510 }
511 let (Some(engine), Some(details)) = (engine, details) else {
512 self.recap
513 .downloads
514 .insert(download, DownloadState::Failed("not connected".to_owned()));
515 return;
516 };
517 drop(runtime::spawn(async move {
518 let outcome = save_download(&engine, download, &occurrence, &details, target, &sender)
519 .await;
520 let _ = sender.send(SaveEvent::Finished(outcome));
521 }));
522 cx.spawn(async move |this, cx| {
523 while let Some(event) = receiver.recv().await {
524 let updated = this.update(cx, |this, cx| {
525 if generation == this.recap.generation {
526 match event {
527 SaveEvent::Progress(percent) => {
528 this.recap
529 .downloads
530 .insert(download, DownloadState::Saving(percent));
531 }
532 SaveEvent::Finished(outcome) => {
533 this.recap.downloads.insert(download, finished_state(outcome));
534 }
535 }
536 }
537 cx.notify();
538 });
539 if updated.is_err() {
540 return;
541 }
542 }
543 })
544 .detach();
545 }
546}
547
548fn finished_state(outcome: Result<PathBuf, String>) -> DownloadState {
549 match outcome {
550 Ok(path) => DownloadState::Saved(path),
551 Err(reason) => DownloadState::Failed(reason),
552 }
553}
554
555async fn save_download(
556 engine: &crate::backend::Engine,
557 download: RecapDownload,
558 occurrence: &Occurrence,
559 details: &RecordingDetails,
560 target: PathBuf,
561 events: &tokio::sync::mpsc::UnboundedSender<SaveEvent>,
562) -> Result<PathBuf, String> {
563 match download {
564 RecapDownload::Transcript(format) => {
565 let bytes = Recap::new(engine.remote().session())
566 .transcript_file(details, format)
567 .await
568 .map_err(|error| short_error(&error))?;
569 std::fs::write(&target, bytes).map_err(|error| short_error(&error))?;
570 }
571 RecapDownload::Recording => {
572 let mut file = std::fs::File::create(&target).map_err(|error| short_error(&error))?;
573 let progress = |percent| {
574 let _ = events.send(SaveEvent::Progress(percent));
575 };
576 let result = engine
577 .download_file(
578 &occurrence.recording_url,
579 |bytes: &[u8]| file.write_all(bytes),
580 progress,
581 )
582 .await;
583 if let Err(error) = result {
584 drop(file);
585 let _ = std::fs::remove_file(&target);
586 return Err(short_error(&error));
587 }
588 }
589 }
590 Ok(target)
591}