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_chat_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_chat_tab_bar(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
360 if !self.in_chat() {
361 return None;
362 }
363 let with_recap = !self.occurrences().is_empty() && self.is_meeting_chat(cx);
364 let view = cx.weak_entity();
365 let select = Rc::new(move |pane, cx: &mut App| {
366 view.update(cx, |this, cx| this.select_pane(pane, cx)).ok();
367 });
368 Some(render_chat_bar(self.pane, with_recap, select))
369 }
370
371 pub(super) fn render_recap(&self, cx: &mut Context<Self>) -> AnyElement {
372 let view = cx.weak_entity();
373 let run: RecapRun = Rc::new(move |command, window, cx| {
374 view.update(cx, |this, cx| this.run_recap(command, window, cx))
375 .ok();
376 });
377 let file_indices: Rc<Vec<usize>> = Rc::new(
378 self.shared
379 .items
380 .iter()
381 .enumerate()
382 .filter(|(_, item)| matches!(item.content, SharedContent::File(_)))
383 .map(|(index, _)| index)
384 .collect(),
385 );
386 let file_states = self.item_download_states();
387 let files = file_indices
388 .iter()
389 .map(|index| self.shared.items[*index].clone())
390 .collect::<Vec<_>>();
391 let file_labels = file_indices
392 .iter()
393 .map(|index| {
394 crate::views::shared_tab::download_label(
395 file_states.get(*index).and_then(Option::as_ref),
396 )
397 })
398 .collect();
399 let file_run: SharedRun = {
400 let view = cx.weak_entity();
401 Rc::new(move |command, window, cx| {
402 let command = match command {
403 SharedCommand::OpenItem(index) => SharedCommand::OpenItem(file_indices[index]),
404 SharedCommand::JumpToPost(index) => {
405 SharedCommand::JumpToPost(file_indices[index])
406 }
407 other => other,
408 };
409 view.update(cx, |this, cx| {
410 if matches!(command, SharedCommand::JumpToPost(_)) {
411 this.pane = ChannelPane::Posts;
412 }
413 this.run_shared(command, window, cx)
414 })
415 .ok();
416 })
417 };
418 let can_delete = self.can_delete_recording(cx);
419 render_recap(
420 RecapView {
421 occurrences: self.occurrences(),
422 selected: self.recap.selected,
423 details: &self.recap.details,
424 transcript: &self.recap.transcript,
425 attendance: &self.recap.attendance,
426 search: &self.recap_search,
427 query: &self.recap.query,
428 can_delete,
429 recording_state: self.recap.downloads.get(&RecapDownload::Recording),
430 vtt_state: self
431 .recap
432 .downloads
433 .get(&RecapDownload::Transcript(TranscriptFormat::Vtt)),
434 docx_state: self
435 .recap
436 .downloads
437 .get(&RecapDownload::Transcript(TranscriptFormat::Docx)),
438 files: &files,
439 file_labels,
440 file_run,
441 now: Utc::now(),
442 },
443 &run,
444 )
445 }
446
447 fn can_delete_recording(&self, cx: &App) -> bool {
448 let my_user_id = self.app.read(cx).directory.me.as_ref().map(|me| me.user_id.as_str());
449 match (self.selected_occurrence(), my_user_id) {
450 (Some(occurrence), Some(my_user_id)) => {
451 occurrence.organizer_id.as_deref() == Some(my_user_id)
452 }
453 _ => false,
454 }
455 }
456
457 fn run_recap(&mut self, command: RecapCommand, window: &mut Window, cx: &mut Context<Self>) {
458 match command {
459 RecapCommand::Occurrence(index) => self.select_occurrence(index, cx),
460 RecapCommand::Retry => self.select_occurrence(self.recap.selected, cx),
461 RecapCommand::Play => {
462 if let Some(occurrence) = self.selected_occurrence() {
463 cx.open_url(&occurrence.recording_url);
464 }
465 }
466 RecapCommand::Download(download) => self.pick_save_target(download, cx),
467 RecapCommand::AskDelete => self.confirm_delete(window, cx),
468 }
469 }
470
471 fn confirm_delete(&mut self, window: &mut Window, cx: &mut Context<Self>) {
472 let view = cx.weak_entity();
473 window.open_alert_dialog(cx, move |alert, _, _| {
474 let view = view.clone();
475 let cancel = Button::new("recap-delete-cancel")
476 .label("Cancel")
477 .on_click(|_, window, cx| window.close_dialog(cx));
478 let delete = Button::new("recap-delete-confirm")
479 .label("Delete")
480 .danger()
481 .on_click(move |_, window, cx| {
482 view.update(cx, |this, cx| this.delete_recording(cx)).ok();
483 window.close_dialog(cx);
484 });
485 alert
486 .title(DELETE_QUESTION)
487 .footer(DialogFooter::new().child(cancel).child(delete))
488 .on_ok(|_, _, _| false)
489 });
490 }
491
492 fn delete_recording(&mut self, cx: &mut Context<Self>) {
493 let (Some(occurrence), Some(details)) = (
494 self.selected_occurrence(),
495 self.recap.details.ready().cloned(),
496 ) else {
497 return;
498 };
499 let state = self.app.read(cx);
500 let (demo, engine) = (state.mode.demo, state.engine.clone());
501 if demo {
502 self.finish_delete(&occurrence, Ok(()), cx);
503 return;
504 }
505 let Some(engine) = engine else {
506 return;
507 };
508 let receiver = runtime::spawn(async move {
509 Recap::new(engine.remote().session())
510 .delete_recording(&details)
511 .await
512 });
513 cx.spawn(async move |this, cx| {
514 let outcome = match receiver.await {
515 Ok(Ok(())) => Ok(()),
516 Ok(Err(error)) => Err(short_error(&error)),
517 Err(error) => Err(short_error(&error)),
518 };
519 this.update(cx, |this, cx| this.finish_delete(&occurrence, outcome, cx))
520 .ok();
521 })
522 .detach();
523 }
524
525 fn finish_delete(
526 &mut self,
527 occurrence: &Occurrence,
528 outcome: Result<(), String>,
529 cx: &mut Context<Self>,
530 ) {
531 if let Err(reason) = outcome {
532 self.notice = Some(format!("Recording not deleted: {reason}"));
533 cx.notify();
534 return;
535 }
536 let remaining: Vec<Occurrence> = self
537 .occurrences()
538 .iter()
539 .filter(|other| other.message_id != occurrence.message_id)
540 .cloned()
541 .collect();
542 let empty = remaining.is_empty();
543 self.recap.listing = Load::Ready(remaining);
544 if empty {
545 self.pane = ChannelPane::Posts;
546 cx.notify();
547 } else {
548 self.select_occurrence(0, cx);
549 }
550 }
551
552 fn pick_save_target(&mut self, download: RecapDownload, cx: &mut Context<Self>) {
553 let Some(occurrence) = self.selected_occurrence() else {
554 return;
555 };
556 if matches!(
557 self.recap.downloads.get(&download),
558 Some(DownloadState::Saving(_))
559 ) {
560 return;
561 }
562 let extension = match download {
563 RecapDownload::Recording => RECORDING_EXTENSION,
564 RecapDownload::Transcript(format) => format.query(),
565 };
566 let name = save_name(&occurrence, extension);
567 let receiver = cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name));
568 cx.spawn(async move |this, cx| {
569 if let Ok(Ok(Some(target))) = receiver.await {
570 this.update(cx, |this, cx| this.save_to(download, occurrence, target, cx))
571 .ok();
572 }
573 })
574 .detach();
575 }
576
577 fn save_to(
578 &mut self,
579 download: RecapDownload,
580 occurrence: Occurrence,
581 target: PathBuf,
582 cx: &mut Context<Self>,
583 ) {
584 self.recap
585 .downloads
586 .insert(download, DownloadState::Saving(0));
587 cx.notify();
588 let generation = self.recap.generation;
589 let state = self.app.read(cx);
590 let (demo, engine) = (state.mode.demo, state.engine.clone());
591 let details = self.recap.details.ready().cloned();
592 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<SaveEvent>();
593 if demo {
594 let outcome = std::fs::write(&target, demo_recap::DEMO_FILE_BYTES)
595 .map(|_| target)
596 .map_err(|error| short_error(&error));
597 self.recap.downloads.insert(download, finished_state(outcome));
598 return;
599 }
600 let (Some(engine), Some(details)) = (engine, details) else {
601 self.recap
602 .downloads
603 .insert(download, DownloadState::Failed("not connected".to_owned()));
604 return;
605 };
606 drop(runtime::spawn(async move {
607 let outcome = save_download(&engine, download, &occurrence, &details, target, &sender)
608 .await;
609 let _ = sender.send(SaveEvent::Finished(outcome));
610 }));
611 cx.spawn(async move |this, cx| {
612 while let Some(event) = receiver.recv().await {
613 let updated = this.update(cx, |this, cx| {
614 if generation == this.recap.generation {
615 match event {
616 SaveEvent::Progress(percent) => {
617 this.recap
618 .downloads
619 .insert(download, DownloadState::Saving(percent));
620 }
621 SaveEvent::Finished(outcome) => {
622 this.recap.downloads.insert(download, finished_state(outcome));
623 }
624 }
625 }
626 cx.notify();
627 });
628 if updated.is_err() {
629 return;
630 }
631 }
632 })
633 .detach();
634 }
635}
636
637fn finished_state(outcome: Result<PathBuf, String>) -> DownloadState {
638 match outcome {
639 Ok(path) => DownloadState::Saved(path),
640 Err(reason) => DownloadState::Failed(reason),
641 }
642}
643
644async fn save_download(
645 engine: &crate::backend::Engine,
646 download: RecapDownload,
647 occurrence: &Occurrence,
648 details: &RecordingDetails,
649 target: PathBuf,
650 events: &tokio::sync::mpsc::UnboundedSender<SaveEvent>,
651) -> Result<PathBuf, String> {
652 match download {
653 RecapDownload::Transcript(format) => {
654 let bytes = Recap::new(engine.remote().session())
655 .transcript_file(details, format)
656 .await
657 .map_err(|error| short_error(&error))?;
658 std::fs::write(&target, bytes).map_err(|error| short_error(&error))?;
659 }
660 RecapDownload::Recording => {
661 let mut file = std::fs::File::create(&target).map_err(|error| short_error(&error))?;
662 let progress = |percent| {
663 let _ = events.send(SaveEvent::Progress(percent));
664 };
665 let result = engine
666 .download_file(
667 &occurrence.recording_url,
668 |bytes: &[u8]| file.write_all(bytes),
669 progress,
670 )
671 .await;
672 if let Err(error) = result {
673 drop(file);
674 let _ = std::fs::remove_file(&target);
675 return Err(short_error(&error));
676 }
677 }
678 }
679 Ok(target)
680}