BlueGit

ict rusty-teams

Files

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

recap.rs

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