BlueGit

ict rusty-teams

Files

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

recap.rs

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