BlueGit

ict rusty-teams

Files

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

recap.rs

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