BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/settings-dialog

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
0128321950ce77da35a4ab7b958716ea786aa6d9
51 files changed +1582 −479
crates/app-base/src/assets.rs +8 −5
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 50] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 53] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
@@ -55,10 +55,13 @@ const SYMBOLS: [(&str, &[u8]); 50] = symbols![
55 55 "call",
56 56 "call_missed",
57 57 "videocam",
58 "radio_button_checked",
59 "stop_circle",
60 "play_arrow",
61 "description",
58 "fluent_video",
59 "fluent_record",
60 "fluent_record_stop",
61 "fluent_cloud_arrow_up",
62 "fluent_share",
63 "fluent_clock",
64 "fluent_document_text",
62 65 ];
63 66
64 67 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 50] = symbols![
11const SYMBOLS: [(&str, &[u8]); 53] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
@@ -55,10 +55,13 @@ const SYMBOLS: [(&str, &[u8]); 50] = symbols![
55 "call",
55 "call",
56 "call_missed",
56 "call_missed",
57 "videocam",
57 "videocam",
58 "radio_button_checked",
58 "fluent_video",
59 "stop_circle",
59 "fluent_record",
60 "play_arrow",
60 "fluent_record_stop",
61 "description",
61 "fluent_cloud_arrow_up",
62 "fluent_share",
63 "fluent_clock",
64 "fluent_document_text",
62];
65];
63
66
64pub struct AppAssets;
67pub struct AppAssets;
crates/app-state/src/activity/feed.rs +5 −1
@@ -261,7 +261,11 @@ impl Feed {
261 261 }
262 262
263 263 pub fn unread_count(&self) -> usize {
264 self.entries.iter().filter(|entry| !entry.read).count()
264 self.unread_entries().count()
265 }
266
267 pub fn unread_entries(&self) -> impl Iterator<Item = &Entry> {
268 self.entries.iter().filter(|entry| !entry.read)
265 269 }
266 270
267 271 pub fn take_dirty(&mut self) -> Vec<Entry> {
@@ -261,7 +261,11 @@ impl Feed {
261 }
261 }
262
262
263 pub fn unread_count(&self) -> usize {
263 pub fn unread_count(&self) -> usize {
264 self.entries.iter().filter(|entry| !entry.read).count()
264 self.unread_entries().count()
265 }
266
267 pub fn unread_entries(&self) -> impl Iterator<Item = &Entry> {
268 self.entries.iter().filter(|entry| !entry.read)
265 }
269 }
266
270
267 pub fn take_dirty(&mut self) -> Vec<Entry> {
271 pub fn take_dirty(&mut self) -> Vec<Entry> {
crates/app-state/src/call_rows.rs +471 −93
@@ -1,9 +1,17 @@
1 1 use std::collections::{HashMap, HashSet};
2 2
3 use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
4 use store::MessageRecord;
3 5 use teams_core::{CallEvent, CallPhase, CallType, ImageRef, format_duration};
4 6
7 use crate::format;
8
5 9 const MAX_AVATARS: usize = 4;
6 const RECORDING_FALLBACK_TITLE: &str = "Meeting recording";
10 const RECAP_FALLBACK_TITLE: &str = "Meeting";
11 const RECAP_DATE_FORMAT: &str = "%A, %-d %B %Y %H:%M";
12 const RECAP_TIME_FORMAT: &str = "%H:%M";
13 const AUTO_STOP_SECONDS: i64 = 5;
14 const WEEKDAY_STAMP_DAYS: i64 = 6;
7 15
8 16 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9 17 pub enum CallIcon {
@@ -12,6 +20,7 @@ pub enum CallIcon {
12 20 Video,
13 21 Record,
14 22 RecordStop,
23 Saved,
15 24 }
16 25
17 26 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -23,11 +32,27 @@ pub struct CallParticipant {
23 32 #[derive(Debug, Clone, PartialEq, Eq)]
24 33 pub struct RecordingCard {
25 34 pub message_id: String,
26 pub title: String,
27 35 pub duration: Option<String>,
28 36 pub url: Option<String>,
29 37 pub thumbnail: Option<ImageRef>,
30 38 pub transcript: bool,
39 pub expires_in_days: Option<i64>,
40 }
41
42 /// The card Teams puts under the "Meeting ended" line of a meeting with a recording.
43 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub struct RecapCard {
45 pub title: String,
46 pub date_line: String,
47 pub recording: RecordingCard,
48 }
49
50 /// A meeting or recording event as Teams draws it: one muted line, icon in the avatar column.
51 #[derive(Debug, Clone, PartialEq, Eq)]
52 pub struct CallNotice {
53 pub stamp: String,
54 pub text: String,
55 pub emphasis: Option<String>,
31 56 }
32 57
33 58 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -39,7 +64,23 @@ pub struct CallCard {
39 64 pub started: bool,
40 65 pub participants: Vec<CallParticipant>,
41 66 pub extra_participants: usize,
42 pub recording: Option<RecordingCard>,
67 pub notice: Option<CallNotice>,
68 pub recap: Option<RecapCard>,
69 }
70
71 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
72 pub struct MeetingSlot {
73 pub start: DateTime<Utc>,
74 pub end: DateTime<Utc>,
75 }
76
77 /// What the meeting rows need beyond the messages: the chat topic, the calendar occurrences
78 /// and the recording expiry the Recap tab reads, keyed by the saved recording message id.
79 #[derive(Debug, Clone, Default, PartialEq)]
80 pub struct MeetingInfo {
81 pub title: Option<String>,
82 pub slots: Vec<MeetingSlot>,
83 pub expiry_days: HashMap<String, i64>,
43 84 }
44 85
45 86 pub struct CallNames<'a> {
@@ -56,6 +97,17 @@ impl CallNames<'_> {
56 97 }
57 98 }
58 99
100 pub struct CallClock<'a> {
101 pub offset: FixedOffset,
102 pub today: NaiveDate,
103 pub meeting: &'a MeetingInfo,
104 }
105
106 struct SavedRecording {
107 message_id: String,
108 event: CallEvent,
109 }
110
59 111 /// Which call events of a timeline show as rows: Teams keeps one row per recording start and stop,
60 112 /// hides transcript notices and, for calls (not meetings), the start once the call ended.
61 113 pub struct CallTimeline {
@@ -63,10 +115,17 @@ pub struct CallTimeline {
63 115 finished: HashSet<String>,
64 116 transcripts: HashSet<String>,
65 117 newest_open_start: Option<usize>,
118 started_at: HashMap<String, DateTime<Utc>>,
119 ended_at: HashMap<String, DateTime<Utc>>,
120 saved: HashMap<String, SavedRecording>,
66 121 }
67 122
68 123 impl CallTimeline {
69 124 pub fn new(events: &[Option<CallEvent>]) -> Self {
125 Self::with_records(events, &[])
126 }
127
128 pub fn with_records(events: &[Option<CallEvent>], records: &[&MessageRecord]) -> Self {
70 129 let finished: HashSet<String> = events
71 130 .iter()
72 131 .flatten()
@@ -103,11 +162,42 @@ impl CallTimeline {
103 162 event.phase == CallPhase::Started && !finished.contains(&event.call_id)
104 163 })
105 164 });
165 let mut started_at = HashMap::new();
166 let mut ended_at = HashMap::new();
167 let mut saved = HashMap::new();
168 for (event, record) in events.iter().zip(records) {
169 let Some(event) = event else {
170 continue;
171 };
172 match event.phase {
173 CallPhase::Started => {
174 started_at
175 .entry(event.call_id.clone())
176 .or_insert(record.created_at);
177 }
178 CallPhase::Ended => {
179 ended_at.insert(event.call_id.clone(), record.created_at);
180 }
181 CallPhase::RecordingSaved => {
182 saved.insert(
183 event.call_id.clone(),
184 SavedRecording {
185 message_id: record.message_id.clone(),
186 event: event.clone(),
187 },
188 );
189 }
190 _ => {}
191 }
192 }
106 193 CallTimeline {
107 194 hidden,
108 195 finished,
109 196 transcripts,
110 197 newest_open_start,
198 started_at,
199 ended_at,
200 saved,
111 201 }
112 202 }
113 203
@@ -126,6 +216,94 @@ impl CallTimeline {
126 216 pub fn has_transcript(&self, call_id: &str) -> bool {
127 217 self.transcripts.contains(call_id)
128 218 }
219
220 /// A recording that stops with the meeting end has no one who stopped it; Teams then says
221 /// "Recording stopped." instead of naming the recorder.
222 fn stopped_by_meeting_end(&self, event: &CallEvent, created_at: DateTime<Utc>) -> bool {
223 self.ended_at.get(&event.call_id).is_some_and(|ended_at| {
224 (*ended_at - created_at).num_seconds().abs() <= AUTO_STOP_SECONDS
225 })
226 }
227
228 fn recap(
229 &self,
230 ended: &CallEvent,
231 ended_at: DateTime<Utc>,
232 clock: &CallClock,
233 ) -> Option<RecapCard> {
234 if ended.phase != CallPhase::Ended || ended.call_type != CallType::Meeting {
235 return None;
236 }
237 let saved = self.saved.get(&ended.call_id)?;
238 let started_at = self
239 .started_at
240 .get(&ended.call_id)
241 .copied()
242 .or_else(|| {
243 ended
244 .duration_seconds
245 .map(|seconds| ended_at - chrono::Duration::seconds(seconds as i64))
246 })
247 .unwrap_or(ended_at);
248 let recording = recording_card(
249 &saved.event,
250 &saved.message_id,
251 self.has_transcript(&ended.call_id),
252 clock.meeting,
253 )?;
254 let title = clock
255 .meeting
256 .title
257 .clone()
258 .filter(|title| !title.trim().is_empty())
259 .or_else(|| saved.event.recording.as_ref()?.title())
260 .unwrap_or_else(|| RECAP_FALLBACK_TITLE.to_owned());
261 Some(RecapCard {
262 title,
263 date_line: recap_date_line(started_at, ended_at, clock),
264 recording,
265 })
266 }
267 }
268
269 /// Teams dates the recap card with the scheduled occurrence; without a calendar match the call's
270 /// own start and end stand in.
271 fn recap_date_line(
272 started_at: DateTime<Utc>,
273 ended_at: DateTime<Utc>,
274 clock: &CallClock,
275 ) -> String {
276 let slot = clock
277 .meeting
278 .slots
279 .iter()
280 .filter(|slot| slot.start <= ended_at && slot.end >= started_at)
281 .min_by_key(|slot| (slot.start - started_at).num_seconds().abs())
282 .copied()
283 .unwrap_or(MeetingSlot {
284 start: started_at,
285 end: ended_at,
286 });
287 format!(
288 "{} - {}",
289 slot.start
290 .with_timezone(&clock.offset)
291 .format(RECAP_DATE_FORMAT),
292 slot.end
293 .with_timezone(&clock.offset)
294 .format(RECAP_TIME_FORMAT)
295 )
296 }
297
298 /// Teams writes the weekday in full on these lines ("Thursday 11:45"), unlike message times.
299 fn notice_stamp(time: DateTime<Utc>, clock: &CallClock) -> String {
300 let local = time.with_timezone(&clock.offset);
301 let days_ago = (clock.today - local.date_naive()).num_days();
302 if (2..=WEEKDAY_STAMP_DAYS).contains(&days_ago) {
303 local.format("%A %H:%M").to_string()
304 } else {
305 format::post_time_label(time, clock.today, clock.offset)
306 }
129 307 }
130 308
131 309 fn participants(event: &CallEvent, names: &CallNames) -> Vec<CallParticipant> {
@@ -143,13 +321,15 @@ fn participants(event: &CallEvent, names: &CallNames) -> Vec<CallParticipant> {
143 321 .collect()
144 322 }
145 323
146 fn recording_card(event: &CallEvent, message_id: &str, transcript: bool) -> Option<RecordingCard> {
324 fn recording_card(
325 event: &CallEvent,
326 message_id: &str,
327 transcript: bool,
328 meeting: &MeetingInfo,
329 ) -> Option<RecordingCard> {
147 330 let recording = event.recording.as_ref()?;
148 331 Some(RecordingCard {
149 332 message_id: message_id.to_owned(),
150 title: recording
151 .title()
152 .unwrap_or_else(|| RECORDING_FALLBACK_TITLE.to_owned()),
153 333 duration: event
154 334 .duration_seconds
155 335 .filter(|seconds| *seconds > 0)
@@ -163,9 +343,71 @@ fn recording_card(event: &CallEvent, message_id: &str, transcript: bool) -> Opti
163 343 alt: None,
164 344 }),
165 345 transcript,
346 expires_in_days: meeting.expiry_days.get(message_id).copied(),
166 347 })
167 348 }
168 349
350 fn day_count(days: i64) -> String {
351 if days == 1 {
352 "1 day".to_owned()
353 } else {
354 format!("{days} days")
355 }
356 }
357
358 struct NoticeSource<'a> {
359 event: &'a CallEvent,
360 message_id: &'a str,
361 stopped_by_meeting_end: bool,
362 }
363
364 fn notice_text(source: NoticeSource, names: &CallNames, meeting: &MeetingInfo) -> String {
365 let NoticeSource {
366 event,
367 message_id,
368 stopped_by_meeting_end,
369 } = source;
370 let initiator = || {
371 names.name(
372 event.initiator_id.as_deref(),
373 event.initiator_name.as_deref(),
374 )
375 };
376 match event.phase {
377 CallPhase::Ended => format!("{}:", event.title(false)),
378 CallPhase::RecordingStarted => match initiator() {
379 Some(name) => format!("{name} started recording."),
380 None => event.title(false).to_owned(),
381 },
382 CallPhase::RecordingStopped => match initiator().filter(|_| !stopped_by_meeting_end) {
383 Some(name) => format!("{name} stopped recording."),
384 None => format!("{}.", event.title(false)),
385 },
386 CallPhase::RecordingSaved => {
387 let saved = saved_to(event, names);
388 match meeting.expiry_days.get(message_id) {
389 Some(days) => format!("{saved} and will expire in {}.", day_count(*days)),
390 None => format!("{saved}."),
391 }
392 }
393 _ => event.title(false).to_owned(),
394 }
395 }
396
397 fn saved_to(event: &CallEvent, names: &CallNames) -> String {
398 let organizer_id = event
399 .recording
400 .as_ref()
401 .and_then(|recording| recording.organizer_id.as_deref());
402 if organizer_id.is_some() && organizer_id == names.my_user_id {
403 return "Recording has been saved to your OneDrive".to_owned();
404 }
405 match names.name(organizer_id, None) {
406 Some(owner) => format!("Recording has been saved to {owner}'s OneDrive"),
407 None => "Recording has been saved to OneDrive".to_owned(),
408 }
409 }
410
169 411 fn title(event: &CallEvent, missed: bool, names: &CallNames) -> String {
170 412 match event.phase {
171 413 CallPhase::RecordingStarted => {
@@ -177,30 +419,35 @@ fn title(event: &CallEvent, missed: bool, names: &CallNames) -> String {
177 419 None => event.title(false).to_owned(),
178 420 }
179 421 }
180 CallPhase::RecordingSaved => {
181 let organizer_id = event
182 .recording
183 .as_ref()
184 .and_then(|recording| recording.organizer_id.as_deref());
185 if organizer_id.is_some() && organizer_id == names.my_user_id {
186 return "Recording has been saved to your OneDrive".to_owned();
187 }
188 match names.name(organizer_id, None) {
189 Some(owner) => format!("Recording has been saved to {owner}'s OneDrive"),
190 None => "Recording has been saved to OneDrive".to_owned(),
191 }
192 }
422 CallPhase::RecordingSaved => saved_to(event, names),
193 423 _ => event.title(missed).to_owned(),
194 424 }
195 425 }
196 426
427 /// Teams draws meeting and recording events as one-line notices; 1:1 and group calls keep the card.
428 pub fn is_notice(event: &CallEvent) -> bool {
429 event.call_type == CallType::Meeting || event.is_recording()
430 }
431
432 pub struct CallSource<'a> {
433 pub event: &'a CallEvent,
434 pub message_id: &'a str,
435 pub created_at: DateTime<Utc>,
436 pub time: &'a str,
437 }
438
197 439 pub fn call_card(
198 event: &CallEvent,
199 message_id: &str,
200 time: &str,
440 source: CallSource,
201 441 names: &CallNames,
202 transcript: bool,
442 clock: &CallClock,
443 timeline: &CallTimeline,
203 444 ) -> CallCard {
445 let CallSource {
446 event,
447 message_id,
448 created_at,
449 time,
450 } = source;
204 451 let missed = event.missed(names.my_user_id);
205 452 let detail = match (event.phase, event.duration_seconds) {
206 453 (CallPhase::Ended, Some(seconds)) if !missed => {
@@ -215,12 +462,29 @@ pub fn call_card(
215 462 };
216 463 let extra_participants = people.len().saturating_sub(MAX_AVATARS);
217 464 people.truncate(MAX_AVATARS);
465 let notice = is_notice(event).then(|| CallNotice {
466 stamp: notice_stamp(created_at, clock),
467 text: notice_text(
468 NoticeSource {
469 event,
470 message_id,
471 stopped_by_meeting_end: timeline.stopped_by_meeting_end(event, created_at),
472 },
473 names,
474 clock.meeting,
475 ),
476 emphasis: event
477 .duration_seconds
478 .filter(|_| event.phase == CallPhase::Ended)
479 .map(format_duration),
480 });
218 481 CallCard {
219 482 title: title(event, missed, names),
220 483 detail,
221 484 icon: match (missed, event.phase, event.call_type) {
222 485 (true, _, _) => CallIcon::Missed,
223 (false, CallPhase::RecordingStarted | CallPhase::RecordingSaved, _) => CallIcon::Record,
486 (false, CallPhase::RecordingStarted, _) => CallIcon::Record,
487 (false, CallPhase::RecordingSaved, _) => CallIcon::Saved,
224 488 (false, CallPhase::RecordingStopped | CallPhase::TranscriptStarted, _) => {
225 489 CallIcon::RecordStop
226 490 }
@@ -231,14 +495,14 @@ pub fn call_card(
231 495 started: event.phase == CallPhase::Started,
232 496 participants: people,
233 497 extra_participants,
234 recording: (event.phase == CallPhase::RecordingSaved)
235 .then(|| recording_card(event, message_id, transcript))
236 .flatten(),
498 recap: timeline.recap(event, created_at, clock),
499 notice,
237 500 }
238 501 }
239 502
240 503 #[cfg(test)]
241 504 mod tests {
505 use chrono::TimeZone;
242 506 use teams_core::Recording;
243 507
244 508 use super::*;
@@ -257,7 +521,7 @@ mod tests {
257 521 }
258 522 }
259 523
260 fn fixture_events() -> Vec<Option<CallEvent>> {
524 fn fixture_records() -> Vec<MessageRecord> {
261 525 let path = format!(
262 526 "{}/../core/tests/fixtures/call_events/meeting_chat_recording.json",
263 527 env!("CARGO_MANIFEST_DIR")
@@ -269,7 +533,10 @@ mod tests {
269 533 .unwrap()
270 534 .iter()
271 535 .rev()
272 .map(|message| CallEvent::from_graph(&message["eventDetail"]))
536 .map(|message| {
537 let message: graph::Message = serde_json::from_value(message.clone()).unwrap();
538 teams_core::message_record("meeting-chat", &message).unwrap()
539 })
273 540 .collect()
274 541 }
275 542
@@ -286,93 +553,197 @@ mod tests {
286 553 ])
287 554 }
288 555
289 #[test]
290 fn recorded_meeting_shows_like_teams() {
291 let events = fixture_events();
292 let timeline = CallTimeline::new(&events);
556 fn cards(records: &[MessageRecord], meeting: &MeetingInfo) -> Vec<CallCard> {
557 let events: Vec<Option<CallEvent>> = records.iter().map(teams_core::call_event).collect();
558 let timeline = CallTimeline::with_records(&events, &records.iter().collect::<Vec<_>>());
293 559 let names = names();
294 560 let lookup = CallNames {
295 561 my_user_id: Some("me"),
296 562 names: &names,
297 563 };
298 let titles: Vec<String> = events
564 let clock = CallClock {
565 offset: FixedOffset::east_opt(0).unwrap(),
566 today: NaiveDate::from_ymd_opt(2026, 10, 30).unwrap(),
567 meeting,
568 };
569 events
299 570 .iter()
571 .zip(records)
300 572 .enumerate()
301 573 .filter(|(index, _)| !timeline.hides(*index))
302 .map(|(_, event)| {
303 let event = event.as_ref().unwrap();
574 .map(|(_, (event, record))| {
304 575 call_card(
305 event,
306 "m",
307 "16:15",
576 CallSource {
577 event: event.as_ref().unwrap(),
578 message_id: &record.message_id,
579 created_at: record.created_at,
580 time: "16:15",
581 },
308 582 &lookup,
309 timeline.has_transcript(&event.call_id),
583 &clock,
584 &timeline,
310 585 )
311 .title
312 586 })
313 .collect();
587 .collect()
588 }
589
590 fn notice_line(card: &CallCard) -> String {
591 let notice = card.notice.as_ref().unwrap();
592 match &notice.emphasis {
593 Some(emphasis) => format!("{} {emphasis}", notice.text),
594 None => notice.text.clone(),
595 }
596 }
597
598 #[test]
599 fn recorded_meeting_shows_as_teams_notices() {
600 let shown = cards(&fixture_records(), &MeetingInfo::default());
601 let lines: Vec<String> = shown.iter().map(notice_line).collect();
314 602 assert_eq!(
315 titles,
603 lines,
316 604 [
317 605 "Meeting started",
318 "Sam Recorder started recording",
319 "Recording stopped",
320 "Meeting ended",
321 "Recording has been saved to Vera Organizer's OneDrive",
606 "Sam Recorder started recording.",
607 "Recording stopped.",
608 "Meeting ended: 16m 28s",
609 "Recording has been saved to Vera Organizer's OneDrive.",
322 610 ]
323 611 );
612 let icons: Vec<CallIcon> = shown.iter().map(|card| card.icon).collect();
613 assert_eq!(
614 icons,
615 [
616 CallIcon::Video,
617 CallIcon::Record,
618 CallIcon::RecordStop,
619 CallIcon::Video,
620 CallIcon::Saved,
621 ]
622 );
623 assert!(
624 shown
625 .iter()
626 .all(|card| card.recap.is_none() == (card.title != "Meeting ended"))
627 );
324 628 }
325 629
326 630 #[test]
327 fn saved_recording_becomes_a_card_with_transcript_and_thumbnail() {
328 let events = fixture_events();
329 let timeline = CallTimeline::new(&events);
330 let saved = events.last().unwrap().as_ref().unwrap();
331 let names = HashMap::new();
332 let lookup = CallNames {
333 my_user_id: None,
334 names: &names,
631 fn a_recording_stopped_before_the_end_names_who_stopped_it() {
632 let mut records = fixture_records();
633 for record in records.iter_mut() {
634 if teams_core::call_event(record)
635 .is_some_and(|event| event.phase == CallPhase::RecordingStopped)
636 {
637 record.created_at -= chrono::Duration::minutes(2);
638 }
639 }
640 let shown = cards(&records, &MeetingInfo::default());
641 assert_eq!(notice_line(&shown[2]), "Sam Recorder stopped recording.");
642 }
643
644 #[test]
645 fn ended_meeting_carries_the_recap_card_of_its_recording() {
646 let records = fixture_records();
647 let saved_id = records.last().unwrap().message_id.clone();
648 let meeting = MeetingInfo {
649 title: Some("Weekly sync".to_owned()),
650 slots: Vec::new(),
651 expiry_days: HashMap::from([(saved_id.clone(), 56)]),
335 652 };
336 let card = call_card(
337 saved,
338 "saved-1",
339 "16:16",
340 &lookup,
341 timeline.has_transcript(&saved.call_id),
653 let shown = cards(&records, &meeting);
654 let ended = shown
655 .iter()
656 .find(|card| card.title == "Meeting ended")
657 .unwrap();
658 let recap = ended.recap.as_ref().unwrap();
659 assert_eq!(recap.title, "Weekly sync");
660 assert_eq!(recap.recording.message_id, saved_id);
661 assert_eq!(recap.recording.duration.as_deref(), Some("13m 34s"));
662 assert_eq!(recap.recording.expires_in_days, Some(56));
663 assert!(recap.recording.transcript);
664 assert!(
665 recap
666 .recording
667 .thumbnail
668 .as_ref()
669 .unwrap()
670 .url
671 .contains("/thumbnails/")
672 );
673 assert!(shown.iter().filter(|card| card.recap.is_some()).count() == 1);
674 assert_eq!(
675 notice_line(shown.last().unwrap()),
676 "Recording has been saved to Vera Organizer's OneDrive and will expire in 56 days."
342 677 );
343 assert_eq!(card.title, "Recording has been saved to OneDrive");
344 assert_eq!(card.icon, CallIcon::Record);
345 let recording = card.recording.unwrap();
346 assert_eq!(recording.title, "Weekly team meeting");
347 assert_eq!(recording.duration.as_deref(), Some("13m 34s"));
348 assert!(recording.transcript);
349 assert_eq!(recording.message_id, "saved-1");
350 assert!(recording.thumbnail.unwrap().url.contains("/thumbnails/"));
678 }
679
680 #[test]
681 fn recap_date_prefers_the_calendar_occurrence() {
682 let started_at = Utc.with_ymd_and_hms(2026, 10, 15, 9, 46, 0).unwrap();
683 let ended_at = Utc.with_ymd_and_hms(2026, 10, 15, 9, 55, 0).unwrap();
684 let mut meeting = MeetingInfo::default();
685 let clock = |meeting: &MeetingInfo| {
686 recap_date_line(
687 started_at,
688 ended_at,
689 &CallClock {
690 offset: FixedOffset::east_opt(2 * 3600).unwrap(),
691 today: NaiveDate::from_ymd_opt(2026, 10, 17).unwrap(),
692 meeting,
693 },
694 )
695 };
696 assert_eq!(clock(&meeting), "Thursday, 15 October 2026 11:46 - 11:55");
697 meeting.slots = vec![
698 MeetingSlot {
699 start: Utc.with_ymd_and_hms(2026, 10, 14, 9, 45, 0).unwrap(),
700 end: Utc.with_ymd_and_hms(2026, 10, 14, 10, 0, 0).unwrap(),
701 },
702 MeetingSlot {
703 start: Utc.with_ymd_and_hms(2026, 10, 15, 9, 45, 0).unwrap(),
704 end: Utc.with_ymd_and_hms(2026, 10, 15, 10, 0, 0).unwrap(),
705 },
706 ];
707 assert_eq!(clock(&meeting), "Thursday, 15 October 2026 11:45 - 12:00");
708 }
709
710 #[test]
711 fn notice_stamps_spell_out_the_weekday_like_teams() {
712 let meeting = MeetingInfo::default();
713 let clock = CallClock {
714 offset: FixedOffset::east_opt(0).unwrap(),
715 today: NaiveDate::from_ymd_opt(2026, 10, 17).unwrap(),
716 meeting: &meeting,
717 };
718 let stamp = |day: u32| {
719 notice_stamp(
720 Utc.with_ymd_and_hms(2026, 10, day, 11, 45, 0).unwrap(),
721 &clock,
722 )
723 };
724 assert_eq!(stamp(17), "11:45");
725 assert_eq!(stamp(16), "Yesterday 11:45");
726 assert_eq!(stamp(15), "Thursday 11:45");
351 727 }
352 728
353 729 #[test]
354 730 fn ended_meeting_lists_named_participants_up_to_four() {
355 let events = fixture_events();
356 let ended = events
731 let shown = cards(&fixture_records(), &MeetingInfo::default());
732 let ended = shown
357 733 .iter()
358 .flatten()
359 .find(|event| event.phase == CallPhase::Ended)
734 .find(|card| card.title == "Meeting ended")
360 735 .unwrap();
361 let names = HashMap::new();
362 let lookup = CallNames {
363 my_user_id: None,
364 names: &names,
365 };
366 let card = call_card(ended, "m", "16:15", &lookup, false);
367 assert_eq!(card.detail, "16m 28s \u{b7} 16:15");
368 assert_eq!(card.icon, CallIcon::Video);
369 let shown: Vec<&str> = card
736 assert_eq!(ended.detail, "16m 28s \u{b7} 16:15");
737 let shown_names: Vec<&str> = ended
370 738 .participants
371 739 .iter()
372 740 .map(|person| person.name.as_str())
373 741 .collect();
374 assert_eq!(shown, ["Person 1", "Person 2", "Person 3", "Person 4"]);
375 assert_eq!(card.extra_participants, 20);
742 assert_eq!(
743 shown_names,
744 ["Person 1", "Person 2", "Person 3", "Person 4"]
745 );
746 assert_eq!(ended.extra_participants, 20);
376 747 }
377 748
378 749 #[test]
@@ -395,8 +766,9 @@ mod tests {
395 766 }
396 767
397 768 #[test]
398 fn my_own_recording_is_saved_to_my_onedrive() {
399 let mut saved = event(CallPhase::RecordingSaved, CallType::Meeting, "c");
769 fn calls_keep_their_card_and_my_recording_is_in_my_onedrive() {
770 assert!(!is_notice(&event(CallPhase::Ended, CallType::Call, "c")));
771 let mut saved = event(CallPhase::RecordingSaved, CallType::Call, "c");
400 772 saved.recording = Some(Recording {
401 773 name: None,
402 774 url: Some("https://contoso.example/rec.mp4".to_owned()),
@@ -407,11 +779,17 @@ mod tests {
407 779 my_user_id: Some("me"),
408 780 names: &names,
409 781 };
410 let card = call_card(&saved, "m", "9:00", &lookup, false);
411 assert_eq!(card.title, "Recording has been saved to your OneDrive");
412 let recording = card.recording.unwrap();
413 assert_eq!(recording.title, "Meeting recording");
414 assert_eq!(recording.thumbnail, None);
415 assert_eq!(recording.duration, None);
782 assert_eq!(
783 notice_text(
784 NoticeSource {
785 event: &saved,
786 message_id: "m",
787 stopped_by_meeting_end: false,
788 },
789 &lookup,
790 &MeetingInfo::default()
791 ),
792 "Recording has been saved to your OneDrive."
793 );
416 794 }
417 795 }
@@ -1,9 +1,17 @@
1use std::collections::{HashMap, HashSet};
1use std::collections::{HashMap, HashSet};
2
2
3use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
4use store::MessageRecord;
3use teams_core::{CallEvent, CallPhase, CallType, ImageRef, format_duration};
5use teams_core::{CallEvent, CallPhase, CallType, ImageRef, format_duration};
4
6
7use crate::format;
8
5const MAX_AVATARS: usize = 4;
9const MAX_AVATARS: usize = 4;
6const RECORDING_FALLBACK_TITLE: &str = "Meeting recording";
10const RECAP_FALLBACK_TITLE: &str = "Meeting";
11const RECAP_DATE_FORMAT: &str = "%A, %-d %B %Y %H:%M";
12const RECAP_TIME_FORMAT: &str = "%H:%M";
13const AUTO_STOP_SECONDS: i64 = 5;
14const WEEKDAY_STAMP_DAYS: i64 = 6;
7
15
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum CallIcon {
17pub enum CallIcon {
@@ -12,6 +20,7 @@ pub enum CallIcon {
12 Video,
20 Video,
13 Record,
21 Record,
14 RecordStop,
22 RecordStop,
23 Saved,
15}
24}
16
25
17#[derive(Debug, Clone, PartialEq, Eq)]
26#[derive(Debug, Clone, PartialEq, Eq)]
@@ -23,11 +32,27 @@ pub struct CallParticipant {
23#[derive(Debug, Clone, PartialEq, Eq)]
32#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct RecordingCard {
33pub struct RecordingCard {
25 pub message_id: String,
34 pub message_id: String,
26 pub title: String,
27 pub duration: Option<String>,
35 pub duration: Option<String>,
28 pub url: Option<String>,
36 pub url: Option<String>,
29 pub thumbnail: Option<ImageRef>,
37 pub thumbnail: Option<ImageRef>,
30 pub transcript: bool,
38 pub transcript: bool,
39 pub expires_in_days: Option<i64>,
40}
41
42/// The card Teams puts under the "Meeting ended" line of a meeting with a recording.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct RecapCard {
45 pub title: String,
46 pub date_line: String,
47 pub recording: RecordingCard,
48}
49
50/// A meeting or recording event as Teams draws it: one muted line, icon in the avatar column.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct CallNotice {
53 pub stamp: String,
54 pub text: String,
55 pub emphasis: Option<String>,
31}
56}
32
57
33#[derive(Debug, Clone, PartialEq, Eq)]
58#[derive(Debug, Clone, PartialEq, Eq)]
@@ -39,7 +64,23 @@ pub struct CallCard {
39 pub started: bool,
64 pub started: bool,
40 pub participants: Vec<CallParticipant>,
65 pub participants: Vec<CallParticipant>,
41 pub extra_participants: usize,
66 pub extra_participants: usize,
42 pub recording: Option<RecordingCard>,
67 pub notice: Option<CallNotice>,
68 pub recap: Option<RecapCard>,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct MeetingSlot {
73 pub start: DateTime<Utc>,
74 pub end: DateTime<Utc>,
75}
76
77/// What the meeting rows need beyond the messages: the chat topic, the calendar occurrences
78/// and the recording expiry the Recap tab reads, keyed by the saved recording message id.
79#[derive(Debug, Clone, Default, PartialEq)]
80pub struct MeetingInfo {
81 pub title: Option<String>,
82 pub slots: Vec<MeetingSlot>,
83 pub expiry_days: HashMap<String, i64>,
43}
84}
44
85
45pub struct CallNames<'a> {
86pub struct CallNames<'a> {
@@ -56,6 +97,17 @@ impl CallNames<'_> {
56 }
97 }
57}
98}
58
99
100pub struct CallClock<'a> {
101 pub offset: FixedOffset,
102 pub today: NaiveDate,
103 pub meeting: &'a MeetingInfo,
104}
105
106struct SavedRecording {
107 message_id: String,
108 event: CallEvent,
109}
110
59/// Which call events of a timeline show as rows: Teams keeps one row per recording start and stop,
111/// Which call events of a timeline show as rows: Teams keeps one row per recording start and stop,
60/// hides transcript notices and, for calls (not meetings), the start once the call ended.
112/// hides transcript notices and, for calls (not meetings), the start once the call ended.
61pub struct CallTimeline {
113pub struct CallTimeline {
@@ -63,10 +115,17 @@ pub struct CallTimeline {
63 finished: HashSet<String>,
115 finished: HashSet<String>,
64 transcripts: HashSet<String>,
116 transcripts: HashSet<String>,
65 newest_open_start: Option<usize>,
117 newest_open_start: Option<usize>,
118 started_at: HashMap<String, DateTime<Utc>>,
119 ended_at: HashMap<String, DateTime<Utc>>,
120 saved: HashMap<String, SavedRecording>,
66}
121}
67
122
68impl CallTimeline {
123impl CallTimeline {
69 pub fn new(events: &[Option<CallEvent>]) -> Self {
124 pub fn new(events: &[Option<CallEvent>]) -> Self {
125 Self::with_records(events, &[])
126 }
127
128 pub fn with_records(events: &[Option<CallEvent>], records: &[&MessageRecord]) -> Self {
70 let finished: HashSet<String> = events
129 let finished: HashSet<String> = events
71 .iter()
130 .iter()
72 .flatten()
131 .flatten()
@@ -103,11 +162,42 @@ impl CallTimeline {
103 event.phase == CallPhase::Started && !finished.contains(&event.call_id)
162 event.phase == CallPhase::Started && !finished.contains(&event.call_id)
104 })
163 })
105 });
164 });
165 let mut started_at = HashMap::new();
166 let mut ended_at = HashMap::new();
167 let mut saved = HashMap::new();
168 for (event, record) in events.iter().zip(records) {
169 let Some(event) = event else {
170 continue;
171 };
172 match event.phase {
173 CallPhase::Started => {
174 started_at
175 .entry(event.call_id.clone())
176 .or_insert(record.created_at);
177 }
178 CallPhase::Ended => {
179 ended_at.insert(event.call_id.clone(), record.created_at);
180 }
181 CallPhase::RecordingSaved => {
182 saved.insert(
183 event.call_id.clone(),
184 SavedRecording {
185 message_id: record.message_id.clone(),
186 event: event.clone(),
187 },
188 );
189 }
190 _ => {}
191 }
192 }
106 CallTimeline {
193 CallTimeline {
107 hidden,
194 hidden,
108 finished,
195 finished,
109 transcripts,
196 transcripts,
110 newest_open_start,
197 newest_open_start,
198 started_at,
199 ended_at,
200 saved,
111 }
201 }
112 }
202 }
113
203
@@ -126,6 +216,94 @@ impl CallTimeline {
126 pub fn has_transcript(&self, call_id: &str) -> bool {
216 pub fn has_transcript(&self, call_id: &str) -> bool {
127 self.transcripts.contains(call_id)
217 self.transcripts.contains(call_id)
128 }
218 }
219
220 /// A recording that stops with the meeting end has no one who stopped it; Teams then says
221 /// "Recording stopped." instead of naming the recorder.
222 fn stopped_by_meeting_end(&self, event: &CallEvent, created_at: DateTime<Utc>) -> bool {
223 self.ended_at.get(&event.call_id).is_some_and(|ended_at| {
224 (*ended_at - created_at).num_seconds().abs() <= AUTO_STOP_SECONDS
225 })
226 }
227
228 fn recap(
229 &self,
230 ended: &CallEvent,
231 ended_at: DateTime<Utc>,
232 clock: &CallClock,
233 ) -> Option<RecapCard> {
234 if ended.phase != CallPhase::Ended || ended.call_type != CallType::Meeting {
235 return None;
236 }
237 let saved = self.saved.get(&ended.call_id)?;
238 let started_at = self
239 .started_at
240 .get(&ended.call_id)
241 .copied()
242 .or_else(|| {
243 ended
244 .duration_seconds
245 .map(|seconds| ended_at - chrono::Duration::seconds(seconds as i64))
246 })
247 .unwrap_or(ended_at);
248 let recording = recording_card(
249 &saved.event,
250 &saved.message_id,
251 self.has_transcript(&ended.call_id),
252 clock.meeting,
253 )?;
254 let title = clock
255 .meeting
256 .title
257 .clone()
258 .filter(|title| !title.trim().is_empty())
259 .or_else(|| saved.event.recording.as_ref()?.title())
260 .unwrap_or_else(|| RECAP_FALLBACK_TITLE.to_owned());
261 Some(RecapCard {
262 title,
263 date_line: recap_date_line(started_at, ended_at, clock),
264 recording,
265 })
266 }
267}
268
269/// Teams dates the recap card with the scheduled occurrence; without a calendar match the call's
270/// own start and end stand in.
271fn recap_date_line(
272 started_at: DateTime<Utc>,
273 ended_at: DateTime<Utc>,
274 clock: &CallClock,
275) -> String {
276 let slot = clock
277 .meeting
278 .slots
279 .iter()
280 .filter(|slot| slot.start <= ended_at && slot.end >= started_at)
281 .min_by_key(|slot| (slot.start - started_at).num_seconds().abs())
282 .copied()
283 .unwrap_or(MeetingSlot {
284 start: started_at,
285 end: ended_at,
286 });
287 format!(
288 "{} - {}",
289 slot.start
290 .with_timezone(&clock.offset)
291 .format(RECAP_DATE_FORMAT),
292 slot.end
293 .with_timezone(&clock.offset)
294 .format(RECAP_TIME_FORMAT)
295 )
296}
297
298/// Teams writes the weekday in full on these lines ("Thursday 11:45"), unlike message times.
299fn notice_stamp(time: DateTime<Utc>, clock: &CallClock) -> String {
300 let local = time.with_timezone(&clock.offset);
301 let days_ago = (clock.today - local.date_naive()).num_days();
302 if (2..=WEEKDAY_STAMP_DAYS).contains(&days_ago) {
303 local.format("%A %H:%M").to_string()
304 } else {
305 format::post_time_label(time, clock.today, clock.offset)
306 }
129}
307}
130
308
131fn participants(event: &CallEvent, names: &CallNames) -> Vec<CallParticipant> {
309fn participants(event: &CallEvent, names: &CallNames) -> Vec<CallParticipant> {
@@ -143,13 +321,15 @@ fn participants(event: &CallEvent, names: &CallNames) -> Vec<CallParticipant> {
143 .collect()
321 .collect()
144}
322}
145
323
146fn recording_card(event: &CallEvent, message_id: &str, transcript: bool) -> Option<RecordingCard> {
324fn recording_card(
325 event: &CallEvent,
326 message_id: &str,
327 transcript: bool,
328 meeting: &MeetingInfo,
329) -> Option<RecordingCard> {
147 let recording = event.recording.as_ref()?;
330 let recording = event.recording.as_ref()?;
148 Some(RecordingCard {
331 Some(RecordingCard {
149 message_id: message_id.to_owned(),
332 message_id: message_id.to_owned(),
150 title: recording
151 .title()
152 .unwrap_or_else(|| RECORDING_FALLBACK_TITLE.to_owned()),
153 duration: event
333 duration: event
154 .duration_seconds
334 .duration_seconds
155 .filter(|seconds| *seconds > 0)
335 .filter(|seconds| *seconds > 0)
@@ -163,9 +343,71 @@ fn recording_card(event: &CallEvent, message_id: &str, transcript: bool) -> Opti
163 alt: None,
343 alt: None,
164 }),
344 }),
165 transcript,
345 transcript,
346 expires_in_days: meeting.expiry_days.get(message_id).copied(),
166 })
347 })
167}
348}
168
349
350fn day_count(days: i64) -> String {
351 if days == 1 {
352 "1 day".to_owned()
353 } else {
354 format!("{days} days")
355 }
356}
357
358struct NoticeSource<'a> {
359 event: &'a CallEvent,
360 message_id: &'a str,
361 stopped_by_meeting_end: bool,
362}
363
364fn notice_text(source: NoticeSource, names: &CallNames, meeting: &MeetingInfo) -> String {
365 let NoticeSource {
366 event,
367 message_id,
368 stopped_by_meeting_end,
369 } = source;
370 let initiator = || {
371 names.name(
372 event.initiator_id.as_deref(),
373 event.initiator_name.as_deref(),
374 )
375 };
376 match event.phase {
377 CallPhase::Ended => format!("{}:", event.title(false)),
378 CallPhase::RecordingStarted => match initiator() {
379 Some(name) => format!("{name} started recording."),
380 None => event.title(false).to_owned(),
381 },
382 CallPhase::RecordingStopped => match initiator().filter(|_| !stopped_by_meeting_end) {
383 Some(name) => format!("{name} stopped recording."),
384 None => format!("{}.", event.title(false)),
385 },
386 CallPhase::RecordingSaved => {
387 let saved = saved_to(event, names);
388 match meeting.expiry_days.get(message_id) {
389 Some(days) => format!("{saved} and will expire in {}.", day_count(*days)),
390 None => format!("{saved}."),
391 }
392 }
393 _ => event.title(false).to_owned(),
394 }
395}
396
397fn saved_to(event: &CallEvent, names: &CallNames) -> String {
398 let organizer_id = event
399 .recording
400 .as_ref()
401 .and_then(|recording| recording.organizer_id.as_deref());
402 if organizer_id.is_some() && organizer_id == names.my_user_id {
403 return "Recording has been saved to your OneDrive".to_owned();
404 }
405 match names.name(organizer_id, None) {
406 Some(owner) => format!("Recording has been saved to {owner}'s OneDrive"),
407 None => "Recording has been saved to OneDrive".to_owned(),
408 }
409}
410
169fn title(event: &CallEvent, missed: bool, names: &CallNames) -> String {
411fn title(event: &CallEvent, missed: bool, names: &CallNames) -> String {
170 match event.phase {
412 match event.phase {
171 CallPhase::RecordingStarted => {
413 CallPhase::RecordingStarted => {
@@ -177,30 +419,35 @@ fn title(event: &CallEvent, missed: bool, names: &CallNames) -> String {
177 None => event.title(false).to_owned(),
419 None => event.title(false).to_owned(),
178 }
420 }
179 }
421 }
180 CallPhase::RecordingSaved => {
422 CallPhase::RecordingSaved => saved_to(event, names),
181 let organizer_id = event
182 .recording
183 .as_ref()
184 .and_then(|recording| recording.organizer_id.as_deref());
185 if organizer_id.is_some() && organizer_id == names.my_user_id {
186 return "Recording has been saved to your OneDrive".to_owned();
187 }
188 match names.name(organizer_id, None) {
189 Some(owner) => format!("Recording has been saved to {owner}'s OneDrive"),
190 None => "Recording has been saved to OneDrive".to_owned(),
191 }
192 }
193 _ => event.title(missed).to_owned(),
423 _ => event.title(missed).to_owned(),
194 }
424 }
195}
425}
196
426
427/// Teams draws meeting and recording events as one-line notices; 1:1 and group calls keep the card.
428pub fn is_notice(event: &CallEvent) -> bool {
429 event.call_type == CallType::Meeting || event.is_recording()
430}
431
432pub struct CallSource<'a> {
433 pub event: &'a CallEvent,
434 pub message_id: &'a str,
435 pub created_at: DateTime<Utc>,
436 pub time: &'a str,
437}
438
197pub fn call_card(
439pub fn call_card(
198 event: &CallEvent,
440 source: CallSource,
199 message_id: &str,
200 time: &str,
201 names: &CallNames,
441 names: &CallNames,
202 transcript: bool,
442 clock: &CallClock,
443 timeline: &CallTimeline,
203) -> CallCard {
444) -> CallCard {
445 let CallSource {
446 event,
447 message_id,
448 created_at,
449 time,
450 } = source;
204 let missed = event.missed(names.my_user_id);
451 let missed = event.missed(names.my_user_id);
205 let detail = match (event.phase, event.duration_seconds) {
452 let detail = match (event.phase, event.duration_seconds) {
206 (CallPhase::Ended, Some(seconds)) if !missed => {
453 (CallPhase::Ended, Some(seconds)) if !missed => {
@@ -215,12 +462,29 @@ pub fn call_card(
215 };
462 };
216 let extra_participants = people.len().saturating_sub(MAX_AVATARS);
463 let extra_participants = people.len().saturating_sub(MAX_AVATARS);
217 people.truncate(MAX_AVATARS);
464 people.truncate(MAX_AVATARS);
465 let notice = is_notice(event).then(|| CallNotice {
466 stamp: notice_stamp(created_at, clock),
467 text: notice_text(
468 NoticeSource {
469 event,
470 message_id,
471 stopped_by_meeting_end: timeline.stopped_by_meeting_end(event, created_at),
472 },
473 names,
474 clock.meeting,
475 ),
476 emphasis: event
477 .duration_seconds
478 .filter(|_| event.phase == CallPhase::Ended)
479 .map(format_duration),
480 });
218 CallCard {
481 CallCard {
219 title: title(event, missed, names),
482 title: title(event, missed, names),
220 detail,
483 detail,
221 icon: match (missed, event.phase, event.call_type) {
484 icon: match (missed, event.phase, event.call_type) {
222 (true, _, _) => CallIcon::Missed,
485 (true, _, _) => CallIcon::Missed,
223 (false, CallPhase::RecordingStarted | CallPhase::RecordingSaved, _) => CallIcon::Record,
486 (false, CallPhase::RecordingStarted, _) => CallIcon::Record,
487 (false, CallPhase::RecordingSaved, _) => CallIcon::Saved,
224 (false, CallPhase::RecordingStopped | CallPhase::TranscriptStarted, _) => {
488 (false, CallPhase::RecordingStopped | CallPhase::TranscriptStarted, _) => {
225 CallIcon::RecordStop
489 CallIcon::RecordStop
226 }
490 }
@@ -231,14 +495,14 @@ pub fn call_card(
231 started: event.phase == CallPhase::Started,
495 started: event.phase == CallPhase::Started,
232 participants: people,
496 participants: people,
233 extra_participants,
497 extra_participants,
234 recording: (event.phase == CallPhase::RecordingSaved)
498 recap: timeline.recap(event, created_at, clock),
235 .then(|| recording_card(event, message_id, transcript))
499 notice,
236 .flatten(),
237 }
500 }
238}
501}
239
502
240#[cfg(test)]
503#[cfg(test)]
241mod tests {
504mod tests {
505 use chrono::TimeZone;
242 use teams_core::Recording;
506 use teams_core::Recording;
243
507
244 use super::*;
508 use super::*;
@@ -257,7 +521,7 @@ mod tests {
257 }
521 }
258 }
522 }
259
523
260 fn fixture_events() -> Vec<Option<CallEvent>> {
524 fn fixture_records() -> Vec<MessageRecord> {
261 let path = format!(
525 let path = format!(
262 "{}/../core/tests/fixtures/call_events/meeting_chat_recording.json",
526 "{}/../core/tests/fixtures/call_events/meeting_chat_recording.json",
263 env!("CARGO_MANIFEST_DIR")
527 env!("CARGO_MANIFEST_DIR")
@@ -269,7 +533,10 @@ mod tests {
269 .unwrap()
533 .unwrap()
270 .iter()
534 .iter()
271 .rev()
535 .rev()
272 .map(|message| CallEvent::from_graph(&message["eventDetail"]))
536 .map(|message| {
537 let message: graph::Message = serde_json::from_value(message.clone()).unwrap();
538 teams_core::message_record("meeting-chat", &message).unwrap()
539 })
273 .collect()
540 .collect()
274 }
541 }
275
542
@@ -286,93 +553,197 @@ mod tests {
286 ])
553 ])
287 }
554 }
288
555
289 #[test]
556 fn cards(records: &[MessageRecord], meeting: &MeetingInfo) -> Vec<CallCard> {
290 fn recorded_meeting_shows_like_teams() {
557 let events: Vec<Option<CallEvent>> = records.iter().map(teams_core::call_event).collect();
291 let events = fixture_events();
558 let timeline = CallTimeline::with_records(&events, &records.iter().collect::<Vec<_>>());
292 let timeline = CallTimeline::new(&events);
293 let names = names();
559 let names = names();
294 let lookup = CallNames {
560 let lookup = CallNames {
295 my_user_id: Some("me"),
561 my_user_id: Some("me"),
296 names: &names,
562 names: &names,
297 };
563 };
298 let titles: Vec<String> = events
564 let clock = CallClock {
565 offset: FixedOffset::east_opt(0).unwrap(),
566 today: NaiveDate::from_ymd_opt(2026, 10, 30).unwrap(),
567 meeting,
568 };
569 events
299 .iter()
570 .iter()
571 .zip(records)
300 .enumerate()
572 .enumerate()
301 .filter(|(index, _)| !timeline.hides(*index))
573 .filter(|(index, _)| !timeline.hides(*index))
302 .map(|(_, event)| {
574 .map(|(_, (event, record))| {
303 let event = event.as_ref().unwrap();
304 call_card(
575 call_card(
305 event,
576 CallSource {
306 "m",
577 event: event.as_ref().unwrap(),
307 "16:15",
578 message_id: &record.message_id,
579 created_at: record.created_at,
580 time: "16:15",
581 },
308 &lookup,
582 &lookup,
309 timeline.has_transcript(&event.call_id),
583 &clock,
584 &timeline,
310 )
585 )
311 .title
312 })
586 })
313 .collect();
587 .collect()
588 }
589
590 fn notice_line(card: &CallCard) -> String {
591 let notice = card.notice.as_ref().unwrap();
592 match &notice.emphasis {
593 Some(emphasis) => format!("{} {emphasis}", notice.text),
594 None => notice.text.clone(),
595 }
596 }
597
598 #[test]
599 fn recorded_meeting_shows_as_teams_notices() {
600 let shown = cards(&fixture_records(), &MeetingInfo::default());
601 let lines: Vec<String> = shown.iter().map(notice_line).collect();
314 assert_eq!(
602 assert_eq!(
315 titles,
603 lines,
316 [
604 [
317 "Meeting started",
605 "Meeting started",
318 "Sam Recorder started recording",
606 "Sam Recorder started recording.",
319 "Recording stopped",
607 "Recording stopped.",
320 "Meeting ended",
608 "Meeting ended: 16m 28s",
321 "Recording has been saved to Vera Organizer's OneDrive",
609 "Recording has been saved to Vera Organizer's OneDrive.",
322 ]
610 ]
323 );
611 );
612 let icons: Vec<CallIcon> = shown.iter().map(|card| card.icon).collect();
613 assert_eq!(
614 icons,
615 [
616 CallIcon::Video,
617 CallIcon::Record,
618 CallIcon::RecordStop,
619 CallIcon::Video,
620 CallIcon::Saved,
621 ]
622 );
623 assert!(
624 shown
625 .iter()
626 .all(|card| card.recap.is_none() == (card.title != "Meeting ended"))
627 );
324 }
628 }
325
629
326 #[test]
630 #[test]
327 fn saved_recording_becomes_a_card_with_transcript_and_thumbnail() {
631 fn a_recording_stopped_before_the_end_names_who_stopped_it() {
328 let events = fixture_events();
632 let mut records = fixture_records();
329 let timeline = CallTimeline::new(&events);
633 for record in records.iter_mut() {
330 let saved = events.last().unwrap().as_ref().unwrap();
634 if teams_core::call_event(record)
331 let names = HashMap::new();
635 .is_some_and(|event| event.phase == CallPhase::RecordingStopped)
332 let lookup = CallNames {
636 {
333 my_user_id: None,
637 record.created_at -= chrono::Duration::minutes(2);
334 names: &names,
638 }
639 }
640 let shown = cards(&records, &MeetingInfo::default());
641 assert_eq!(notice_line(&shown[2]), "Sam Recorder stopped recording.");
642 }
643
644 #[test]
645 fn ended_meeting_carries_the_recap_card_of_its_recording() {
646 let records = fixture_records();
647 let saved_id = records.last().unwrap().message_id.clone();
648 let meeting = MeetingInfo {
649 title: Some("Weekly sync".to_owned()),
650 slots: Vec::new(),
651 expiry_days: HashMap::from([(saved_id.clone(), 56)]),
335 };
652 };
336 let card = call_card(
653 let shown = cards(&records, &meeting);
337 saved,
654 let ended = shown
338 "saved-1",
655 .iter()
339 "16:16",
656 .find(|card| card.title == "Meeting ended")
340 &lookup,
657 .unwrap();
341 timeline.has_transcript(&saved.call_id),
658 let recap = ended.recap.as_ref().unwrap();
659 assert_eq!(recap.title, "Weekly sync");
660 assert_eq!(recap.recording.message_id, saved_id);
661 assert_eq!(recap.recording.duration.as_deref(), Some("13m 34s"));
662 assert_eq!(recap.recording.expires_in_days, Some(56));
663 assert!(recap.recording.transcript);
664 assert!(
665 recap
666 .recording
667 .thumbnail
668 .as_ref()
669 .unwrap()
670 .url
671 .contains("/thumbnails/")
672 );
673 assert!(shown.iter().filter(|card| card.recap.is_some()).count() == 1);
674 assert_eq!(
675 notice_line(shown.last().unwrap()),
676 "Recording has been saved to Vera Organizer's OneDrive and will expire in 56 days."
342 );
677 );
343 assert_eq!(card.title, "Recording has been saved to OneDrive");
678 }
344 assert_eq!(card.icon, CallIcon::Record);
679
345 let recording = card.recording.unwrap();
680 #[test]
346 assert_eq!(recording.title, "Weekly team meeting");
681 fn recap_date_prefers_the_calendar_occurrence() {
347 assert_eq!(recording.duration.as_deref(), Some("13m 34s"));
682 let started_at = Utc.with_ymd_and_hms(2026, 10, 15, 9, 46, 0).unwrap();
348 assert!(recording.transcript);
683 let ended_at = Utc.with_ymd_and_hms(2026, 10, 15, 9, 55, 0).unwrap();
349 assert_eq!(recording.message_id, "saved-1");
684 let mut meeting = MeetingInfo::default();
350 assert!(recording.thumbnail.unwrap().url.contains("/thumbnails/"));
685 let clock = |meeting: &MeetingInfo| {
686 recap_date_line(
687 started_at,
688 ended_at,
689 &CallClock {
690 offset: FixedOffset::east_opt(2 * 3600).unwrap(),
691 today: NaiveDate::from_ymd_opt(2026, 10, 17).unwrap(),
692 meeting,
693 },
694 )
695 };
696 assert_eq!(clock(&meeting), "Thursday, 15 October 2026 11:46 - 11:55");
697 meeting.slots = vec![
698 MeetingSlot {
699 start: Utc.with_ymd_and_hms(2026, 10, 14, 9, 45, 0).unwrap(),
700 end: Utc.with_ymd_and_hms(2026, 10, 14, 10, 0, 0).unwrap(),
701 },
702 MeetingSlot {
703 start: Utc.with_ymd_and_hms(2026, 10, 15, 9, 45, 0).unwrap(),
704 end: Utc.with_ymd_and_hms(2026, 10, 15, 10, 0, 0).unwrap(),
705 },
706 ];
707 assert_eq!(clock(&meeting), "Thursday, 15 October 2026 11:45 - 12:00");
708 }
709
710 #[test]
711 fn notice_stamps_spell_out_the_weekday_like_teams() {
712 let meeting = MeetingInfo::default();
713 let clock = CallClock {
714 offset: FixedOffset::east_opt(0).unwrap(),
715 today: NaiveDate::from_ymd_opt(2026, 10, 17).unwrap(),
716 meeting: &meeting,
717 };
718 let stamp = |day: u32| {
719 notice_stamp(
720 Utc.with_ymd_and_hms(2026, 10, day, 11, 45, 0).unwrap(),
721 &clock,
722 )
723 };
724 assert_eq!(stamp(17), "11:45");
725 assert_eq!(stamp(16), "Yesterday 11:45");
726 assert_eq!(stamp(15), "Thursday 11:45");
351 }
727 }
352
728
353 #[test]
729 #[test]
354 fn ended_meeting_lists_named_participants_up_to_four() {
730 fn ended_meeting_lists_named_participants_up_to_four() {
355 let events = fixture_events();
731 let shown = cards(&fixture_records(), &MeetingInfo::default());
356 let ended = events
732 let ended = shown
357 .iter()
733 .iter()
358 .flatten()
734 .find(|card| card.title == "Meeting ended")
359 .find(|event| event.phase == CallPhase::Ended)
360 .unwrap();
735 .unwrap();
361 let names = HashMap::new();
736 assert_eq!(ended.detail, "16m 28s \u{b7} 16:15");
362 let lookup = CallNames {
737 let shown_names: Vec<&str> = ended
363 my_user_id: None,
364 names: &names,
365 };
366 let card = call_card(ended, "m", "16:15", &lookup, false);
367 assert_eq!(card.detail, "16m 28s \u{b7} 16:15");
368 assert_eq!(card.icon, CallIcon::Video);
369 let shown: Vec<&str> = card
370 .participants
738 .participants
371 .iter()
739 .iter()
372 .map(|person| person.name.as_str())
740 .map(|person| person.name.as_str())
373 .collect();
741 .collect();
374 assert_eq!(shown, ["Person 1", "Person 2", "Person 3", "Person 4"]);
742 assert_eq!(
375 assert_eq!(card.extra_participants, 20);
743 shown_names,
744 ["Person 1", "Person 2", "Person 3", "Person 4"]
745 );
746 assert_eq!(ended.extra_participants, 20);
376 }
747 }
377
748
378 #[test]
749 #[test]
@@ -395,8 +766,9 @@ mod tests {
395 }
766 }
396
767
397 #[test]
768 #[test]
398 fn my_own_recording_is_saved_to_my_onedrive() {
769 fn calls_keep_their_card_and_my_recording_is_in_my_onedrive() {
399 let mut saved = event(CallPhase::RecordingSaved, CallType::Meeting, "c");
770 assert!(!is_notice(&event(CallPhase::Ended, CallType::Call, "c")));
771 let mut saved = event(CallPhase::RecordingSaved, CallType::Call, "c");
400 saved.recording = Some(Recording {
772 saved.recording = Some(Recording {
401 name: None,
773 name: None,
402 url: Some("https://contoso.example/rec.mp4".to_owned()),
774 url: Some("https://contoso.example/rec.mp4".to_owned()),
@@ -407,11 +779,17 @@ mod tests {
407 my_user_id: Some("me"),
779 my_user_id: Some("me"),
408 names: &names,
780 names: &names,
409 };
781 };
410 let card = call_card(&saved, "m", "9:00", &lookup, false);
782 assert_eq!(
411 assert_eq!(card.title, "Recording has been saved to your OneDrive");
783 notice_text(
412 let recording = card.recording.unwrap();
784 NoticeSource {
413 assert_eq!(recording.title, "Meeting recording");
785 event: &saved,
414 assert_eq!(recording.thumbnail, None);
786 message_id: "m",
415 assert_eq!(recording.duration, None);
787 stopped_by_meeting_end: false,
788 },
789 &lookup,
790 &MeetingInfo::default()
791 ),
792 "Recording has been saved to your OneDrive."
793 );
416 }
794 }
417}
795}
crates/app-state/src/demo_meetings.rs +36 −37
@@ -158,64 +158,63 @@ fn channel_meeting() -> Vec<MessageRecord> {
158 158 ]
159 159 }
160 160
161 fn standup_line(id: &str, time: DateTime<Utc>, event: CallEvent) -> MessageRecord {
162 record(DEMO_RECAP_CHAT, id, None, time, event)
163 }
164
161 165 fn recorded_standup() -> Vec<MessageRecord> {
162 let start = at(1, 9, 0);
166 let start = at(2, 11, 45);
163 167 let minutes = |count: i64| start + Duration::minutes(count);
164 let name = "Daily standup-1-Meeting Recording.mp4";
168 let name = "Daily standup-20261015_114602-Meeting Recording.mp4";
165 169 let url = format!("{DEMO_RECORDING_URL}/standup-1.mp4");
166 170 let people = [
167 171 (JONAS_ID, "Jonas Ortega"),
168 172 (DEMO_USER_ID, "Dana Demo"),
169 173 (MARA_ID, "Mara Lindqvist"),
170 174 ];
171 let line = |id: &str, offset: i64, event: CallEvent| {
172 record(DEMO_RECAP_CHAT, id, None, minutes(offset), event)
175 let saved_recording = |phase: CallPhase, seconds: Option<u64>, url: Option<&str>| {
176 recording(
177 event(phase, STANDUP_CALL, DEMO_USER_ID, seconds),
178 name,
179 url,
180 MARA_ID,
181 )
173 182 };
174 183 vec![
175 line(
184 standup_line(
176 185 "standup-1-start",
177 0,
186 start,
178 187 event(CallPhase::Started, STANDUP_CALL, JONAS_ID, None),
179 188 ),
180 line(
189 standup_line(
181 190 "standup-1-rec",
182 1,
183 recording(
184 event(CallPhase::RecordingStarted, STANDUP_CALL, JONAS_ID, Some(0)),
185 name,
186 None,
191 minutes(1),
192 saved_recording(CallPhase::RecordingStarted, Some(0), None),
193 ),
194 standup_line(
195 "standup-1-transcript",
196 minutes(1),
197 event(
198 CallPhase::TranscriptStarted,
199 STANDUP_CALL,
187 200 DEMO_USER_ID,
201 None,
188 202 ),
189 203 ),
190 line(
204 standup_line(
191 205 "standup-1-stop",
192 17,
193 recording(
194 event(
195 CallPhase::RecordingStopped,
196 STANDUP_CALL,
197 JONAS_ID,
198 Some(985),
199 ),
200 name,
201 None,
202 DEMO_USER_ID,
203 ),
206 minutes(10),
207 saved_recording(CallPhase::RecordingStopped, Some(531), None),
204 208 ),
205 line(
209 standup_line(
206 210 "standup-1-end",
207 18,
208 ended(STANDUP_CALL, JONAS_ID, 1080, &people),
211 minutes(10) + Duration::seconds(40),
212 ended(STANDUP_CALL, JONAS_ID, 586, &people),
209 213 ),
210 line(
211 "demo-recap-1",
212 19,
213 recording(
214 event(CallPhase::RecordingSaved, STANDUP_CALL, JONAS_ID, Some(985)),
215 name,
216 Some(&url),
217 DEMO_USER_ID,
218 ),
214 standup_line(
215 "demo-recap-0",
216 minutes(10) + Duration::seconds(55),
217 saved_recording(CallPhase::RecordingSaved, Some(531), Some(&url)),
219 218 ),
220 219 ]
221 220 }
@@ -158,64 +158,63 @@ fn channel_meeting() -> Vec<MessageRecord> {
158 ]
158 ]
159}
159}
160
160
161fn standup_line(id: &str, time: DateTime<Utc>, event: CallEvent) -> MessageRecord {
162 record(DEMO_RECAP_CHAT, id, None, time, event)
163}
164
161fn recorded_standup() -> Vec<MessageRecord> {
165fn recorded_standup() -> Vec<MessageRecord> {
162 let start = at(1, 9, 0);
166 let start = at(2, 11, 45);
163 let minutes = |count: i64| start + Duration::minutes(count);
167 let minutes = |count: i64| start + Duration::minutes(count);
164 let name = "Daily standup-1-Meeting Recording.mp4";
168 let name = "Daily standup-20261015_114602-Meeting Recording.mp4";
165 let url = format!("{DEMO_RECORDING_URL}/standup-1.mp4");
169 let url = format!("{DEMO_RECORDING_URL}/standup-1.mp4");
166 let people = [
170 let people = [
167 (JONAS_ID, "Jonas Ortega"),
171 (JONAS_ID, "Jonas Ortega"),
168 (DEMO_USER_ID, "Dana Demo"),
172 (DEMO_USER_ID, "Dana Demo"),
169 (MARA_ID, "Mara Lindqvist"),
173 (MARA_ID, "Mara Lindqvist"),
170 ];
174 ];
171 let line = |id: &str, offset: i64, event: CallEvent| {
175 let saved_recording = |phase: CallPhase, seconds: Option<u64>, url: Option<&str>| {
172 record(DEMO_RECAP_CHAT, id, None, minutes(offset), event)
176 recording(
177 event(phase, STANDUP_CALL, DEMO_USER_ID, seconds),
178 name,
179 url,
180 MARA_ID,
181 )
173 };
182 };
174 vec![
183 vec![
175 line(
184 standup_line(
176 "standup-1-start",
185 "standup-1-start",
177 0,
186 start,
178 event(CallPhase::Started, STANDUP_CALL, JONAS_ID, None),
187 event(CallPhase::Started, STANDUP_CALL, JONAS_ID, None),
179 ),
188 ),
180 line(
189 standup_line(
181 "standup-1-rec",
190 "standup-1-rec",
182 1,
191 minutes(1),
183 recording(
192 saved_recording(CallPhase::RecordingStarted, Some(0), None),
184 event(CallPhase::RecordingStarted, STANDUP_CALL, JONAS_ID, Some(0)),
193 ),
185 name,
194 standup_line(
186 None,
195 "standup-1-transcript",
196 minutes(1),
197 event(
198 CallPhase::TranscriptStarted,
199 STANDUP_CALL,
187 DEMO_USER_ID,
200 DEMO_USER_ID,
201 None,
188 ),
202 ),
189 ),
203 ),
190 line(
204 standup_line(
191 "standup-1-stop",
205 "standup-1-stop",
192 17,
206 minutes(10),
193 recording(
207 saved_recording(CallPhase::RecordingStopped, Some(531), None),
194 event(
195 CallPhase::RecordingStopped,
196 STANDUP_CALL,
197 JONAS_ID,
198 Some(985),
199 ),
200 name,
201 None,
202 DEMO_USER_ID,
203 ),
204 ),
208 ),
205 line(
209 standup_line(
206 "standup-1-end",
210 "standup-1-end",
207 18,
211 minutes(10) + Duration::seconds(40),
208 ended(STANDUP_CALL, JONAS_ID, 1080, &people),
212 ended(STANDUP_CALL, JONAS_ID, 586, &people),
209 ),
213 ),
210 line(
214 standup_line(
211 "demo-recap-1",
215 "demo-recap-0",
212 19,
216 minutes(10) + Duration::seconds(55),
213 recording(
217 saved_recording(CallPhase::RecordingSaved, Some(531), Some(&url)),
214 event(CallPhase::RecordingSaved, STANDUP_CALL, JONAS_ID, Some(985)),
215 name,
216 Some(&url),
217 DEMO_USER_ID,
218 ),
219 ),
218 ),
220 ]
219 ]
221}
220}
crates/app-state/src/notify/mod.rs +2 −0
@@ -3,6 +3,7 @@ pub mod layout;
3 3 pub mod rules;
4 4 pub mod settings;
5 5 pub mod stack;
6 pub mod taskbar;
6 7 pub mod text;
7 8
8 9 pub use app_base::notify::{badge, platform, sound_cache, sounds};
@@ -11,3 +12,4 @@ pub use incoming::{IncomingTracker, LateArrivals, preview_of};
11 12 #[cfg(windows)]
12 13 pub use platform::native_handle;
13 14 pub use rules::{ChatKind, Incoming, Preview, alerts};
15 pub use taskbar::taskbar_badge_count;
@@ -3,6 +3,7 @@ pub mod layout;
3pub mod rules;
3pub mod rules;
4pub mod settings;
4pub mod settings;
5pub mod stack;
5pub mod stack;
6pub mod taskbar;
6pub mod text;
7pub mod text;
7
8
8pub use app_base::notify::{badge, platform, sound_cache, sounds};
9pub use app_base::notify::{badge, platform, sound_cache, sounds};
@@ -11,3 +12,4 @@ pub use incoming::{IncomingTracker, LateArrivals, preview_of};
11#[cfg(windows)]
12#[cfg(windows)]
12pub use platform::native_handle;
13pub use platform::native_handle;
13pub use rules::{ChatKind, Incoming, Preview, alerts};
14pub use rules::{ChatKind, Incoming, Preview, alerts};
15pub use taskbar::taskbar_badge_count;
crates/app-state/src/notify/taskbar.rs added +127 −0
@@ -0,0 +1,127 @@
1 use std::collections::HashSet;
2
3 use store::Sidebar;
4
5 use crate::activity::Kind;
6 use crate::activity::feed::Feed;
7 use crate::sidebar_model::unread_chat_count;
8
9 pub fn taskbar_badge_count(sidebar: &Sidebar, feed: &Feed, adaptive_rail: bool) -> usize {
10 let channel_ids: HashSet<&str> = sidebar
11 .teams
12 .iter()
13 .flat_map(|team| team.channels.iter())
14 .map(|channel| channel.id.as_str())
15 .collect();
16 let is_channel = |conversation_id: &str| channel_ids.contains(conversation_id);
17 let activity = feed
18 .unread_entries()
19 .filter(|entry| entry.kind != Kind::Messages || is_channel(&entry.conversation_id))
20 .count();
21 let channels_with_mentions = if adaptive_rail {
22 feed.unread_entries()
23 .filter(|entry| entry.kind == Kind::Mention && is_channel(&entry.conversation_id))
24 .map(|entry| entry.conversation_id.as_str())
25 .collect::<HashSet<_>>()
26 .len()
27 } else {
28 0
29 };
30 activity + unread_chat_count(&sidebar.chats) as usize + channels_with_mentions
31 }
32
33 #[cfg(test)]
34 mod tests {
35 use chrono::Utc;
36 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
37
38 use super::*;
39 use crate::activity::Entry;
40
41 fn sidebar() -> Sidebar {
42 let chat = |id: &str, unread: bool, muted: bool| ChatRecord {
43 id: id.into(),
44 unread,
45 muted,
46 ..Default::default()
47 };
48 let channel = |id: &str| ChannelRecord {
49 id: id.into(),
50 team_id: "team".into(),
51 name: id.into(),
52 membership_type: None,
53 last_message_at: None,
54 unread: true,
55 };
56 Sidebar {
57 chats: vec![
58 chat("chat-unread", true, false),
59 chat("chat-muted", true, true),
60 chat("chat-read", false, false),
61 ],
62 teams: vec![SidebarTeam {
63 team: TeamRecord {
64 id: "team".into(),
65 name: "Team".into(),
66 },
67 channels: vec![channel("channel-a"), channel("channel-b")],
68 hidden: false,
69 hidden_channel_ids: vec!["channel-b".into()],
70 notifications: Default::default(),
71 }],
72 }
73 }
74
75 fn feed(entries: &[(&str, Kind, bool)]) -> Feed {
76 let mut feed = Feed::load(Vec::new());
77 for (conversation_id, kind, read) in entries {
78 feed.add(Entry {
79 id: 0,
80 conversation_id: (*conversation_id).into(),
81 kind: *kind,
82 message_id: String::new(),
83 actors: Vec::new(),
84 preview: String::new(),
85 glyphs: Vec::new(),
86 count: 1,
87 updated_at: Utc::now(),
88 read: *read,
89 });
90 }
91 feed
92 }
93
94 #[test]
95 fn unread_channel_posts_without_activity_do_not_count() {
96 assert_eq!(taskbar_badge_count(&sidebar(), &feed(&[]), true), 1);
97 }
98
99 #[test]
100 fn muted_chats_never_count_as_chats() {
101 let mentioned = feed(&[("chat-muted", Kind::Mention, false)]);
102 assert_eq!(taskbar_badge_count(&sidebar(), &mentioned, false), 2);
103 }
104
105 #[test]
106 fn chat_message_rows_are_counted_once_by_the_chat() {
107 let rows = feed(&[
108 ("chat-unread", Kind::Messages, false),
109 ("chat-unread", Kind::Reaction, false),
110 ("channel-a", Kind::Messages, false),
111 ("channel-a", Kind::Reaction, true),
112 ]);
113 assert_eq!(taskbar_badge_count(&sidebar(), &rows, false), 3);
114 }
115
116 #[test]
117 fn the_adaptive_rail_adds_one_per_channel_with_an_unread_mention() {
118 let mentions = feed(&[
119 ("channel-a", Kind::Mention, false),
120 ("channel-a", Kind::Mention, false),
121 ("channel-b", Kind::Mention, false),
122 ("chat-unread", Kind::Mention, false),
123 ]);
124 assert_eq!(taskbar_badge_count(&sidebar(), &mentions, false), 5);
125 assert_eq!(taskbar_badge_count(&sidebar(), &mentions, true), 7);
126 }
127 }
@@ -0,0 +1,127 @@
1use std::collections::HashSet;
2
3use store::Sidebar;
4
5use crate::activity::Kind;
6use crate::activity::feed::Feed;
7use crate::sidebar_model::unread_chat_count;
8
9pub fn taskbar_badge_count(sidebar: &Sidebar, feed: &Feed, adaptive_rail: bool) -> usize {
10 let channel_ids: HashSet<&str> = sidebar
11 .teams
12 .iter()
13 .flat_map(|team| team.channels.iter())
14 .map(|channel| channel.id.as_str())
15 .collect();
16 let is_channel = |conversation_id: &str| channel_ids.contains(conversation_id);
17 let activity = feed
18 .unread_entries()
19 .filter(|entry| entry.kind != Kind::Messages || is_channel(&entry.conversation_id))
20 .count();
21 let channels_with_mentions = if adaptive_rail {
22 feed.unread_entries()
23 .filter(|entry| entry.kind == Kind::Mention && is_channel(&entry.conversation_id))
24 .map(|entry| entry.conversation_id.as_str())
25 .collect::<HashSet<_>>()
26 .len()
27 } else {
28 0
29 };
30 activity + unread_chat_count(&sidebar.chats) as usize + channels_with_mentions
31}
32
33#[cfg(test)]
34mod tests {
35 use chrono::Utc;
36 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
37
38 use super::*;
39 use crate::activity::Entry;
40
41 fn sidebar() -> Sidebar {
42 let chat = |id: &str, unread: bool, muted: bool| ChatRecord {
43 id: id.into(),
44 unread,
45 muted,
46 ..Default::default()
47 };
48 let channel = |id: &str| ChannelRecord {
49 id: id.into(),
50 team_id: "team".into(),
51 name: id.into(),
52 membership_type: None,
53 last_message_at: None,
54 unread: true,
55 };
56 Sidebar {
57 chats: vec![
58 chat("chat-unread", true, false),
59 chat("chat-muted", true, true),
60 chat("chat-read", false, false),
61 ],
62 teams: vec![SidebarTeam {
63 team: TeamRecord {
64 id: "team".into(),
65 name: "Team".into(),
66 },
67 channels: vec![channel("channel-a"), channel("channel-b")],
68 hidden: false,
69 hidden_channel_ids: vec!["channel-b".into()],
70 notifications: Default::default(),
71 }],
72 }
73 }
74
75 fn feed(entries: &[(&str, Kind, bool)]) -> Feed {
76 let mut feed = Feed::load(Vec::new());
77 for (conversation_id, kind, read) in entries {
78 feed.add(Entry {
79 id: 0,
80 conversation_id: (*conversation_id).into(),
81 kind: *kind,
82 message_id: String::new(),
83 actors: Vec::new(),
84 preview: String::new(),
85 glyphs: Vec::new(),
86 count: 1,
87 updated_at: Utc::now(),
88 read: *read,
89 });
90 }
91 feed
92 }
93
94 #[test]
95 fn unread_channel_posts_without_activity_do_not_count() {
96 assert_eq!(taskbar_badge_count(&sidebar(), &feed(&[]), true), 1);
97 }
98
99 #[test]
100 fn muted_chats_never_count_as_chats() {
101 let mentioned = feed(&[("chat-muted", Kind::Mention, false)]);
102 assert_eq!(taskbar_badge_count(&sidebar(), &mentioned, false), 2);
103 }
104
105 #[test]
106 fn chat_message_rows_are_counted_once_by_the_chat() {
107 let rows = feed(&[
108 ("chat-unread", Kind::Messages, false),
109 ("chat-unread", Kind::Reaction, false),
110 ("channel-a", Kind::Messages, false),
111 ("channel-a", Kind::Reaction, true),
112 ]);
113 assert_eq!(taskbar_badge_count(&sidebar(), &rows, false), 3);
114 }
115
116 #[test]
117 fn the_adaptive_rail_adds_one_per_channel_with_an_unread_mention() {
118 let mentions = feed(&[
119 ("channel-a", Kind::Mention, false),
120 ("channel-a", Kind::Mention, false),
121 ("channel-b", Kind::Mention, false),
122 ("chat-unread", Kind::Mention, false),
123 ]);
124 assert_eq!(taskbar_badge_count(&sidebar(), &mentions, false), 5);
125 assert_eq!(taskbar_badge_count(&sidebar(), &mentions, true), 7);
126 }
127}
crates/app-state/src/rows.rs +32 −29
@@ -14,8 +14,11 @@ use teams_core::{
14 14 reactions, readable_text, translated_spans,
15 15 };
16 16
17 pub use crate::call_rows::{CallCard, CallIcon, CallParticipant, RecordingCard};
18 use crate::call_rows::{CallNames, CallTimeline, call_card};
17 pub use crate::call_rows::{
18 CallCard, CallIcon, CallNotice, CallParticipant, MeetingInfo, MeetingSlot, RecapCard,
19 RecordingCard,
20 };
21 use crate::call_rows::{CallClock, CallNames, CallSource, CallTimeline, call_card};
19 22 use crate::card_state::CardOverride;
20 23 use crate::format;
21 24 use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
@@ -563,6 +566,7 @@ pub struct RowContext {
563 566 pub card_overrides: HashMap<String, CardOverride>,
564 567 pub translation: TranslationContext,
565 568 pub skin_tone: u8,
569 pub meeting: MeetingInfo,
566 570 }
567 571
568 572 fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
@@ -580,7 +584,7 @@ fn call_row(
580 584 record: &MessageRecord,
581 585 event: &CallEvent,
582 586 context: &RowContext,
583 transcript: bool,
587 timeline: &CallTimeline,
584 588 ) -> MessageRow {
585 589 let my_user_id = context.my_user_id.as_deref();
586 590 let time = clock_label(record.created_at, context.offset);
@@ -633,11 +637,19 @@ fn call_row(
633 637 forwarded: false,
634 638 translation: None,
635 639 call: Some(call_card(
636 event,
637 &record.message_id,
638 &time,
640 CallSource {
641 event,
642 message_id: &record.message_id,
643 created_at: record.created_at,
644 time: &time,
645 },
639 646 &names,
640 transcript,
647 &CallClock {
648 offset: context.offset,
649 today: context.today,
650 meeting: &context.meeting,
651 },
652 timeline,
641 653 )),
642 654 time,
643 655 }
@@ -706,7 +718,8 @@ fn message_row_with(
706 718 quoted: &HashMap<String, String>,
707 719 ) -> MessageRow {
708 720 if let Some(event) = call_event(record) {
709 return call_row(record, &event, context, false);
721 let events = [Some(event.clone())];
722 return call_row(record, &event, context, &CallTimeline::new(&events));
710 723 }
711 724 let local = record.created_at.with_timezone(&context.offset);
712 725 let images = images(record);
@@ -778,7 +791,7 @@ pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: boo
778 791 rows.push(Row::LoadOlder);
779 792 }
780 793 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
781 let timeline = CallTimeline::new(&events);
794 let timeline = CallTimeline::with_records(&events, &records.iter().collect::<Vec<_>>());
782 795 let mut previous_day: Option<NaiveDate> = None;
783 796 let quoted = quoted_texts(records);
784 797 for (index, (record, event)) in records.iter().zip(&events).enumerate() {
@@ -786,12 +799,7 @@ pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: boo
786 799 continue;
787 800 }
788 801 let mut row = match event {
789 Some(event) => call_row(
790 record,
791 event,
792 context,
793 timeline.has_transcript(&event.call_id),
794 ),
802 Some(event) => call_row(record, event, context, &timeline),
795 803 None => message_row_with(record, context, &quoted),
796 804 };
797 805 if let Some(call) = row.call.as_mut() {
@@ -849,12 +857,7 @@ fn post_message_row(
849 857 timeline: &CallTimeline,
850 858 ) -> MessageRow {
851 859 let mut row = match call_event(record) {
852 Some(event) => call_row(
853 record,
854 &event,
855 context,
856 timeline.has_transcript(&event.call_id),
857 ),
860 Some(event) => call_row(record, &event, context, timeline),
858 861 None => message_row(record, context),
859 862 };
860 863 row.day_header = None;
@@ -885,7 +888,7 @@ fn meeting_root_row(
885 888 ..ended_event
886 889 };
887 890 summary.call_type = started.call_type;
888 let mut row = call_row(ended_record, &summary, context, false);
891 let mut row = call_row(ended_record, &summary, context, timeline);
889 892 row.key = root.message_id.clone();
890 893 row.created_at = root.created_at;
891 894 row.reply_root = None;
@@ -1291,6 +1294,7 @@ mod tests {
1291 1294 card_overrides: HashMap::new(),
1292 1295 translation: TranslationContext::default(),
1293 1296 skin_tone: 0,
1297 meeting: MeetingInfo::default(),
1294 1298 }
1295 1299 }
1296 1300
@@ -2116,13 +2120,12 @@ mod tests {
2116 2120 let post = feed_post(&rows[0]);
2117 2121 assert_eq!(post.replies.len(), 1);
2118 2122 assert_eq!(post.hidden_reply_count, 0);
2119 let recording = post.replies[0]
2120 .call
2121 .as_ref()
2122 .and_then(|call| call.recording.as_ref())
2123 .unwrap();
2124 assert_eq!(recording.title, "Weekly team meeting");
2125 assert!(recording.transcript);
2123 let saved = post.replies[0].call.as_ref().unwrap();
2124 assert_eq!(saved.icon, CallIcon::Saved);
2125 assert_eq!(
2126 saved.notice.as_ref().unwrap().text,
2127 "Recording has been saved to OneDrive."
2128 );
2126 2129 let thread = thread_rows(&records, &root_id, &call_context());
2127 2130 let calls = thread
2128 2131 .iter()
@@ -14,8 +14,11 @@ use teams_core::{
14 reactions, readable_text, translated_spans,
14 reactions, readable_text, translated_spans,
15};
15};
16
16
17pub use crate::call_rows::{CallCard, CallIcon, CallParticipant, RecordingCard};
17pub use crate::call_rows::{
18use crate::call_rows::{CallNames, CallTimeline, call_card};
18 CallCard, CallIcon, CallNotice, CallParticipant, MeetingInfo, MeetingSlot, RecapCard,
19 RecordingCard,
20};
21use crate::call_rows::{CallClock, CallNames, CallSource, CallTimeline, call_card};
19use crate::card_state::CardOverride;
22use crate::card_state::CardOverride;
20use crate::format;
23use crate::format;
21use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
24use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
@@ -563,6 +566,7 @@ pub struct RowContext {
563 pub card_overrides: HashMap<String, CardOverride>,
566 pub card_overrides: HashMap<String, CardOverride>,
564 pub translation: TranslationContext,
567 pub translation: TranslationContext,
565 pub skin_tone: u8,
568 pub skin_tone: u8,
569 pub meeting: MeetingInfo,
566}
570}
567
571
568fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
572fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
@@ -580,7 +584,7 @@ fn call_row(
580 record: &MessageRecord,
584 record: &MessageRecord,
581 event: &CallEvent,
585 event: &CallEvent,
582 context: &RowContext,
586 context: &RowContext,
583 transcript: bool,
587 timeline: &CallTimeline,
584) -> MessageRow {
588) -> MessageRow {
585 let my_user_id = context.my_user_id.as_deref();
589 let my_user_id = context.my_user_id.as_deref();
586 let time = clock_label(record.created_at, context.offset);
590 let time = clock_label(record.created_at, context.offset);
@@ -633,11 +637,19 @@ fn call_row(
633 forwarded: false,
637 forwarded: false,
634 translation: None,
638 translation: None,
635 call: Some(call_card(
639 call: Some(call_card(
636 event,
640 CallSource {
637 &record.message_id,
641 event,
638 &time,
642 message_id: &record.message_id,
643 created_at: record.created_at,
644 time: &time,
645 },
639 &names,
646 &names,
640 transcript,
647 &CallClock {
648 offset: context.offset,
649 today: context.today,
650 meeting: &context.meeting,
651 },
652 timeline,
641 )),
653 )),
642 time,
654 time,
643 }
655 }
@@ -706,7 +718,8 @@ fn message_row_with(
706 quoted: &HashMap<String, String>,
718 quoted: &HashMap<String, String>,
707) -> MessageRow {
719) -> MessageRow {
708 if let Some(event) = call_event(record) {
720 if let Some(event) = call_event(record) {
709 return call_row(record, &event, context, false);
721 let events = [Some(event.clone())];
722 return call_row(record, &event, context, &CallTimeline::new(&events));
710 }
723 }
711 let local = record.created_at.with_timezone(&context.offset);
724 let local = record.created_at.with_timezone(&context.offset);
712 let images = images(record);
725 let images = images(record);
@@ -778,7 +791,7 @@ pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: boo
778 rows.push(Row::LoadOlder);
791 rows.push(Row::LoadOlder);
779 }
792 }
780 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
793 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
781 let timeline = CallTimeline::new(&events);
794 let timeline = CallTimeline::with_records(&events, &records.iter().collect::<Vec<_>>());
782 let mut previous_day: Option<NaiveDate> = None;
795 let mut previous_day: Option<NaiveDate> = None;
783 let quoted = quoted_texts(records);
796 let quoted = quoted_texts(records);
784 for (index, (record, event)) in records.iter().zip(&events).enumerate() {
797 for (index, (record, event)) in records.iter().zip(&events).enumerate() {
@@ -786,12 +799,7 @@ pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: boo
786 continue;
799 continue;
787 }
800 }
788 let mut row = match event {
801 let mut row = match event {
789 Some(event) => call_row(
802 Some(event) => call_row(record, event, context, &timeline),
790 record,
791 event,
792 context,
793 timeline.has_transcript(&event.call_id),
794 ),
795 None => message_row_with(record, context, &quoted),
803 None => message_row_with(record, context, &quoted),
796 };
804 };
797 if let Some(call) = row.call.as_mut() {
805 if let Some(call) = row.call.as_mut() {
@@ -849,12 +857,7 @@ fn post_message_row(
849 timeline: &CallTimeline,
857 timeline: &CallTimeline,
850) -> MessageRow {
858) -> MessageRow {
851 let mut row = match call_event(record) {
859 let mut row = match call_event(record) {
852 Some(event) => call_row(
860 Some(event) => call_row(record, &event, context, timeline),
853 record,
854 &event,
855 context,
856 timeline.has_transcript(&event.call_id),
857 ),
858 None => message_row(record, context),
861 None => message_row(record, context),
859 };
862 };
860 row.day_header = None;
863 row.day_header = None;
@@ -885,7 +888,7 @@ fn meeting_root_row(
885 ..ended_event
888 ..ended_event
886 };
889 };
887 summary.call_type = started.call_type;
890 summary.call_type = started.call_type;
888 let mut row = call_row(ended_record, &summary, context, false);
891 let mut row = call_row(ended_record, &summary, context, timeline);
889 row.key = root.message_id.clone();
892 row.key = root.message_id.clone();
890 row.created_at = root.created_at;
893 row.created_at = root.created_at;
891 row.reply_root = None;
894 row.reply_root = None;
@@ -1291,6 +1294,7 @@ mod tests {
1291 card_overrides: HashMap::new(),
1294 card_overrides: HashMap::new(),
1292 translation: TranslationContext::default(),
1295 translation: TranslationContext::default(),
1293 skin_tone: 0,
1296 skin_tone: 0,
1297 meeting: MeetingInfo::default(),
1294 }
1298 }
1295 }
1299 }
1296
1300
@@ -2116,13 +2120,12 @@ mod tests {
2116 let post = feed_post(&rows[0]);
2120 let post = feed_post(&rows[0]);
2117 assert_eq!(post.replies.len(), 1);
2121 assert_eq!(post.replies.len(), 1);
2118 assert_eq!(post.hidden_reply_count, 0);
2122 assert_eq!(post.hidden_reply_count, 0);
2119 let recording = post.replies[0]
2123 let saved = post.replies[0].call.as_ref().unwrap();
2120 .call
2124 assert_eq!(saved.icon, CallIcon::Saved);
2121 .as_ref()
2125 assert_eq!(
2122 .and_then(|call| call.recording.as_ref())
2126 saved.notice.as_ref().unwrap().text,
2123 .unwrap();
2127 "Recording has been saved to OneDrive."
2124 assert_eq!(recording.title, "Weekly team meeting");
2128 );
2125 assert!(recording.transcript);
2126 let thread = thread_rows(&records, &root_id, &call_context());
2129 let thread = thread_rows(&records, &root_id, &call_context());
2127 let calls = thread
2130 let calls = thread
2128 .iter()
2131 .iter()
crates/app/assets/symbols/description.svg deleted +0 −1
@@ -1 +0,0 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M320-240h320v-80H320v80Zm0-160h320v-80H320v80ZM240-80q-33 0-56.5-23.5T160-160v-640q0-33 23.5-56.5T240-880h320l240 240v480q0 33-23.5 56.5T720-80H240Zm280-520v-200H240v640h480v-440H520ZM240-800v200-200 640-640Z"/></svg>
@@ -1 +0,0 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M320-240h320v-80H320v80Zm0-160h320v-80H320v80ZM240-80q-33 0-56.5-23.5T160-160v-640q0-33 23.5-56.5T240-880h320l240 240v480q0 33-23.5 56.5T720-80H240Zm280-520v-200H240v640h480v-440H520ZM240-800v200-200 640-640Z"/></svg>
crates/app/assets/symbols/fluent_clock.svg added +1 −0
@@ -0,0 +1 @@
1 <svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"><path d="M6 1a5 5 0 1 1 0 10A5 5 0 0 1 6 1Zm0 1a4 4 0 1 0 0 8 4 4 0 0 0 0-8Zm-.5 1.5a.5.5 0 0 1 .5.41V6h1.5a.5.5 0 0 1 .09 1H5.5a.5.5 0 0 1-.5-.41V4c0-.28.22-.5.5-.5Z"/></svg>
@@ -0,0 +1 @@
1<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"><path d="M6 1a5 5 0 1 1 0 10A5 5 0 0 1 6 1Zm0 1a4 4 0 1 0 0 8 4 4 0 0 0 0-8Zm-.5 1.5a.5.5 0 0 1 .5.41V6h1.5a.5.5 0 0 1 .09 1H5.5a.5.5 0 0 1-.5-.41V4c0-.28.22-.5.5-.5Z"/></svg>
crates/app/assets/symbols/fluent_cloud_arrow_up.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2c2.82 0 4.41 1.92 4.65 4.25h.07a3.33 3.33 0 0 1 3.27 3.66c-.32-.4-.7-.76-1.12-1.07a2.3 2.3 0 0 0-2.150-1.6h-.07a1 1 0 0 1-1-.9C13.45 4.33 12.11 3 10 3S6.55 4.32 6.35 6.35a1 1 0 0 1-1 .9h-.07A2.33 2.33 0 0 0 3 9.62 2.33 2.33 0 0 0 5.28 12h2.67c-.09.32-.15.66-.18 1H5.28A3.33 3.33 0 0 1 2 9.62c0-1.8 1.37-3.27 3.1-3.37h.25C5.6 3.9 7.18 2 10 2Zm3.5 7a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9Zm1.6 4.9a.56.56 0 1 0 .8-.8l-2-2a.56.56 0 0 0-.8 0l-2 2a.56.56 0 1 0 .8.8l1.1-1.1v2.7a.5.5 0 0 0 1 0v-2.7l1.1 1.1Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2c2.82 0 4.41 1.92 4.65 4.25h.07a3.33 3.33 0 0 1 3.27 3.66c-.32-.4-.7-.76-1.12-1.07a2.3 2.3 0 0 0-2.150-1.6h-.07a1 1 0 0 1-1-.9C13.45 4.33 12.11 3 10 3S6.55 4.32 6.35 6.35a1 1 0 0 1-1 .9h-.07A2.33 2.33 0 0 0 3 9.62 2.33 2.33 0 0 0 5.28 12h2.67c-.09.32-.15.66-.18 1H5.28A3.33 3.33 0 0 1 2 9.62c0-1.8 1.37-3.27 3.1-3.37h.25C5.6 3.9 7.18 2 10 2Zm3.5 7a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9Zm1.6 4.9a.56.56 0 1 0 .8-.8l-2-2a.56.56 0 0 0-.8 0l-2 2a.56.56 0 1 0 .8.8l1.1-1.1v2.7a.5.5 0 0 0 1 0v-2.7l1.1 1.1Z"/></svg>
crates/app/assets/symbols/fluent_document_text.svg added +1 −0
@@ -0,0 +1 @@
1 <svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6.5 10a.5.5 0 0 0 0 1h7a.5.5 0 0 0 0-1h-7Zm0 2a.5.5 0 0 0 0 1h7a.5.5 0 0 0 0-1h-7Zm0 2a.5.5 0 0 0 0 1h7a.5.5 0 0 0 0-1h-7ZM4 4c0-1.1.9-2 2-2h4.59c.4 0 .78.16 1.06.44l3.91 3.91c.28.28.44.67.44 1.06V16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4Zm2-1a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8h-3.5A1.5 1.5 0 0 1 10 6.5V3H6Zm5.5 4h3.3L11 3.2v3.3c0 .28.22.5.5.5Z"/></svg>
@@ -0,0 +1 @@
1<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6.5 10a.5.5 0 0 0 0 1h7a.5.5 0 0 0 0-1h-7Zm0 2a.5.5 0 0 0 0 1h7a.5.5 0 0 0 0-1h-7Zm0 2a.5.5 0 0 0 0 1h7a.5.5 0 0 0 0-1h-7ZM4 4c0-1.1.9-2 2-2h4.59c.4 0 .78.16 1.06.44l3.91 3.91c.28.28.44.67.44 1.06V16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4Zm2-1a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8h-3.5A1.5 1.5 0 0 1 10 6.5V3H6Zm5.5 4h3.3L11 3.2v3.3c0 .28.22.5.5.5Z"/></svg>
crates/app/assets/symbols/fluent_record.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 14.5a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9ZM10 2a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm-7 8a7 7 0 1 1 14 0 7 7 0 0 1-14 0Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 14.5a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9ZM10 2a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm-7 8a7 7 0 1 1 14 0 7 7 0 0 1-14 0Z"/></svg>
crates/app/assets/symbols/fluent_record_stop.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 3a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm-8 7a8 8 0 1 1 16 0 8 8 0 0 1-16 0Zm5-2a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V8Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 3a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm-8 7a8 8 0 1 1 16 0 8 8 0 0 1-16 0Zm5-2a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V8Z"/></svg>
crates/app/assets/symbols/fluent_share.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="m13.33 12.84 4.5-4.42.05-.07a.59.59 0 0 0-.05-.77l-4.5-4.42-.06-.05c-.36-.27-.9-.01-.9.47V5.7l-.22.01C8.6 6.01 6.5 8.26 6 12.35c-.06.53.54.85.93.5a9.64 9.64 0 0 1 4.450-2.38c.24-.06.5-.1.74-.12l.26-.02v2.17c.06.46.61.67.95.34Zm-1.1-6.12 1.15-.08V4.61L16.82 8l-3.44 3.39V9.23l-1.36.12c-1.7.19-3.32.87-4.83 2 .3-1.33.8-2.34 1.47-3.06a5.2 5.2 0 0 1 3.57-1.57ZM5.5 4A2.5 2.5 0 0 0 3 6.5v8A2.5 2.5 0 0 0 5.5 17h8a2.5 2.5 0 0 0 2.5-2.5v-1a.5.5 0 0 0-1 0v1c0 .83-.67 1.5-1.5 1.5h-8A1.5 1.5 0 0 1 4 14.5v-8C4 5.67 4.67 5 5.5 5h3a.5.5 0 0 0 0-1h-3Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="m13.33 12.84 4.5-4.42.05-.07a.59.59 0 0 0-.05-.77l-4.5-4.42-.06-.05c-.36-.27-.9-.01-.9.47V5.7l-.22.01C8.6 6.01 6.5 8.26 6 12.35c-.06.53.54.85.93.5a9.64 9.64 0 0 1 4.450-2.38c.24-.06.5-.1.74-.12l.26-.02v2.17c.06.46.61.67.95.34Zm-1.1-6.12 1.15-.08V4.61L16.82 8l-3.44 3.39V9.23l-1.36.12c-1.7.19-3.32.87-4.83 2 .3-1.33.8-2.34 1.47-3.06a5.2 5.2 0 0 1 3.57-1.57ZM5.5 4A2.5 2.5 0 0 0 3 6.5v8A2.5 2.5 0 0 0 5.5 17h8a2.5 2.5 0 0 0 2.5-2.5v-1a.5.5 0 0 0-1 0v1c0 .83-.67 1.5-1.5 1.5h-8A1.5 1.5 0 0 1 4 14.5v-8C4 5.67 4.67 5 5.5 5h3a.5.5 0 0 0 0-1h-3Z"/></svg>
crates/app/assets/symbols/fluent_video.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M5 4a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h5a3 3 0 0 0 3-3v-.32l3.04 2.1c.83.57 1.96-.03 1.960-1.03v-7.5c0-1-1.13-1.6-1.96-1.03L13 7.32V7a3 3 0 0 0-3-3H5Zm8 4.54 3.6-2.5c.17-.1.4.01.4.21v7.5c0 .2-.23.32-.4.2L13 11.46V8.540ZM3 7c0-1.1.9-2 2-2h5a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M5 4a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h5a3 3 0 0 0 3-3v-.32l3.04 2.1c.83.57 1.96-.03 1.960-1.03v-7.5c0-1-1.13-1.6-1.96-1.03L13 7.32V7a3 3 0 0 0-3-3H5Zm8 4.54 3.6-2.5c.17-.1.4.01.4.21v7.5c0 .2-.23.32-.4.2L13 11.46V8.540ZM3 7c0-1.1.9-2 2-2h5a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"/></svg>
crates/app/assets/symbols/play_arrow.svg deleted +0 −1
@@ -1 +0,0 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M320-200v-560l440 280-440 280Z"/></svg>
@@ -1 +0,0 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M320-200v-560l440 280-440 280Z"/></svg>
crates/app/assets/symbols/radio_button_checked.svg deleted +0 −1
@@ -1 +0,0 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M480-280q83 0 141.5-58.5T680-480q0-83-58.5-141.5T480-680q-83 0-141.5 58.5T280-480q0 83 58.5 141.5T480-280Zm0 200q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Z"/></svg>
@@ -1 +0,0 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M480-280q83 0 141.5-58.5T680-480q0-83-58.5-141.5T480-680q-83 0-141.5 58.5T280-480q0 83 58.5 141.5T480-280Zm0 200q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Z"/></svg>
crates/app/assets/symbols/stop_circle.svg deleted +0 −1
@@ -1 +0,0 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M320-320h320v-320H320v320ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Z"/></svg>
@@ -1 +0,0 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M320-320h320v-320H320v320ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Z"/></svg>
crates/app/src/notify/center.rs +32 −38
@@ -21,8 +21,10 @@ use super::sounds::{CallTone, Ringtone};
21 21 use super::stack::{
22 22 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
23 23 };
24 use super::taskbar::taskbar_badge_count;
24 25 use super::text::describe;
25 26 use super::toast::{PillView, ToastView};
27 use crate::activity::ActivityCenter;
26 28 use crate::agents::{AgentRun, AgentRunsEvent, RunState};
27 29 use crate::app_state::{AppEvent, AppState, selection_for};
28 30 use crate::call::DemoScene;
@@ -65,6 +67,7 @@ impl OpenWindow {
65 67
66 68 pub struct NotificationCenter {
67 69 app: Entity<AppState>,
70 activity: Entity<ActivityCenter>,
68 71 main_window: AnyWindowHandle,
69 72 main_native: Option<NativeHandle>,
70 73 settings: Settings,
@@ -88,11 +91,17 @@ pub struct NotificationCenter {
88 91 shown_badge: Option<Badge>,
89 92 animations: bool,
90 93 _subscription: Subscription,
94 _activity_observation: Subscription,
91 95 _agent_subscription: Option<Subscription>,
92 96 }
93 97
94 98 impl NotificationCenter {
95 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
99 pub fn new(
100 app: Entity<AppState>,
101 activity: Entity<ActivityCenter>,
102 window: &mut Window,
103 cx: &mut Context<Self>,
104 ) -> Self {
96 105 let settings = settings::load(&app.read(cx).store);
97 106 let tray = if app.read(cx).mode.demo {
98 107 None
@@ -102,6 +111,7 @@ impl NotificationCenter {
102 111 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
103 112 this.on_app_event(event, cx);
104 113 });
114 let activity_observation = cx.observe(&activity, |this, _, cx| this.refresh_badge(cx));
105 115 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
106 116 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
107 117 if let AgentRunsEvent::Finished(run_id) = event
@@ -135,7 +145,9 @@ impl NotificationCenter {
135 145 shown_badge: None,
136 146 animations: platform::animations_enabled(),
137 147 app,
148 activity,
138 149 _subscription: subscription,
150 _activity_observation: activity_observation,
139 151 _agent_subscription: agent_subscription,
140 152 };
141 153 cx.spawn(async move |this, cx| {
@@ -902,10 +914,15 @@ impl NotificationCenter {
902 914 }
903 915
904 916 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
905 let (count, still_unread) =
906 unread_summary(&self.app.read(cx).sidebar, &self.unread_mentions);
917 let state = self.app.read(cx);
918 let count = taskbar_badge_count(
919 &state.sidebar,
920 self.activity.read(cx).feed(),
921 state.directory.section_settings.adaptive_rail(),
922 );
923 let still_unread = unread_conversation_ids(&state.sidebar);
907 924 self.unread_mentions
908 .retain(|conversation_id| still_unread.contains(conversation_id));
925 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
909 926 let badge = badge_for(count);
910 927 if badge == self.shown_badge {
911 928 return;
@@ -1211,31 +1228,17 @@ fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1211 1228 }
1212 1229 }
1213 1230
1214 pub fn unread_summary(
1215 sidebar: &Sidebar,
1216 unread_mentions: &HashSet<String>,
1217 ) -> (usize, HashSet<String>) {
1231 pub fn unread_conversation_ids(sidebar: &Sidebar) -> HashSet<&str> {
1218 1232 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
1219 1233 let channels = sidebar
1220 1234 .teams
1221 1235 .iter()
1222 1236 .flat_map(|team| team.channels.iter())
1223 1237 .filter(|channel| channel.unread);
1224 let silenced_chat_ids: HashSet<&str> = sidebar
1225 .chats
1226 .iter()
1227 .filter(|chat| chat.muted && !unread_mentions.contains(&chat.id))
1238 chats
1228 1239 .map(|chat| chat.id.as_str())
1229 .collect();
1230 let ids: HashSet<String> = chats
1231 .map(|chat| chat.id.clone())
1232 .chain(channels.map(|channel| channel.id.clone()))
1233 .collect();
1234 let counted = ids
1235 .iter()
1236 .filter(|id| !silenced_chat_ids.contains(id.as_str()))
1237 .count();
1238 (counted, ids)
1240 .chain(channels.map(|channel| channel.id.as_str()))
1241 .collect()
1239 1242 }
1240 1243
1241 1244 fn demo_incoming() -> Vec<Incoming> {
@@ -1310,7 +1313,7 @@ mod tests {
1310 1313
1311 1314 use std::collections::HashSet;
1312 1315
1313 use super::{preview_lines, unread_summary};
1316 use super::{preview_lines, unread_conversation_ids};
1314 1317 use store::Sidebar;
1315 1318
1316 1319 fn sidebar() -> Sidebar {
@@ -1348,21 +1351,12 @@ mod tests {
1348 1351 }
1349 1352
1350 1353 #[test]
1351 fn unread_summary_counts_chats_and_channels() {
1352 let (count, ids) = unread_summary(&sidebar(), &HashSet::new());
1353 assert_eq!(count, 2);
1354 assert!(ids.contains("a") && ids.contains("ch"));
1355 }
1356
1357 #[test]
1358 fn muted_chats_only_count_with_an_unread_mention() {
1359 let mut quiet = sidebar();
1360 quiet.chats[0].muted = true;
1361 let (count, ids) = unread_summary(&quiet, &HashSet::new());
1362 assert_eq!(count, 1);
1363 assert!(ids.contains("a"));
1364 let (count, _) = unread_summary(&quiet, &HashSet::from(["a".to_owned()]));
1365 assert_eq!(count, 2);
1354 fn unread_conversation_ids_hold_chats_and_channels() {
1355 let sidebar = sidebar();
1356 assert_eq!(
1357 unread_conversation_ids(&sidebar),
1358 HashSet::from(["a", "ch"])
1359 );
1366 1360 }
1367 1361
1368 1362 #[gpui_kit::test]
@@ -21,8 +21,10 @@ use super::sounds::{CallTone, Ringtone};
21use super::stack::{
21use super::stack::{
22 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
22 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
23};
23};
24use super::taskbar::taskbar_badge_count;
24use super::text::describe;
25use super::text::describe;
25use super::toast::{PillView, ToastView};
26use super::toast::{PillView, ToastView};
27use crate::activity::ActivityCenter;
26use crate::agents::{AgentRun, AgentRunsEvent, RunState};
28use crate::agents::{AgentRun, AgentRunsEvent, RunState};
27use crate::app_state::{AppEvent, AppState, selection_for};
29use crate::app_state::{AppEvent, AppState, selection_for};
28use crate::call::DemoScene;
30use crate::call::DemoScene;
@@ -65,6 +67,7 @@ impl OpenWindow {
65
67
66pub struct NotificationCenter {
68pub struct NotificationCenter {
67 app: Entity<AppState>,
69 app: Entity<AppState>,
70 activity: Entity<ActivityCenter>,
68 main_window: AnyWindowHandle,
71 main_window: AnyWindowHandle,
69 main_native: Option<NativeHandle>,
72 main_native: Option<NativeHandle>,
70 settings: Settings,
73 settings: Settings,
@@ -88,11 +91,17 @@ pub struct NotificationCenter {
88 shown_badge: Option<Badge>,
91 shown_badge: Option<Badge>,
89 animations: bool,
92 animations: bool,
90 _subscription: Subscription,
93 _subscription: Subscription,
94 _activity_observation: Subscription,
91 _agent_subscription: Option<Subscription>,
95 _agent_subscription: Option<Subscription>,
92}
96}
93
97
94impl NotificationCenter {
98impl NotificationCenter {
95 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
99 pub fn new(
100 app: Entity<AppState>,
101 activity: Entity<ActivityCenter>,
102 window: &mut Window,
103 cx: &mut Context<Self>,
104 ) -> Self {
96 let settings = settings::load(&app.read(cx).store);
105 let settings = settings::load(&app.read(cx).store);
97 let tray = if app.read(cx).mode.demo {
106 let tray = if app.read(cx).mode.demo {
98 None
107 None
@@ -102,6 +111,7 @@ impl NotificationCenter {
102 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
111 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
103 this.on_app_event(event, cx);
112 this.on_app_event(event, cx);
104 });
113 });
114 let activity_observation = cx.observe(&activity, |this, _, cx| this.refresh_badge(cx));
105 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
115 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
106 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
116 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
107 if let AgentRunsEvent::Finished(run_id) = event
117 if let AgentRunsEvent::Finished(run_id) = event
@@ -135,7 +145,9 @@ impl NotificationCenter {
135 shown_badge: None,
145 shown_badge: None,
136 animations: platform::animations_enabled(),
146 animations: platform::animations_enabled(),
137 app,
147 app,
148 activity,
138 _subscription: subscription,
149 _subscription: subscription,
150 _activity_observation: activity_observation,
139 _agent_subscription: agent_subscription,
151 _agent_subscription: agent_subscription,
140 };
152 };
141 cx.spawn(async move |this, cx| {
153 cx.spawn(async move |this, cx| {
@@ -902,10 +914,15 @@ impl NotificationCenter {
902 }
914 }
903
915
904 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
916 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
905 let (count, still_unread) =
917 let state = self.app.read(cx);
906 unread_summary(&self.app.read(cx).sidebar, &self.unread_mentions);
918 let count = taskbar_badge_count(
919 &state.sidebar,
920 self.activity.read(cx).feed(),
921 state.directory.section_settings.adaptive_rail(),
922 );
923 let still_unread = unread_conversation_ids(&state.sidebar);
907 self.unread_mentions
924 self.unread_mentions
908 .retain(|conversation_id| still_unread.contains(conversation_id));
925 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
909 let badge = badge_for(count);
926 let badge = badge_for(count);
910 if badge == self.shown_badge {
927 if badge == self.shown_badge {
911 return;
928 return;
@@ -1211,31 +1228,17 @@ fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1211 }
1228 }
1212}
1229}
1213
1230
1214pub fn unread_summary(
1231pub fn unread_conversation_ids(sidebar: &Sidebar) -> HashSet<&str> {
1215 sidebar: &Sidebar,
1216 unread_mentions: &HashSet<String>,
1217) -> (usize, HashSet<String>) {
1218 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
1232 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
1219 let channels = sidebar
1233 let channels = sidebar
1220 .teams
1234 .teams
1221 .iter()
1235 .iter()
1222 .flat_map(|team| team.channels.iter())
1236 .flat_map(|team| team.channels.iter())
1223 .filter(|channel| channel.unread);
1237 .filter(|channel| channel.unread);
1224 let silenced_chat_ids: HashSet<&str> = sidebar
1238 chats
1225 .chats
1226 .iter()
1227 .filter(|chat| chat.muted && !unread_mentions.contains(&chat.id))
1228 .map(|chat| chat.id.as_str())
1239 .map(|chat| chat.id.as_str())
1229 .collect();
1240 .chain(channels.map(|channel| channel.id.as_str()))
1230 let ids: HashSet<String> = chats
1241 .collect()
1231 .map(|chat| chat.id.clone())
1232 .chain(channels.map(|channel| channel.id.clone()))
1233 .collect();
1234 let counted = ids
1235 .iter()
1236 .filter(|id| !silenced_chat_ids.contains(id.as_str()))
1237 .count();
1238 (counted, ids)
1239}
1242}
1240
1243
1241fn demo_incoming() -> Vec<Incoming> {
1244fn demo_incoming() -> Vec<Incoming> {
@@ -1310,7 +1313,7 @@ mod tests {
1310
1313
1311 use std::collections::HashSet;
1314 use std::collections::HashSet;
1312
1315
1313 use super::{preview_lines, unread_summary};
1316 use super::{preview_lines, unread_conversation_ids};
1314 use store::Sidebar;
1317 use store::Sidebar;
1315
1318
1316 fn sidebar() -> Sidebar {
1319 fn sidebar() -> Sidebar {
@@ -1348,21 +1351,12 @@ mod tests {
1348 }
1351 }
1349
1352
1350 #[test]
1353 #[test]
1351 fn unread_summary_counts_chats_and_channels() {
1354 fn unread_conversation_ids_hold_chats_and_channels() {
1352 let (count, ids) = unread_summary(&sidebar(), &HashSet::new());
1355 let sidebar = sidebar();
1353 assert_eq!(count, 2);
1356 assert_eq!(
1354 assert!(ids.contains("a") && ids.contains("ch"));
1357 unread_conversation_ids(&sidebar),
1355 }
1358 HashSet::from(["a", "ch"])
1356
1359 );
1357 #[test]
1358 fn muted_chats_only_count_with_an_unread_mention() {
1359 let mut quiet = sidebar();
1360 quiet.chats[0].muted = true;
1361 let (count, ids) = unread_summary(&quiet, &HashSet::new());
1362 assert_eq!(count, 1);
1363 assert!(ids.contains("a"));
1364 let (count, _) = unread_summary(&quiet, &HashSet::from(["a".to_owned()]));
1365 assert_eq!(count, 2);
1366 }
1360 }
1367
1361
1368 #[gpui_kit::test]
1362 #[gpui_kit::test]
crates/app/src/views/call_card.rs +16 −148
@@ -3,11 +3,12 @@ use gpui_kit::prelude::FluentBuilder as _;
3 3 use gpui_kit::*;
4 4
5 5 use super::avatar::person_avatar;
6 use super::call_notice::{RecapActions, notice_row};
6 7 use super::message_row::{AVATAR_GAP, AVATAR_SIZE, RowAction, day_separator, new_marker};
7 8 use super::profile_card::opens_profile;
8 9 use super::widgets::symbol;
9 10 use crate::data::Directory;
10 use crate::rows::{CallCard, CallIcon, CallParticipant, MessageRow, RecordingCard};
11 use crate::rows::{CallCard, CallIcon, CallParticipant, MessageRow};
11 12 use crate::theme;
12 13
13 14 const SERIES_START_GAP: f32 = 8.;
@@ -20,19 +21,11 @@ const DETAIL_SIZE: f32 = 11.;
20 21 const JOIN_HEIGHT: f32 = 24.;
21 22 const PARTICIPANT_AVATAR: f32 = 20.;
22 23 const PARTICIPANT_GAP: f32 = 2.;
23 const TILE_WIDTH: f32 = 288.;
24 const TILE_HEIGHT: f32 = 162.;
25 const TILE_RADIUS: f32 = 8.;
26 const PLAY_CIRCLE: f32 = 40.;
27 const PLAY_GLYPH: f32 = 24.;
28 const DURATION_INSET: f32 = 6.;
29 const CHIP_HEIGHT: f32 = 26.;
30 24
31 25 pub struct CallActions {
32 26 pub call_back: RowAction,
33 27 pub join: RowAction,
34 pub open_recording: RowAction,
35 pub open_transcript: RowAction,
28 pub recap: RecapActions,
36 29 }
37 30
38 31 impl CallActions {
@@ -40,8 +33,12 @@ impl CallActions {
40 33 CallActions {
41 34 call_back: None,
42 35 join: None,
43 open_recording: None,
44 open_transcript: None,
36 recap: RecapActions {
37 view_recap: None,
38 open_recording: None,
39 transcript: None,
40 share: None,
41 },
45 42 }
46 43 }
47 44 }
@@ -51,12 +48,12 @@ fn icon_circle(call: &CallCard, own: bool) -> Div {
51 48 CallIcon::Missed => (theme::red().opacity(0.2), "call_missed", theme::red_soft()),
52 49 CallIcon::Call => (circle_fill(own), "call", theme::text()),
53 50 CallIcon::Video => (circle_fill(own), "videocam", theme::text()),
54 CallIcon::Record => (
51 CallIcon::Record | CallIcon::Saved => (
55 52 circle_fill(own),
56 "radio_button_checked",
53 "fluent_record",
57 54 theme::accent_text(),
58 55 ),
59 CallIcon::RecordStop => (circle_fill(own), "stop_circle", theme::text()),
56 CallIcon::RecordStop => (circle_fill(own), "fluent_record_stop", theme::text()),
60 57 };
61 58 h_flex()
62 59 .size(px(ICON_CIRCLE))
@@ -161,130 +158,6 @@ fn participant_stack(
161 158 )
162 159 }
163 160
164 fn recording_thumbnail(recording: &RecordingCard, directory: &Directory) -> AnyElement {
165 let image = recording
166 .thumbnail
167 .as_ref()
168 .and_then(|thumbnail| directory.image(&thumbnail.url));
169 match image {
170 Some(entry) => img(entry.path.clone())
171 .size_full()
172 .object_fit(ObjectFit::Cover)
173 .into_any_element(),
174 None => div()
175 .size_full()
176 .bg(theme::code_surface())
177 .into_any_element(),
178 }
179 }
180
181 fn recording_tile(
182 recording: &RecordingCard,
183 index: usize,
184 directory: &Directory,
185 open_recording: RowAction,
186 ) -> Stateful<Div> {
187 div()
188 .id(ElementId::Name(format!("call-recording-{index}").into()))
189 .relative()
190 .w(px(TILE_WIDTH))
191 .h(px(TILE_HEIGHT))
192 .flex_none()
193 .rounded(px(TILE_RADIUS))
194 .overflow_hidden()
195 .cursor_pointer()
196 .hover(|tile| tile.opacity(0.92))
197 .child(recording_thumbnail(recording, directory))
198 .child(
199 h_flex()
200 .absolute()
201 .inset_0()
202 .items_center()
203 .justify_center()
204 .child(
205 h_flex()
206 .size(px(PLAY_CIRCLE))
207 .items_center()
208 .justify_center()
209 .rounded_full()
210 .bg(black().opacity(0.55))
211 .child(symbol("play_arrow", PLAY_GLYPH, theme::white())),
212 ),
213 )
214 .children(recording.duration.clone().map(|duration| {
215 div()
216 .absolute()
217 .bottom(px(DURATION_INSET))
218 .right(px(DURATION_INSET))
219 .px(px(6.))
220 .py(px(1.))
221 .rounded(px(4.))
222 .bg(black().opacity(0.65))
223 .text_size(px(DETAIL_SIZE))
224 .font_weight(FontWeight::SEMIBOLD)
225 .text_color(theme::white())
226 .child(duration)
227 }))
228 .when_some(open_recording, |tile, open| {
229 tile.on_click(move |_, _, cx| open(cx))
230 })
231 }
232
233 fn transcript_chip(index: usize, open_transcript: RowAction) -> Stateful<Div> {
234 h_flex()
235 .id(ElementId::Name(format!("call-transcript-{index}").into()))
236 .h(px(CHIP_HEIGHT))
237 .px(px(10.))
238 .gap(px(6.))
239 .flex_none()
240 .items_center()
241 .rounded(px(6.))
242 .border_1()
243 .border_color(theme::border())
244 .text_size(px(DETAIL_SIZE + 1.))
245 .font_weight(FontWeight::SEMIBOLD)
246 .text_color(theme::text())
247 .cursor_pointer()
248 .hover(|chip| chip.bg(theme::popup_hover()))
249 .child(symbol("description", 15., theme::accent_text()))
250 .child("Transcript")
251 .when_some(open_transcript, |chip, open| {
252 chip.on_click(move |_, _, cx| open(cx))
253 })
254 }
255
256 fn recording_block(
257 recording: &RecordingCard,
258 index: usize,
259 directory: &Directory,
260 open_recording: RowAction,
261 open_transcript: RowAction,
262 ) -> Div {
263 v_flex()
264 .pt(px(4.))
265 .gap(px(8.))
266 .child(recording_tile(recording, index, directory, open_recording))
267 .child(
268 h_flex()
269 .w(px(TILE_WIDTH))
270 .gap(px(8.))
271 .items_center()
272 .child(
273 div()
274 .flex_1()
275 .min_w_0()
276 .truncate()
277 .text_size(px(TITLE_SIZE))
278 .font_weight(FontWeight::SEMIBOLD)
279 .text_color(theme::text())
280 .child(recording.title.clone()),
281 )
282 .when(recording.transcript, |line| {
283 line.child(transcript_chip(index, open_transcript))
284 }),
285 )
286 }
287
288 161 fn card(
289 162 call: &CallCard,
290 163 index: usize,
@@ -292,12 +165,7 @@ fn card(
292 165 actions: CallActions,
293 166 directory: &Directory,
294 167 ) -> Div {
295 let CallActions {
296 call_back,
297 join,
298 open_recording,
299 open_transcript,
300 } = actions;
168 let CallActions { call_back, join, .. } = actions;
301 169 let show_join = call.started && join.is_some();
302 170 let summary = h_flex()
303 171 .gap(px(8.))
@@ -341,9 +209,6 @@ fn card(
341 209 theme::bubble_other()
342 210 })
343 211 .child(summary)
344 .children(call.recording.as_ref().map(|recording| {
345 recording_block(recording, index, directory, open_recording, open_transcript)
346 }))
347 212 }
348 213
349 214 pub(super) fn post_call_card(
@@ -362,6 +227,9 @@ pub(super) fn call_card_row(
362 227 directory: &Directory,
363 228 actions: CallActions,
364 229 ) -> AnyElement {
230 if let Some(notice) = &call.notice {
231 return notice_row(row, call, notice, index, directory, actions.recap);
232 }
365 233 let own = row.own;
366 234 let body = if own {
367 235 h_flex()
@@ -3,11 +3,12 @@ use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::*;
3use gpui_kit::*;
4
4
5use super::avatar::person_avatar;
5use super::avatar::person_avatar;
6use super::call_notice::{RecapActions, notice_row};
6use super::message_row::{AVATAR_GAP, AVATAR_SIZE, RowAction, day_separator, new_marker};
7use super::message_row::{AVATAR_GAP, AVATAR_SIZE, RowAction, day_separator, new_marker};
7use super::profile_card::opens_profile;
8use super::profile_card::opens_profile;
8use super::widgets::symbol;
9use super::widgets::symbol;
9use crate::data::Directory;
10use crate::data::Directory;
10use crate::rows::{CallCard, CallIcon, CallParticipant, MessageRow, RecordingCard};
11use crate::rows::{CallCard, CallIcon, CallParticipant, MessageRow};
11use crate::theme;
12use crate::theme;
12
13
13const SERIES_START_GAP: f32 = 8.;
14const SERIES_START_GAP: f32 = 8.;
@@ -20,19 +21,11 @@ const DETAIL_SIZE: f32 = 11.;
20const JOIN_HEIGHT: f32 = 24.;
21const JOIN_HEIGHT: f32 = 24.;
21const PARTICIPANT_AVATAR: f32 = 20.;
22const PARTICIPANT_AVATAR: f32 = 20.;
22const PARTICIPANT_GAP: f32 = 2.;
23const PARTICIPANT_GAP: f32 = 2.;
23const TILE_WIDTH: f32 = 288.;
24const TILE_HEIGHT: f32 = 162.;
25const TILE_RADIUS: f32 = 8.;
26const PLAY_CIRCLE: f32 = 40.;
27const PLAY_GLYPH: f32 = 24.;
28const DURATION_INSET: f32 = 6.;
29const CHIP_HEIGHT: f32 = 26.;
30
24
31pub struct CallActions {
25pub struct CallActions {
32 pub call_back: RowAction,
26 pub call_back: RowAction,
33 pub join: RowAction,
27 pub join: RowAction,
34 pub open_recording: RowAction,
28 pub recap: RecapActions,
35 pub open_transcript: RowAction,
36}
29}
37
30
38impl CallActions {
31impl CallActions {
@@ -40,8 +33,12 @@ impl CallActions {
40 CallActions {
33 CallActions {
41 call_back: None,
34 call_back: None,
42 join: None,
35 join: None,
43 open_recording: None,
36 recap: RecapActions {
44 open_transcript: None,
37 view_recap: None,
38 open_recording: None,
39 transcript: None,
40 share: None,
41 },
45 }
42 }
46 }
43 }
47}
44}
@@ -51,12 +48,12 @@ fn icon_circle(call: &CallCard, own: bool) -> Div {
51 CallIcon::Missed => (theme::red().opacity(0.2), "call_missed", theme::red_soft()),
48 CallIcon::Missed => (theme::red().opacity(0.2), "call_missed", theme::red_soft()),
52 CallIcon::Call => (circle_fill(own), "call", theme::text()),
49 CallIcon::Call => (circle_fill(own), "call", theme::text()),
53 CallIcon::Video => (circle_fill(own), "videocam", theme::text()),
50 CallIcon::Video => (circle_fill(own), "videocam", theme::text()),
54 CallIcon::Record => (
51 CallIcon::Record | CallIcon::Saved => (
55 circle_fill(own),
52 circle_fill(own),
56 "radio_button_checked",
53 "fluent_record",
57 theme::accent_text(),
54 theme::accent_text(),
58 ),
55 ),
59 CallIcon::RecordStop => (circle_fill(own), "stop_circle", theme::text()),
56 CallIcon::RecordStop => (circle_fill(own), "fluent_record_stop", theme::text()),
60 };
57 };
61 h_flex()
58 h_flex()
62 .size(px(ICON_CIRCLE))
59 .size(px(ICON_CIRCLE))
@@ -161,130 +158,6 @@ fn participant_stack(
161 )
158 )
162}
159}
163
160
164fn recording_thumbnail(recording: &RecordingCard, directory: &Directory) -> AnyElement {
165 let image = recording
166 .thumbnail
167 .as_ref()
168 .and_then(|thumbnail| directory.image(&thumbnail.url));
169 match image {
170 Some(entry) => img(entry.path.clone())
171 .size_full()
172 .object_fit(ObjectFit::Cover)
173 .into_any_element(),
174 None => div()
175 .size_full()
176 .bg(theme::code_surface())
177 .into_any_element(),
178 }
179}
180
181fn recording_tile(
182 recording: &RecordingCard,
183 index: usize,
184 directory: &Directory,
185 open_recording: RowAction,
186) -> Stateful<Div> {
187 div()
188 .id(ElementId::Name(format!("call-recording-{index}").into()))
189 .relative()
190 .w(px(TILE_WIDTH))
191 .h(px(TILE_HEIGHT))
192 .flex_none()
193 .rounded(px(TILE_RADIUS))
194 .overflow_hidden()
195 .cursor_pointer()
196 .hover(|tile| tile.opacity(0.92))
197 .child(recording_thumbnail(recording, directory))
198 .child(
199 h_flex()
200 .absolute()
201 .inset_0()
202 .items_center()
203 .justify_center()
204 .child(
205 h_flex()
206 .size(px(PLAY_CIRCLE))
207 .items_center()
208 .justify_center()
209 .rounded_full()
210 .bg(black().opacity(0.55))
211 .child(symbol("play_arrow", PLAY_GLYPH, theme::white())),
212 ),
213 )
214 .children(recording.duration.clone().map(|duration| {
215 div()
216 .absolute()
217 .bottom(px(DURATION_INSET))
218 .right(px(DURATION_INSET))
219 .px(px(6.))
220 .py(px(1.))
221 .rounded(px(4.))
222 .bg(black().opacity(0.65))
223 .text_size(px(DETAIL_SIZE))
224 .font_weight(FontWeight::SEMIBOLD)
225 .text_color(theme::white())
226 .child(duration)
227 }))
228 .when_some(open_recording, |tile, open| {
229 tile.on_click(move |_, _, cx| open(cx))
230 })
231}
232
233fn transcript_chip(index: usize, open_transcript: RowAction) -> Stateful<Div> {
234 h_flex()
235 .id(ElementId::Name(format!("call-transcript-{index}").into()))
236 .h(px(CHIP_HEIGHT))
237 .px(px(10.))
238 .gap(px(6.))
239 .flex_none()
240 .items_center()
241 .rounded(px(6.))
242 .border_1()
243 .border_color(theme::border())
244 .text_size(px(DETAIL_SIZE + 1.))
245 .font_weight(FontWeight::SEMIBOLD)
246 .text_color(theme::text())
247 .cursor_pointer()
248 .hover(|chip| chip.bg(theme::popup_hover()))
249 .child(symbol("description", 15., theme::accent_text()))
250 .child("Transcript")
251 .when_some(open_transcript, |chip, open| {
252 chip.on_click(move |_, _, cx| open(cx))
253 })
254}
255
256fn recording_block(
257 recording: &RecordingCard,
258 index: usize,
259 directory: &Directory,
260 open_recording: RowAction,
261 open_transcript: RowAction,
262) -> Div {
263 v_flex()
264 .pt(px(4.))
265 .gap(px(8.))
266 .child(recording_tile(recording, index, directory, open_recording))
267 .child(
268 h_flex()
269 .w(px(TILE_WIDTH))
270 .gap(px(8.))
271 .items_center()
272 .child(
273 div()
274 .flex_1()
275 .min_w_0()
276 .truncate()
277 .text_size(px(TITLE_SIZE))
278 .font_weight(FontWeight::SEMIBOLD)
279 .text_color(theme::text())
280 .child(recording.title.clone()),
281 )
282 .when(recording.transcript, |line| {
283 line.child(transcript_chip(index, open_transcript))
284 }),
285 )
286}
287
288fn card(
161fn card(
289 call: &CallCard,
162 call: &CallCard,
290 index: usize,
163 index: usize,
@@ -292,12 +165,7 @@ fn card(
292 actions: CallActions,
165 actions: CallActions,
293 directory: &Directory,
166 directory: &Directory,
294) -> Div {
167) -> Div {
295 let CallActions {
168 let CallActions { call_back, join, .. } = actions;
296 call_back,
297 join,
298 open_recording,
299 open_transcript,
300 } = actions;
301 let show_join = call.started && join.is_some();
169 let show_join = call.started && join.is_some();
302 let summary = h_flex()
170 let summary = h_flex()
303 .gap(px(8.))
171 .gap(px(8.))
@@ -341,9 +209,6 @@ fn card(
341 theme::bubble_other()
209 theme::bubble_other()
342 })
210 })
343 .child(summary)
211 .child(summary)
344 .children(call.recording.as_ref().map(|recording| {
345 recording_block(recording, index, directory, open_recording, open_transcript)
346 }))
347}
212}
348
213
349pub(super) fn post_call_card(
214pub(super) fn post_call_card(
@@ -362,6 +227,9 @@ pub(super) fn call_card_row(
362 directory: &Directory,
227 directory: &Directory,
363 actions: CallActions,
228 actions: CallActions,
364) -> AnyElement {
229) -> AnyElement {
230 if let Some(notice) = &call.notice {
231 return notice_row(row, call, notice, index, directory, actions.recap);
232 }
365 let own = row.own;
233 let own = row.own;
366 let body = if own {
234 let body = if own {
367 h_flex()
235 h_flex()
crates/app/src/views/call_notice.rs added +379 −0
@@ -0,0 +1,379 @@
1 use gpui_kit::component::{h_flex, v_flex};
2 use gpui_kit::prelude::FluentBuilder as _;
3 use gpui_kit::*;
4
5 use super::message_row::{AVATAR_GAP, AVATAR_SIZE, RowAction, day_separator, new_marker};
6 use super::widgets::symbol;
7 use crate::data::Directory;
8 use crate::rows::{CallCard, CallIcon, CallNotice, MessageRow, RecapCard, RecordingCard};
9 use crate::theme;
10
11 const ROW_TOP: f32 = 8.;
12 const LINE_HEIGHT: f32 = 20.;
13 const TEXT_SIZE: f32 = 12.;
14 const ICON_SIZE: f32 = 20.;
15 const STAMP_GAP: &str = "\u{2003}";
16 const CARD_TOP: f32 = 14.;
17 const CARD_MAX_WIDTH: f32 = 646.;
18 const CARD_RADIUS: f32 = 8.;
19 const CARD_PADDING_X: f32 = 20.;
20 const CARD_PADDING_TOP: f32 = 14.;
21 const TITLE_SIZE: f32 = 16.;
22 const BUTTON_HEIGHT: f32 = 32.;
23 const BUTTON_RADIUS: f32 = 4.;
24 const VIEW_RECAP_WIDTH: f32 = 108.;
25 const VIEW_RECAP_SIZE: f32 = 14.;
26 const DIVIDER_GAP: f32 = 12.;
27 const CONTENT_GAP_TOP: f32 = 12.;
28 const CONTENT_GAP_BOTTOM: f32 = 16.;
29 const CHIP_MIN_WIDTH: f32 = 96.;
30 const CHIP_ICON_GAP: f32 = 6.;
31 const THUMB_WIDTH: f32 = 108.;
32 const THUMB_HEIGHT: f32 = 60.;
33 const THUMB_RADIUS: f32 = 6.;
34 const BADGE_INSET_RIGHT: f32 = 6.;
35 const BADGE_INSET_BOTTOM: f32 = 8.;
36 const EXPIRY_SIZE: f32 = 10.;
37 const EXPIRY_LINE: f32 = 24.;
38 const EXPIRY_ICON_GAP: f32 = 4.;
39 const CONTENT_LABEL: &str = "Content";
40
41 pub struct RecapActions {
42 pub view_recap: RowAction,
43 pub open_recording: RowAction,
44 pub transcript: RowAction,
45 pub share: RowAction,
46 }
47
48 fn notice_icon(icon: CallIcon) -> (&'static str, Hsla) {
49 match icon {
50 CallIcon::Record => ("fluent_record", theme::accent_text()),
51 CallIcon::RecordStop => ("fluent_record_stop", theme::text_muted()),
52 CallIcon::Saved => ("fluent_cloud_arrow_up", theme::text_muted()),
53 CallIcon::Video | CallIcon::Call | CallIcon::Missed => {
54 ("fluent_video", theme::text_muted())
55 }
56 }
57 }
58
59 fn notice_text(notice: &CallNotice) -> StyledText {
60 let mut text = format!("{}{STAMP_GAP}{}", notice.stamp, notice.text);
61 let mut highlights = Vec::new();
62 if let Some(emphasis) = &notice.emphasis {
63 text.push('\u{a0}');
64 let start = text.len();
65 text.push_str(emphasis);
66 highlights.push((
67 start..text.len(),
68 HighlightStyle {
69 font_weight: Some(FontWeight::BOLD),
70 ..HighlightStyle::default()
71 },
72 ));
73 }
74 StyledText::new(text).with_highlights(highlights)
75 }
76
77 fn plain_button(id: String, action: RowAction) -> Stateful<Div> {
78 h_flex()
79 .id(ElementId::Name(id.into()))
80 .h(px(BUTTON_HEIGHT))
81 .flex_none()
82 .items_center()
83 .justify_center()
84 .rounded(px(BUTTON_RADIUS))
85 .cursor_pointer()
86 .when_some(action, |button, action| {
87 button.on_click(move |_, _, cx| action(cx))
88 })
89 }
90
91 fn recap_header(recap: &RecapCard, index: usize, open: RowAction, share: RowAction) -> Div {
92 h_flex()
93 .w_full()
94 .items_start()
95 .gap(px(4.))
96 .child(
97 v_flex()
98 .flex_1()
99 .min_w_0()
100 .line_height(px(LINE_HEIGHT))
101 .child(
102 div()
103 .truncate()
104 .text_size(px(TITLE_SIZE))
105 .font_weight(FontWeight::SEMIBOLD)
106 .text_color(theme::text())
107 .child(recap.title.clone()),
108 )
109 .child(
110 div()
111 .truncate()
112 .text_size(px(TEXT_SIZE))
113 .text_color(theme::text_muted())
114 .child(recap.date_line.clone()),
115 ),
116 )
117 .child(
118 h_flex()
119 .pt(px(2.))
120 .gap(px(4.))
121 .child(
122 plain_button(format!("recap-share-{index}"), share)
123 .w(px(BUTTON_HEIGHT))
124 .hover(|button| button.bg(theme::popup_hover()))
125 .child(symbol("fluent_share", ICON_SIZE, theme::text_soft())),
126 )
127 .child(
128 plain_button(format!("recap-view-{index}"), open)
129 .w(px(VIEW_RECAP_WIDTH))
130 .bg(theme::accent())
131 .hover(|button| button.opacity(0.85))
132 .text_size(px(VIEW_RECAP_SIZE))
133 .font_weight(FontWeight::SEMIBOLD)
134 .text_color(theme::white())
135 .child("View recap"),
136 ),
137 )
138 }
139
140 fn divider() -> Div {
141 div()
142 .w_full()
143 .py(px(DIVIDER_GAP))
144 .child(div().w_full().h(px(1.)).bg(theme::border_strong()))
145 }
146
147 fn transcript_chip(index: usize, transcript: RowAction) -> Stateful<Div> {
148 plain_button(format!("recap-transcript-{index}"), transcript)
149 .min_w(px(CHIP_MIN_WIDTH))
150 .px(px(8.))
151 .gap(px(CHIP_ICON_GAP))
152 .border_1()
153 .border_color(theme::border_strong())
154 .bg(theme::bubble_other())
155 .hover(|chip| chip.bg(theme::popup_hover()))
156 .text_size(px(TEXT_SIZE))
157 .font_weight(FontWeight::SEMIBOLD)
158 .text_color(theme::text())
159 .child(symbol(
160 "fluent_document_text",
161 ICON_SIZE,
162 theme::accent_text(),
163 ))
164 .child("Transcript")
165 }
166
167 fn thumbnail_image(recording: &RecordingCard, directory: &Directory) -> AnyElement {
168 let image = recording
169 .thumbnail
170 .as_ref()
171 .and_then(|thumbnail| directory.image(&thumbnail.url));
172 match image {
173 Some(entry) => img(entry.path.clone())
174 .size_full()
175 .object_fit(ObjectFit::Cover)
176 .into_any_element(),
177 None => h_flex()
178 .size_full()
179 .items_center()
180 .justify_center()
181 .bg(theme::code_surface())
182 .when(recording.duration.is_none(), |tile| {
183 tile.child(symbol("fluent_video", ICON_SIZE, theme::text()))
184 })
185 .into_any_element(),
186 }
187 }
188
189 fn recording_thumbnail(
190 recording: &RecordingCard,
191 index: usize,
192 directory: &Directory,
193 open: RowAction,
194 ) -> Div {
195 v_flex()
196 .w(px(THUMB_WIDTH))
197 .flex_none()
198 .child(
199 div()
200 .id(ElementId::Name(format!("recap-recording-{index}").into()))
201 .relative()
202 .w(px(THUMB_WIDTH))
203 .h(px(THUMB_HEIGHT))
204 .rounded(px(THUMB_RADIUS))
205 .overflow_hidden()
206 .cursor_pointer()
207 .hover(|tile| tile.opacity(0.92))
208 .child(thumbnail_image(recording, directory))
209 .children(recording.duration.clone().map(|duration| {
210 div()
211 .absolute()
212 .right(px(BADGE_INSET_RIGHT))
213 .bottom(px(BADGE_INSET_BOTTOM))
214 .px(px(6.))
215 .py(px(1.))
216 .rounded(px(2.))
217 .bg(black().opacity(0.5))
218 .text_size(px(TEXT_SIZE))
219 .line_height(px(16.))
220 .text_color(theme::white())
221 .child(duration)
222 }))
223 .when_some(open, |tile, open| tile.on_click(move |_, _, cx| open(cx))),
224 )
225 .children(recording.expires_in_days.map(|days| {
226 h_flex()
227 .h(px(EXPIRY_LINE))
228 .justify_center()
229 .items_center()
230 .gap(px(EXPIRY_ICON_GAP))
231 .text_size(px(EXPIRY_SIZE))
232 .text_color(theme::text_muted())
233 .child(symbol("fluent_clock", EXPIRY_SIZE, theme::text_muted()))
234 .child(if days == 1 {
235 "Expires in 1 day".to_owned()
236 } else {
237 format!("Expires in {days} days")
238 })
239 }))
240 }
241
242 fn recap_card(
243 recap: &RecapCard,
244 index: usize,
245 directory: &Directory,
246 actions: RecapActions,
247 ) -> Div {
248 let RecapActions {
249 view_recap,
250 open_recording,
251 transcript,
252 share,
253 } = actions;
254 v_flex()
255 .mt(px(CARD_TOP))
256 .w_full()
257 .max_w(px(CARD_MAX_WIDTH))
258 .pt(px(CARD_PADDING_TOP))
259 .px(px(CARD_PADDING_X))
260 .rounded(px(CARD_RADIUS))
261 .bg(theme::bubble_other())
262 .shadow(card_shadow())
263 .child(recap_header(recap, index, view_recap, share))
264 .child(divider())
265 .child(
266 h_flex()
267 .w_full()
268 .items_start()
269 .child(
270 v_flex()
271 .flex_1()
272 .min_w_0()
273 .child(
274 div()
275 .text_size(px(TEXT_SIZE))
276 .line_height(px(16.))
277 .font_weight(FontWeight::SEMIBOLD)
278 .text_color(theme::text_soft())
279 .child(CONTENT_LABEL),
280 )
281 .child(
282 h_flex()
283 .mt(px(CONTENT_GAP_TOP))
284 .mb(px(CONTENT_GAP_BOTTOM))
285 .when(recap.recording.transcript, |chips| {
286 chips.child(transcript_chip(index, transcript))
287 }),
288 ),
289 )
290 .child(recording_thumbnail(
291 &recap.recording,
292 index,
293 directory,
294 open_recording,
295 )),
296 )
297 }
298
299 fn card_shadow() -> Vec<BoxShadow> {
300 vec![
301 BoxShadow {
302 color: hsla(0., 0., 0., 0.24),
303 offset: point(px(0.), px(0.)),
304 blur_radius: px(1.),
305 spread_radius: px(0.),
306 inset: false,
307 },
308 BoxShadow {
309 color: hsla(0., 0., 0., 0.28),
310 offset: point(px(0.), px(2.)),
311 blur_radius: px(2.),
312 spread_radius: px(0.),
313 inset: false,
314 },
315 ]
316 }
317
318 pub(super) fn notice_line(
319 call: &CallCard,
320 notice: &CallNotice,
321 index: usize,
322 directory: &Directory,
323 actions: RecapActions,
324 ) -> Div {
325 let (glyph, tint) = notice_icon(call.icon);
326 h_flex()
327 .w_full()
328 .pt(px(ROW_TOP))
329 .items_start()
330 .gap(px(AVATAR_GAP))
331 .child(
332 h_flex()
333 .w(px(AVATAR_SIZE))
334 .h(px(LINE_HEIGHT))
335 .flex_none()
336 .justify_center()
337 .items_center()
338 .child(symbol(glyph, ICON_SIZE, tint)),
339 )
340 .child(
341 v_flex()
342 .flex_1()
343 .min_w_0()
344 .child(
345 div()
346 .text_size(px(TEXT_SIZE))
347 .line_height(px(LINE_HEIGHT))
348 .text_color(theme::text_muted())
349 .child(notice_text(notice)),
350 )
351 .children(
352 call.recap
353 .as_ref()
354 .map(|recap| recap_card(recap, index, directory, actions)),
355 ),
356 )
357 }
358
359 pub(super) fn notice_row(
360 row: &MessageRow,
361 call: &CallCard,
362 notice: &CallNotice,
363 index: usize,
364 directory: &Directory,
365 actions: RecapActions,
366 ) -> AnyElement {
367 v_flex()
368 .w_full()
369 .px(px(20.))
370 .children(row.day_header.as_deref().map(day_separator))
371 .when(row.new_marker, |column| column.child(new_marker()))
372 .child(
373 div()
374 .id(ElementId::Name(format!("row-{index}").into()))
375 .w_full()
376 .child(notice_line(call, notice, index, directory, actions)),
377 )
378 .into_any_element()
379 }
@@ -0,0 +1,379 @@
1use gpui_kit::component::{h_flex, v_flex};
2use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::*;
4
5use super::message_row::{AVATAR_GAP, AVATAR_SIZE, RowAction, day_separator, new_marker};
6use super::widgets::symbol;
7use crate::data::Directory;
8use crate::rows::{CallCard, CallIcon, CallNotice, MessageRow, RecapCard, RecordingCard};
9use crate::theme;
10
11const ROW_TOP: f32 = 8.;
12const LINE_HEIGHT: f32 = 20.;
13const TEXT_SIZE: f32 = 12.;
14const ICON_SIZE: f32 = 20.;
15const STAMP_GAP: &str = "\u{2003}";
16const CARD_TOP: f32 = 14.;
17const CARD_MAX_WIDTH: f32 = 646.;
18const CARD_RADIUS: f32 = 8.;
19const CARD_PADDING_X: f32 = 20.;
20const CARD_PADDING_TOP: f32 = 14.;
21const TITLE_SIZE: f32 = 16.;
22const BUTTON_HEIGHT: f32 = 32.;
23const BUTTON_RADIUS: f32 = 4.;
24const VIEW_RECAP_WIDTH: f32 = 108.;
25const VIEW_RECAP_SIZE: f32 = 14.;
26const DIVIDER_GAP: f32 = 12.;
27const CONTENT_GAP_TOP: f32 = 12.;
28const CONTENT_GAP_BOTTOM: f32 = 16.;
29const CHIP_MIN_WIDTH: f32 = 96.;
30const CHIP_ICON_GAP: f32 = 6.;
31const THUMB_WIDTH: f32 = 108.;
32const THUMB_HEIGHT: f32 = 60.;
33const THUMB_RADIUS: f32 = 6.;
34const BADGE_INSET_RIGHT: f32 = 6.;
35const BADGE_INSET_BOTTOM: f32 = 8.;
36const EXPIRY_SIZE: f32 = 10.;
37const EXPIRY_LINE: f32 = 24.;
38const EXPIRY_ICON_GAP: f32 = 4.;
39const CONTENT_LABEL: &str = "Content";
40
41pub struct RecapActions {
42 pub view_recap: RowAction,
43 pub open_recording: RowAction,
44 pub transcript: RowAction,
45 pub share: RowAction,
46}
47
48fn notice_icon(icon: CallIcon) -> (&'static str, Hsla) {
49 match icon {
50 CallIcon::Record => ("fluent_record", theme::accent_text()),
51 CallIcon::RecordStop => ("fluent_record_stop", theme::text_muted()),
52 CallIcon::Saved => ("fluent_cloud_arrow_up", theme::text_muted()),
53 CallIcon::Video | CallIcon::Call | CallIcon::Missed => {
54 ("fluent_video", theme::text_muted())
55 }
56 }
57}
58
59fn notice_text(notice: &CallNotice) -> StyledText {
60 let mut text = format!("{}{STAMP_GAP}{}", notice.stamp, notice.text);
61 let mut highlights = Vec::new();
62 if let Some(emphasis) = &notice.emphasis {
63 text.push('\u{a0}');
64 let start = text.len();
65 text.push_str(emphasis);
66 highlights.push((
67 start..text.len(),
68 HighlightStyle {
69 font_weight: Some(FontWeight::BOLD),
70 ..HighlightStyle::default()
71 },
72 ));
73 }
74 StyledText::new(text).with_highlights(highlights)
75}
76
77fn plain_button(id: String, action: RowAction) -> Stateful<Div> {
78 h_flex()
79 .id(ElementId::Name(id.into()))
80 .h(px(BUTTON_HEIGHT))
81 .flex_none()
82 .items_center()
83 .justify_center()
84 .rounded(px(BUTTON_RADIUS))
85 .cursor_pointer()
86 .when_some(action, |button, action| {
87 button.on_click(move |_, _, cx| action(cx))
88 })
89}
90
91fn recap_header(recap: &RecapCard, index: usize, open: RowAction, share: RowAction) -> Div {
92 h_flex()
93 .w_full()
94 .items_start()
95 .gap(px(4.))
96 .child(
97 v_flex()
98 .flex_1()
99 .min_w_0()
100 .line_height(px(LINE_HEIGHT))
101 .child(
102 div()
103 .truncate()
104 .text_size(px(TITLE_SIZE))
105 .font_weight(FontWeight::SEMIBOLD)
106 .text_color(theme::text())
107 .child(recap.title.clone()),
108 )
109 .child(
110 div()
111 .truncate()
112 .text_size(px(TEXT_SIZE))
113 .text_color(theme::text_muted())
114 .child(recap.date_line.clone()),
115 ),
116 )
117 .child(
118 h_flex()
119 .pt(px(2.))
120 .gap(px(4.))
121 .child(
122 plain_button(format!("recap-share-{index}"), share)
123 .w(px(BUTTON_HEIGHT))
124 .hover(|button| button.bg(theme::popup_hover()))
125 .child(symbol("fluent_share", ICON_SIZE, theme::text_soft())),
126 )
127 .child(
128 plain_button(format!("recap-view-{index}"), open)
129 .w(px(VIEW_RECAP_WIDTH))
130 .bg(theme::accent())
131 .hover(|button| button.opacity(0.85))
132 .text_size(px(VIEW_RECAP_SIZE))
133 .font_weight(FontWeight::SEMIBOLD)
134 .text_color(theme::white())
135 .child("View recap"),
136 ),
137 )
138}
139
140fn divider() -> Div {
141 div()
142 .w_full()
143 .py(px(DIVIDER_GAP))
144 .child(div().w_full().h(px(1.)).bg(theme::border_strong()))
145}
146
147fn transcript_chip(index: usize, transcript: RowAction) -> Stateful<Div> {
148 plain_button(format!("recap-transcript-{index}"), transcript)
149 .min_w(px(CHIP_MIN_WIDTH))
150 .px(px(8.))
151 .gap(px(CHIP_ICON_GAP))
152 .border_1()
153 .border_color(theme::border_strong())
154 .bg(theme::bubble_other())
155 .hover(|chip| chip.bg(theme::popup_hover()))
156 .text_size(px(TEXT_SIZE))
157 .font_weight(FontWeight::SEMIBOLD)
158 .text_color(theme::text())
159 .child(symbol(
160 "fluent_document_text",
161 ICON_SIZE,
162 theme::accent_text(),
163 ))
164 .child("Transcript")
165}
166
167fn thumbnail_image(recording: &RecordingCard, directory: &Directory) -> AnyElement {
168 let image = recording
169 .thumbnail
170 .as_ref()
171 .and_then(|thumbnail| directory.image(&thumbnail.url));
172 match image {
173 Some(entry) => img(entry.path.clone())
174 .size_full()
175 .object_fit(ObjectFit::Cover)
176 .into_any_element(),
177 None => h_flex()
178 .size_full()
179 .items_center()
180 .justify_center()
181 .bg(theme::code_surface())
182 .when(recording.duration.is_none(), |tile| {
183 tile.child(symbol("fluent_video", ICON_SIZE, theme::text()))
184 })
185 .into_any_element(),
186 }
187}
188
189fn recording_thumbnail(
190 recording: &RecordingCard,
191 index: usize,
192 directory: &Directory,
193 open: RowAction,
194) -> Div {
195 v_flex()
196 .w(px(THUMB_WIDTH))
197 .flex_none()
198 .child(
199 div()
200 .id(ElementId::Name(format!("recap-recording-{index}").into()))
201 .relative()
202 .w(px(THUMB_WIDTH))
203 .h(px(THUMB_HEIGHT))
204 .rounded(px(THUMB_RADIUS))
205 .overflow_hidden()
206 .cursor_pointer()
207 .hover(|tile| tile.opacity(0.92))
208 .child(thumbnail_image(recording, directory))
209 .children(recording.duration.clone().map(|duration| {
210 div()
211 .absolute()
212 .right(px(BADGE_INSET_RIGHT))
213 .bottom(px(BADGE_INSET_BOTTOM))
214 .px(px(6.))
215 .py(px(1.))
216 .rounded(px(2.))
217 .bg(black().opacity(0.5))
218 .text_size(px(TEXT_SIZE))
219 .line_height(px(16.))
220 .text_color(theme::white())
221 .child(duration)
222 }))
223 .when_some(open, |tile, open| tile.on_click(move |_, _, cx| open(cx))),
224 )
225 .children(recording.expires_in_days.map(|days| {
226 h_flex()
227 .h(px(EXPIRY_LINE))
228 .justify_center()
229 .items_center()
230 .gap(px(EXPIRY_ICON_GAP))
231 .text_size(px(EXPIRY_SIZE))
232 .text_color(theme::text_muted())
233 .child(symbol("fluent_clock", EXPIRY_SIZE, theme::text_muted()))
234 .child(if days == 1 {
235 "Expires in 1 day".to_owned()
236 } else {
237 format!("Expires in {days} days")
238 })
239 }))
240}
241
242fn recap_card(
243 recap: &RecapCard,
244 index: usize,
245 directory: &Directory,
246 actions: RecapActions,
247) -> Div {
248 let RecapActions {
249 view_recap,
250 open_recording,
251 transcript,
252 share,
253 } = actions;
254 v_flex()
255 .mt(px(CARD_TOP))
256 .w_full()
257 .max_w(px(CARD_MAX_WIDTH))
258 .pt(px(CARD_PADDING_TOP))
259 .px(px(CARD_PADDING_X))
260 .rounded(px(CARD_RADIUS))
261 .bg(theme::bubble_other())
262 .shadow(card_shadow())
263 .child(recap_header(recap, index, view_recap, share))
264 .child(divider())
265 .child(
266 h_flex()
267 .w_full()
268 .items_start()
269 .child(
270 v_flex()
271 .flex_1()
272 .min_w_0()
273 .child(
274 div()
275 .text_size(px(TEXT_SIZE))
276 .line_height(px(16.))
277 .font_weight(FontWeight::SEMIBOLD)
278 .text_color(theme::text_soft())
279 .child(CONTENT_LABEL),
280 )
281 .child(
282 h_flex()
283 .mt(px(CONTENT_GAP_TOP))
284 .mb(px(CONTENT_GAP_BOTTOM))
285 .when(recap.recording.transcript, |chips| {
286 chips.child(transcript_chip(index, transcript))
287 }),
288 ),
289 )
290 .child(recording_thumbnail(
291 &recap.recording,
292 index,
293 directory,
294 open_recording,
295 )),
296 )
297}
298
299fn card_shadow() -> Vec<BoxShadow> {
300 vec![
301 BoxShadow {
302 color: hsla(0., 0., 0., 0.24),
303 offset: point(px(0.), px(0.)),
304 blur_radius: px(1.),
305 spread_radius: px(0.),
306 inset: false,
307 },
308 BoxShadow {
309 color: hsla(0., 0., 0., 0.28),
310 offset: point(px(0.), px(2.)),
311 blur_radius: px(2.),
312 spread_radius: px(0.),
313 inset: false,
314 },
315 ]
316}
317
318pub(super) fn notice_line(
319 call: &CallCard,
320 notice: &CallNotice,
321 index: usize,
322 directory: &Directory,
323 actions: RecapActions,
324) -> Div {
325 let (glyph, tint) = notice_icon(call.icon);
326 h_flex()
327 .w_full()
328 .pt(px(ROW_TOP))
329 .items_start()
330 .gap(px(AVATAR_GAP))
331 .child(
332 h_flex()
333 .w(px(AVATAR_SIZE))
334 .h(px(LINE_HEIGHT))
335 .flex_none()
336 .justify_center()
337 .items_center()
338 .child(symbol(glyph, ICON_SIZE, tint)),
339 )
340 .child(
341 v_flex()
342 .flex_1()
343 .min_w_0()
344 .child(
345 div()
346 .text_size(px(TEXT_SIZE))
347 .line_height(px(LINE_HEIGHT))
348 .text_color(theme::text_muted())
349 .child(notice_text(notice)),
350 )
351 .children(
352 call.recap
353 .as_ref()
354 .map(|recap| recap_card(recap, index, directory, actions)),
355 ),
356 )
357}
358
359pub(super) fn notice_row(
360 row: &MessageRow,
361 call: &CallCard,
362 notice: &CallNotice,
363 index: usize,
364 directory: &Directory,
365 actions: RecapActions,
366) -> AnyElement {
367 v_flex()
368 .w_full()
369 .px(px(20.))
370 .children(row.day_header.as_deref().map(day_separator))
371 .when(row.new_marker, |column| column.child(new_marker()))
372 .child(
373 div()
374 .id(ElementId::Name(format!("row-{index}").into()))
375 .w_full()
376 .child(notice_line(call, notice, index, directory, actions)),
377 )
378 .into_any_element()
379}
crates/app/src/views/conversation.rs +1 −0
@@ -1271,6 +1271,7 @@ impl ConversationView {
1271 1271 card_overrides,
1272 1272 translation,
1273 1273 skin_tone: teams_core::skin_tone(&app.store),
1274 meeting: self.meeting_info(app),
1274 1275 }
1275 1276 }
1276 1277
@@ -1271,6 +1271,7 @@ impl ConversationView {
1271 card_overrides,
1271 card_overrides,
1272 translation,
1272 translation,
1273 skin_tone: teams_core::skin_tone(&app.store),
1273 skin_tone: teams_core::skin_tone(&app.store),
1274 meeting: self.meeting_info(app),
1274 }
1275 }
1275 }
1276 }
1276
1277
crates/app/src/views/conversation/recap.rs +91 −3
@@ -5,6 +5,7 @@ use std::rc::Rc;
5 5
6 6 use chatsvc::{
7 7 Attendance, Occurrence, Recap, RecordingDetails, TranscriptFormat, TranscriptTurn,
8 days_until_expiry,
8 9 };
9 10 use chrono::Utc;
10 11 use gpui_kit::component::button::{Button, ButtonVariants as _};
@@ -14,7 +15,8 @@ use gpui_kit::component::WindowExt as _;
14 15 use gpui_kit::*;
15 16
16 17 use super::ConversationView;
17 use crate::app_state::Selection;
18 use crate::app_state::{AppState, Selection};
19 use crate::rows::{MeetingInfo, MeetingSlot};
18 20 use crate::channel_files::SharedContent;
19 21 use crate::demo_recap;
20 22 use crate::downloads::{self, DownloadState};
@@ -27,6 +29,7 @@ use crate::views::shared_tab::{SharedCommand, SharedRun};
27 29
28 30 const SEARCH_PLACEHOLDER: &str = "Search transcript";
29 31 const RECORDING_EXTENSION: &str = "mp4";
32 const EXPIRY_OCCURRENCES: usize = 3;
30 33
31 34 pub(super) fn search_input(
32 35 window: &mut Window,
@@ -44,6 +47,7 @@ pub(super) struct RecapState {
44 47 query: String,
45 48 downloads: HashMap<RecapDownload, DownloadState>,
46 49 generation: u64,
50 expiry_days: HashMap<String, i64>,
47 51 }
48 52
49 53 impl Default for RecapState {
@@ -57,6 +61,7 @@ impl Default for RecapState {
57 61 query: String::new(),
58 62 downloads: HashMap::new(),
59 63 generation: 0,
64 expiry_days: HashMap::new(),
60 65 }
61 66 }
62 67 }
@@ -119,7 +124,19 @@ impl ConversationView {
119 124 let state = self.app.read(cx);
120 125 let (demo, engine) = (state.mode.demo, state.engine.clone());
121 126 if demo {
122 self.recap.listing = Load::Ready(demo_recap::occurrences(&conversation_id, Utc::now()));
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);
123 140 return;
124 141 }
125 142 let Some(engine) = engine else {
@@ -142,7 +159,10 @@ impl ConversationView {
142 159 return;
143 160 }
144 161 this.recap.listing = match outcome {
145 Ok(occurrences) => Load::Ready(occurrences),
162 Ok(occurrences) => {
163 this.load_expiry(&occurrences, cx);
164 Load::Ready(occurrences)
165 }
146 166 Err(reason) => Load::Failed(reason),
147 167 };
148 168 if this.pane == ChannelPane::Recap {
@@ -155,6 +175,74 @@ impl ConversationView {
155 175 .detach();
156 176 }
157 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
158 246 /// Teams opens a meeting chat recording in the Recap tab at its occurrence and plays any
159 247 /// other recording (channel meetings) in the browser.
160 248 pub(super) fn open_recording(
@@ -5,6 +5,7 @@ use std::rc::Rc;
5
5
6use chatsvc::{
6use chatsvc::{
7 Attendance, Occurrence, Recap, RecordingDetails, TranscriptFormat, TranscriptTurn,
7 Attendance, Occurrence, Recap, RecordingDetails, TranscriptFormat, TranscriptTurn,
8 days_until_expiry,
8};
9};
9use chrono::Utc;
10use chrono::Utc;
10use gpui_kit::component::button::{Button, ButtonVariants as _};
11use gpui_kit::component::button::{Button, ButtonVariants as _};
@@ -14,7 +15,8 @@ use gpui_kit::component::WindowExt as _;
14use gpui_kit::*;
15use gpui_kit::*;
15
16
16use super::ConversationView;
17use super::ConversationView;
17use crate::app_state::Selection;
18use crate::app_state::{AppState, Selection};
19use crate::rows::{MeetingInfo, MeetingSlot};
18use crate::channel_files::SharedContent;
20use crate::channel_files::SharedContent;
19use crate::demo_recap;
21use crate::demo_recap;
20use crate::downloads::{self, DownloadState};
22use crate::downloads::{self, DownloadState};
@@ -27,6 +29,7 @@ use crate::views::shared_tab::{SharedCommand, SharedRun};
27
29
28const SEARCH_PLACEHOLDER: &str = "Search transcript";
30const SEARCH_PLACEHOLDER: &str = "Search transcript";
29const RECORDING_EXTENSION: &str = "mp4";
31const RECORDING_EXTENSION: &str = "mp4";
32const EXPIRY_OCCURRENCES: usize = 3;
30
33
31pub(super) fn search_input(
34pub(super) fn search_input(
32 window: &mut Window,
35 window: &mut Window,
@@ -44,6 +47,7 @@ pub(super) struct RecapState {
44 query: String,
47 query: String,
45 downloads: HashMap<RecapDownload, DownloadState>,
48 downloads: HashMap<RecapDownload, DownloadState>,
46 generation: u64,
49 generation: u64,
50 expiry_days: HashMap<String, i64>,
47}
51}
48
52
49impl Default for RecapState {
53impl Default for RecapState {
@@ -57,6 +61,7 @@ impl Default for RecapState {
57 query: String::new(),
61 query: String::new(),
58 downloads: HashMap::new(),
62 downloads: HashMap::new(),
59 generation: 0,
63 generation: 0,
64 expiry_days: HashMap::new(),
60 }
65 }
61 }
66 }
62}
67}
@@ -119,7 +124,19 @@ impl ConversationView {
119 let state = self.app.read(cx);
124 let state = self.app.read(cx);
120 let (demo, engine) = (state.mode.demo, state.engine.clone());
125 let (demo, engine) = (state.mode.demo, state.engine.clone());
121 if demo {
126 if demo {
122 self.recap.listing = Load::Ready(demo_recap::occurrences(&conversation_id, Utc::now()));
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);
123 return;
140 return;
124 }
141 }
125 let Some(engine) = engine else {
142 let Some(engine) = engine else {
@@ -142,7 +159,10 @@ impl ConversationView {
142 return;
159 return;
143 }
160 }
144 this.recap.listing = match outcome {
161 this.recap.listing = match outcome {
145 Ok(occurrences) => Load::Ready(occurrences),
162 Ok(occurrences) => {
163 this.load_expiry(&occurrences, cx);
164 Load::Ready(occurrences)
165 }
146 Err(reason) => Load::Failed(reason),
166 Err(reason) => Load::Failed(reason),
147 };
167 };
148 if this.pane == ChannelPane::Recap {
168 if this.pane == ChannelPane::Recap {
@@ -155,6 +175,74 @@ impl ConversationView {
155 .detach();
175 .detach();
156 }
176 }
157
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
158 /// Teams opens a meeting chat recording in the Recap tab at its occurrence and plays any
246 /// Teams opens a meeting chat recording in the Recap tab at its occurrence and plays any
159 /// other recording (channel meetings) in the browser.
247 /// other recording (channel meetings) in the browser.
160 pub(super) fn open_recording(
248 pub(super) fn open_recording(
crates/app/src/views/conversation/render_env.rs +12 −3
@@ -15,6 +15,7 @@ use crate::agent_api::agent_label;
15 15 use crate::agents::AgentRun;
16 16 use crate::app_state::AppState;
17 17 use crate::rows::{Delivery, MessageRow, PostRow, RecordingCard};
18 use crate::views::call_notice::RecapActions;
18 19 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
19 20 use crate::translation::TranslationLine;
20 21 use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
@@ -72,7 +73,7 @@ impl RenderEnv {
72 73 message
73 74 .call
74 75 .as_ref()
75 .and_then(|call| call.recording.as_ref()?.thumbnail.clone()),
76 .and_then(|call| call.recap.as_ref()?.recording.thumbnail.clone()),
76 77 )
77 78 .filter(|image| self.app.read(cx).directory.image(&image.url).is_none())
78 79 .collect();
@@ -340,11 +341,19 @@ impl RenderEnv {
340 341 .ok();
341 342 })
342 343 };
344 let recording = call.recap.as_ref().map(|recap| &recap.recording);
345 let share = recording.and_then(|recording| recording.url.clone()).map(|url| {
346 boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
347 });
343 348 CallActions {
344 349 call_back,
345 350 join,
346 open_recording: call.recording.as_ref().map(open),
347 open_transcript: call.recording.as_ref().map(open),
351 recap: RecapActions {
352 view_recap: recording.map(open),
353 open_recording: recording.map(open),
354 transcript: recording.map(open),
355 share,
356 },
348 357 }
349 358 }
350 359
@@ -15,6 +15,7 @@ use crate::agent_api::agent_label;
15use crate::agents::AgentRun;
15use crate::agents::AgentRun;
16use crate::app_state::AppState;
16use crate::app_state::AppState;
17use crate::rows::{Delivery, MessageRow, PostRow, RecordingCard};
17use crate::rows::{Delivery, MessageRow, PostRow, RecordingCard};
18use crate::views::call_notice::RecapActions;
18use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
19use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
19use crate::translation::TranslationLine;
20use crate::translation::TranslationLine;
20use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
21use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
@@ -72,7 +73,7 @@ impl RenderEnv {
72 message
73 message
73 .call
74 .call
74 .as_ref()
75 .as_ref()
75 .and_then(|call| call.recording.as_ref()?.thumbnail.clone()),
76 .and_then(|call| call.recap.as_ref()?.recording.thumbnail.clone()),
76 )
77 )
77 .filter(|image| self.app.read(cx).directory.image(&image.url).is_none())
78 .filter(|image| self.app.read(cx).directory.image(&image.url).is_none())
78 .collect();
79 .collect();
@@ -340,11 +341,19 @@ impl RenderEnv {
340 .ok();
341 .ok();
341 })
342 })
342 };
343 };
344 let recording = call.recap.as_ref().map(|recap| &recap.recording);
345 let share = recording.and_then(|recording| recording.url.clone()).map(|url| {
346 boxed(move |cx| cx.write_to_clipboard(ClipboardItem::new_string(url.clone())))
347 });
343 CallActions {
348 CallActions {
344 call_back,
349 call_back,
345 join,
350 join,
346 open_recording: call.recording.as_ref().map(open),
351 recap: RecapActions {
347 open_transcript: call.recording.as_ref().map(open),
352 view_recap: recording.map(open),
353 open_recording: recording.map(open),
354 transcript: recording.map(open),
355 share,
356 },
348 }
357 }
349 }
358 }
350
359
crates/app/src/views/mod.rs +1 −0
@@ -5,6 +5,7 @@ pub mod attachment_tray;
5 5 pub mod attachments;
6 6 pub mod avatar;
7 7 pub mod call_card;
8 pub mod call_notice;
8 9 pub mod call_control_fold;
9 10 pub mod call_end_view;
10 11 pub mod call_controls;
@@ -5,6 +5,7 @@ pub mod attachment_tray;
5pub mod attachments;
5pub mod attachments;
6pub mod avatar;
6pub mod avatar;
7pub mod call_card;
7pub mod call_card;
8pub mod call_notice;
8pub mod call_control_fold;
9pub mod call_control_fold;
9pub mod call_end_view;
10pub mod call_end_view;
10pub mod call_controls;
11pub mod call_controls;
crates/app/src/views/post_card.rs +13 −0
@@ -7,6 +7,7 @@ use super::adaptive_card::cards_view;
7 7 use super::attachments::{attachments_view, message_body};
8 8 use super::avatar::{bot_avatar, person_avatar};
9 9 use super::call_card::{CallActions, post_call_card};
10 use super::call_notice::notice_line;
10 11 use super::link_preview::{link_preview_card, meeting_join_chip};
11 12 use super::message_actions::message_toolbar;
12 13 use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
@@ -199,6 +200,18 @@ fn message_block(
199 200 Some(bot) => bot_avatar(bot, size),
200 201 None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),
201 202 };
203 if let (Role::Reply, Some(call)) = (role, &row.call)
204 && let Some(notice) = &call.notice
205 {
206 let recap = std::mem::replace(&mut actions.call, CallActions::none()).recap;
207 return div()
208 .id(ElementId::Name(format!("post-message-{index}").into()))
209 .w_full()
210 .px(px(CARD_PADDING))
211 .pb(px(CARD_PADDING))
212 .bg(theme::reply_surface())
213 .child(notice_line(call, notice, index, directory, recap));
214 }
202 215 let profile_user = row.sender_id.as_deref().filter(|_| actions.bot.is_none());
203 216 let content = match &row.call {
204 217 Some(call) => v_flex().child(post_call_card(
@@ -7,6 +7,7 @@ use super::adaptive_card::cards_view;
7use super::attachments::{attachments_view, message_body};
7use super::attachments::{attachments_view, message_body};
8use super::avatar::{bot_avatar, person_avatar};
8use super::avatar::{bot_avatar, person_avatar};
9use super::call_card::{CallActions, post_call_card};
9use super::call_card::{CallActions, post_call_card};
10use super::call_notice::notice_line;
10use super::link_preview::{link_preview_card, meeting_join_chip};
11use super::link_preview::{link_preview_card, meeting_join_chip};
11use super::message_actions::message_toolbar;
12use super::message_actions::message_toolbar;
12use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
13use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
@@ -199,6 +200,18 @@ fn message_block(
199 Some(bot) => bot_avatar(bot, size),
200 Some(bot) => bot_avatar(bot, size),
200 None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),
201 None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),
201 };
202 };
203 if let (Role::Reply, Some(call)) = (role, &row.call)
204 && let Some(notice) = &call.notice
205 {
206 let recap = std::mem::replace(&mut actions.call, CallActions::none()).recap;
207 return div()
208 .id(ElementId::Name(format!("post-message-{index}").into()))
209 .w_full()
210 .px(px(CARD_PADDING))
211 .pb(px(CARD_PADDING))
212 .bg(theme::reply_surface())
213 .child(notice_line(call, notice, index, directory, recap));
214 }
202 let profile_user = row.sender_id.as_deref().filter(|_| actions.bot.is_none());
215 let profile_user = row.sender_id.as_deref().filter(|_| actions.bot.is_none());
203 let content = match &row.call {
216 let content = match &row.call {
204 Some(call) => v_flex().child(post_call_card(
217 Some(call) => v_flex().child(post_call_card(
crates/app/src/views/shell.rs +2 −1
@@ -266,7 +266,8 @@ impl AppShell {
266 266 });
267 267 let focus_handle = cx.focus_handle();
268 268 window.focus(&focus_handle, cx);
269 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
269 let notifications =
270 cx.new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
270 271 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
271 272 let user_input = cx.global::<UserInputHandle>().0.clone();
272 273 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
@@ -266,7 +266,8 @@ impl AppShell {
266 });
266 });
267 let focus_handle = cx.focus_handle();
267 let focus_handle = cx.focus_handle();
268 window.focus(&focus_handle, cx);
268 window.focus(&focus_handle, cx);
269 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
269 let notifications =
270 cx.new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
270 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
271 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
271 let user_input = cx.global::<UserInputHandle>().0.clone();
272 let user_input = cx.global::<UserInputHandle>().0.clone();
272 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
273 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
crates/chatsvc/examples/calendar_probe.rs +12 −3
@@ -31,15 +31,24 @@ async fn main() {
31 31 );
32 32 println!(
33 33 "# with thread: {}",
34 events.iter().filter(|event| event.thread_id.is_some()).count()
34 events
35 .iter()
36 .filter(|event| event.thread_id.is_some())
37 .count()
35 38 );
36 39 println!(
37 40 "# with organizer name: {}",
38 events.iter().filter(|event| event.organizer_name.is_some()).count()
41 events
42 .iter()
43 .filter(|event| event.organizer_name.is_some())
44 .count()
39 45 );
40 46 println!(
41 47 "# not responded: {}, cancelled: {}, all day: {}",
42 events.iter().filter(|event| event.response == chatsvc::ResponseType::NotResponded).count(),
48 events
49 .iter()
50 .filter(|event| event.response == chatsvc::ResponseType::NotResponded)
51 .count(),
43 52 events.iter().filter(|event| event.cancelled).count(),
44 53 events.iter().filter(|event| event.all_day).count()
45 54 );
@@ -31,15 +31,24 @@ async fn main() {
31 );
31 );
32 println!(
32 println!(
33 "# with thread: {}",
33 "# with thread: {}",
34 events.iter().filter(|event| event.thread_id.is_some()).count()
34 events
35 .iter()
36 .filter(|event| event.thread_id.is_some())
37 .count()
35 );
38 );
36 println!(
39 println!(
37 "# with organizer name: {}",
40 "# with organizer name: {}",
38 events.iter().filter(|event| event.organizer_name.is_some()).count()
41 events
42 .iter()
43 .filter(|event| event.organizer_name.is_some())
44 .count()
39 );
45 );
40 println!(
46 println!(
41 "# not responded: {}, cancelled: {}, all day: {}",
47 "# not responded: {}, cancelled: {}, all day: {}",
42 events.iter().filter(|event| event.response == chatsvc::ResponseType::NotResponded).count(),
48 events
49 .iter()
50 .filter(|event| event.response == chatsvc::ResponseType::NotResponded)
51 .count(),
43 events.iter().filter(|event| event.cancelled).count(),
52 events.iter().filter(|event| event.cancelled).count(),
44 events.iter().filter(|event| event.all_day).count()
53 events.iter().filter(|event| event.all_day).count()
45 );
54 );
crates/chatsvc/examples/presence_endpoint_probe.rs +31 −8
@@ -1,6 +1,8 @@
1 1 use std::time::Duration;
2 2
3 use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
3 use chatsvc::{
4 ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind,
5 };
4 6 use session::{DEFAULT_ENDPOINT, Session};
5 7
6 8 const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
@@ -8,7 +10,9 @@ const SETTLE: Duration = Duration::from_secs(10);
8 10
9 11 #[tokio::main]
10 12 async fn main() {
11 let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
13 let user_id = std::env::args()
14 .nth(1)
15 .expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
12 16 let inactive_wait = std::env::args()
13 17 .nth(2)
14 18 .and_then(|value| value.parse().ok())
@@ -21,11 +25,20 @@ async fn main() {
21 25 initially_active: true,
22 26 ..RealtimeConfig::default()
23 27 };
24 let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
28 let mut realtime = Realtime::start_with(&session, config)
29 .await
30 .expect("realtime start");
25 31 let endpoint_id = wait_for_endpoint(&mut realtime).await;
26 32 println!("# trouter connected");
27 33
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));
34 println!(
35 "register: {}",
36 outcome(
37 presence
38 .register_endpoint(&endpoint_id, ActivityReporting::Transport)
39 .await
40 )
41 );
29 42 realtime.resend_activity();
30 43 println!("# sent active");
31 44 tokio::time::sleep(SETTLE).await;
@@ -36,8 +49,14 @@ async fn main() {
36 49 tokio::time::sleep(inactive_wait).await;
37 50 print_own_presence(&presence, &user_id).await;
38 51
39 println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));
40 println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));
52 println!(
53 "http report inactive: {}",
54 outcome(presence.report_activity(&endpoint_id, false).await)
55 );
56 println!(
57 "unregister: {}",
58 outcome(presence.unregister_endpoint(&endpoint_id).await)
59 );
41 60 realtime.stop().await;
42 61 println!("# stopped");
43 62 }
@@ -49,7 +68,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
49 68 while let Some(event) = realtime.recv().await {
50 69 match event {
51 70 RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
52 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,
71 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => {
72 connected = true
73 }
53 74 _ => {}
54 75 }
55 76 if connected && let Some(endpoint_id) = endpoint_id.take() {
@@ -58,7 +79,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
58 79 }
59 80 panic!("realtime closed before connecting");
60 81 };
61 tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")
82 tokio::time::timeout(CONNECT_TIMEOUT, wait)
83 .await
84 .expect("trouter did not connect")
62 85 }
63 86
64 87 async fn print_own_presence(presence: &PresenceService, user_id: &str) {
@@ -1,6 +1,8 @@
1use std::time::Duration;
1use std::time::Duration;
2
2
3use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
3use chatsvc::{
4 ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind,
5};
4use session::{DEFAULT_ENDPOINT, Session};
6use session::{DEFAULT_ENDPOINT, Session};
5
7
6const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
8const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
@@ -8,7 +10,9 @@ const SETTLE: Duration = Duration::from_secs(10);
8
10
9#[tokio::main]
11#[tokio::main]
10async fn main() {
12async fn main() {
11 let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
13 let user_id = std::env::args()
14 .nth(1)
15 .expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
12 let inactive_wait = std::env::args()
16 let inactive_wait = std::env::args()
13 .nth(2)
17 .nth(2)
14 .and_then(|value| value.parse().ok())
18 .and_then(|value| value.parse().ok())
@@ -21,11 +25,20 @@ async fn main() {
21 initially_active: true,
25 initially_active: true,
22 ..RealtimeConfig::default()
26 ..RealtimeConfig::default()
23 };
27 };
24 let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
28 let mut realtime = Realtime::start_with(&session, config)
29 .await
30 .expect("realtime start");
25 let endpoint_id = wait_for_endpoint(&mut realtime).await;
31 let endpoint_id = wait_for_endpoint(&mut realtime).await;
26 println!("# trouter connected");
32 println!("# trouter connected");
27
33
28 println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));
34 println!(
35 "register: {}",
36 outcome(
37 presence
38 .register_endpoint(&endpoint_id, ActivityReporting::Transport)
39 .await
40 )
41 );
29 realtime.resend_activity();
42 realtime.resend_activity();
30 println!("# sent active");
43 println!("# sent active");
31 tokio::time::sleep(SETTLE).await;
44 tokio::time::sleep(SETTLE).await;
@@ -36,8 +49,14 @@ async fn main() {
36 tokio::time::sleep(inactive_wait).await;
49 tokio::time::sleep(inactive_wait).await;
37 print_own_presence(&presence, &user_id).await;
50 print_own_presence(&presence, &user_id).await;
38
51
39 println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));
52 println!(
40 println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));
53 "http report inactive: {}",
54 outcome(presence.report_activity(&endpoint_id, false).await)
55 );
56 println!(
57 "unregister: {}",
58 outcome(presence.unregister_endpoint(&endpoint_id).await)
59 );
41 realtime.stop().await;
60 realtime.stop().await;
42 println!("# stopped");
61 println!("# stopped");
43}
62}
@@ -49,7 +68,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
49 while let Some(event) = realtime.recv().await {
68 while let Some(event) = realtime.recv().await {
50 match event {
69 match event {
51 RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
70 RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
52 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,
71 RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => {
72 connected = true
73 }
53 _ => {}
74 _ => {}
54 }
75 }
55 if connected && let Some(endpoint_id) = endpoint_id.take() {
76 if connected && let Some(endpoint_id) = endpoint_id.take() {
@@ -58,7 +79,9 @@ async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
58 }
79 }
59 panic!("realtime closed before connecting");
80 panic!("realtime closed before connecting");
60 };
81 };
61 tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")
82 tokio::time::timeout(CONNECT_TIMEOUT, wait)
83 .await
84 .expect("trouter did not connect")
62}
85}
63
86
64async fn print_own_presence(presence: &PresenceService, user_id: &str) {
87async fn print_own_presence(presence: &PresenceService, user_id: &str) {
crates/chatsvc/examples/recap_probe.rs +43 −14
@@ -19,10 +19,13 @@ fn host_and_path_shape(url: &str) -> String {
19 19 _ => "*",
20 20 })
21 21 .collect();
22 let host_kind = without_scheme
23 .split('/')
24 .next()
25 .map_or("?", |host| if host.ends_with("-my.sharepoint.com") { "<tenant>-my.sharepoint.com" } else { "other" });
22 let host_kind = without_scheme.split('/').next().map_or("?", |host| {
23 if host.ends_with("-my.sharepoint.com") {
24 "<tenant>-my.sharepoint.com"
25 } else {
26 "other"
27 }
28 });
26 29 format!("{host_kind}/{}", shape.join("/"))
27 30 }
28 31
@@ -30,15 +33,22 @@ fn error_shape(error: &TranscriptError) -> String {
30 33 match error {
31 34 TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
32 35 "HTTP {status} code {}",
33 body.pointer("/error/code").and_then(serde_json::Value::as_str).unwrap_or("-")
36 body.pointer("/error/code")
37 .and_then(serde_json::Value::as_str)
38 .unwrap_or("-")
39 ),
40 TranscriptError::Request(other) => format!(
41 "request {}",
42 other.to_string().chars().take(60).collect::<String>()
34 43 ),
35 TranscriptError::Request(other) => format!("request {}", other.to_string().chars().take(60).collect::<String>()),
36 44 other => format!("{other:?}"),
37 45 }
38 46 }
39 47
40 48 fn magic(bytes: &[u8]) -> String {
41 let start = bytes.strip_prefix(b"\xEF\xBB\xBF".as_slice()).unwrap_or(bytes);
49 let start = bytes
50 .strip_prefix(b"\xEF\xBB\xBF".as_slice())
51 .unwrap_or(bytes);
42 52 if start.starts_with(b"WEBVTT") {
43 53 format!("WEBVTT (bom {})", start.len() != bytes.len())
44 54 } else if bytes.starts_with(b"PK\x03\x04") {
@@ -51,9 +61,14 @@ fn magic(bytes: &[u8]) -> String {
51 61 #[tokio::main]
52 62 async fn main() {
53 63 let mut arguments = std::env::args().skip(1);
54 let Some(thread_file) = arguments.next() else { usage() };
64 let Some(thread_file) = arguments.next() else {
65 usage()
66 };
55 67 let delete = arguments.any(|argument| argument == "--delete");
56 let thread_id = std::fs::read_to_string(&thread_file).expect("thread file").trim().to_owned();
68 let thread_id = std::fs::read_to_string(&thread_file)
69 .expect("thread file")
70 .trim()
71 .to_owned();
57 72 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
58 73 let session = Session::connect(&endpoint).await.expect("browser");
59 74 let recap = Recap::new(&session);
@@ -76,7 +91,9 @@ async fn main() {
76 91 host_and_path_shape(&occurrence.recording_url)
77 92 );
78 93 }
79 let Some(occurrence) = occurrences.first() else { return };
94 let Some(occurrence) = occurrences.first() else {
95 return;
96 };
80 97
81 98 let details = match recap.details(occurrence).await {
82 99 Ok(details) => details,
@@ -89,7 +106,9 @@ async fn main() {
89 106 "# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
90 107 details.audio_only,
91 108 details.duration_seconds,
92 details.expires_at.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
109 details
110 .expires_at
111 .map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
93 112 details.transcript_id.is_some(),
94 113 host_and_path_shape(&details.item_url)
95 114 );
@@ -99,8 +118,14 @@ async fn main() {
99 118 "# transcript: {} turns, {} with speaker, {} words, spans {:?}",
100 119 turns.len(),
101 120 turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
102 turns.iter().map(|turn| turn.text.split_whitespace().count()).sum::<usize>(),
103 turns.iter().map(|turn| (turn.start_seconds.round(), turn.end_seconds.round())).collect::<Vec<_>>()
121 turns
122 .iter()
123 .map(|turn| turn.text.split_whitespace().count())
124 .sum::<usize>(),
125 turns
126 .iter()
127 .map(|turn| (turn.start_seconds.round(), turn.end_seconds.round()))
128 .collect::<Vec<_>>()
104 129 ),
105 130 Err(error) => println!("# transcript: error {}", error_shape(&error)),
106 131 }
@@ -123,7 +148,11 @@ async fn main() {
123 148 text.contains("word/document.xml")
124 149 );
125 150 }
126 Err(error) => println!("# transcript file {}: error {}", format.query(), error_shape(&error)),
151 Err(error) => println!(
152 "# transcript file {}: error {}",
153 format.query(),
154 error_shape(&error)
155 ),
127 156 }
128 157 }
129 158 let _ = std::fs::remove_dir_all(&directory);
@@ -19,10 +19,13 @@ fn host_and_path_shape(url: &str) -> String {
19 _ => "*",
19 _ => "*",
20 })
20 })
21 .collect();
21 .collect();
22 let host_kind = without_scheme
22 let host_kind = without_scheme.split('/').next().map_or("?", |host| {
23 .split('/')
23 if host.ends_with("-my.sharepoint.com") {
24 .next()
24 "<tenant>-my.sharepoint.com"
25 .map_or("?", |host| if host.ends_with("-my.sharepoint.com") { "<tenant>-my.sharepoint.com" } else { "other" });
25 } else {
26 "other"
27 }
28 });
26 format!("{host_kind}/{}", shape.join("/"))
29 format!("{host_kind}/{}", shape.join("/"))
27}
30}
28
31
@@ -30,15 +33,22 @@ fn error_shape(error: &TranscriptError) -> String {
30 match error {
33 match error {
31 TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
34 TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
32 "HTTP {status} code {}",
35 "HTTP {status} code {}",
33 body.pointer("/error/code").and_then(serde_json::Value::as_str).unwrap_or("-")
36 body.pointer("/error/code")
37 .and_then(serde_json::Value::as_str)
38 .unwrap_or("-")
39 ),
40 TranscriptError::Request(other) => format!(
41 "request {}",
42 other.to_string().chars().take(60).collect::<String>()
34 ),
43 ),
35 TranscriptError::Request(other) => format!("request {}", other.to_string().chars().take(60).collect::<String>()),
36 other => format!("{other:?}"),
44 other => format!("{other:?}"),
37 }
45 }
38}
46}
39
47
40fn magic(bytes: &[u8]) -> String {
48fn magic(bytes: &[u8]) -> String {
41 let start = bytes.strip_prefix(b"\xEF\xBB\xBF".as_slice()).unwrap_or(bytes);
49 let start = bytes
50 .strip_prefix(b"\xEF\xBB\xBF".as_slice())
51 .unwrap_or(bytes);
42 if start.starts_with(b"WEBVTT") {
52 if start.starts_with(b"WEBVTT") {
43 format!("WEBVTT (bom {})", start.len() != bytes.len())
53 format!("WEBVTT (bom {})", start.len() != bytes.len())
44 } else if bytes.starts_with(b"PK\x03\x04") {
54 } else if bytes.starts_with(b"PK\x03\x04") {
@@ -51,9 +61,14 @@ fn magic(bytes: &[u8]) -> String {
51#[tokio::main]
61#[tokio::main]
52async fn main() {
62async fn main() {
53 let mut arguments = std::env::args().skip(1);
63 let mut arguments = std::env::args().skip(1);
54 let Some(thread_file) = arguments.next() else { usage() };
64 let Some(thread_file) = arguments.next() else {
65 usage()
66 };
55 let delete = arguments.any(|argument| argument == "--delete");
67 let delete = arguments.any(|argument| argument == "--delete");
56 let thread_id = std::fs::read_to_string(&thread_file).expect("thread file").trim().to_owned();
68 let thread_id = std::fs::read_to_string(&thread_file)
69 .expect("thread file")
70 .trim()
71 .to_owned();
57 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
72 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
58 let session = Session::connect(&endpoint).await.expect("browser");
73 let session = Session::connect(&endpoint).await.expect("browser");
59 let recap = Recap::new(&session);
74 let recap = Recap::new(&session);
@@ -76,7 +91,9 @@ async fn main() {
76 host_and_path_shape(&occurrence.recording_url)
91 host_and_path_shape(&occurrence.recording_url)
77 );
92 );
78 }
93 }
79 let Some(occurrence) = occurrences.first() else { return };
94 let Some(occurrence) = occurrences.first() else {
95 return;
96 };
80
97
81 let details = match recap.details(occurrence).await {
98 let details = match recap.details(occurrence).await {
82 Ok(details) => details,
99 Ok(details) => details,
@@ -89,7 +106,9 @@ async fn main() {
89 "# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
106 "# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
90 details.audio_only,
107 details.audio_only,
91 details.duration_seconds,
108 details.duration_seconds,
92 details.expires_at.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
109 details
110 .expires_at
111 .map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
93 details.transcript_id.is_some(),
112 details.transcript_id.is_some(),
94 host_and_path_shape(&details.item_url)
113 host_and_path_shape(&details.item_url)
95 );
114 );
@@ -99,8 +118,14 @@ async fn main() {
99 "# transcript: {} turns, {} with speaker, {} words, spans {:?}",
118 "# transcript: {} turns, {} with speaker, {} words, spans {:?}",
100 turns.len(),
119 turns.len(),
101 turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
120 turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
102 turns.iter().map(|turn| turn.text.split_whitespace().count()).sum::<usize>(),
121 turns
103 turns.iter().map(|turn| (turn.start_seconds.round(), turn.end_seconds.round())).collect::<Vec<_>>()
122 .iter()
123 .map(|turn| turn.text.split_whitespace().count())
124 .sum::<usize>(),
125 turns
126 .iter()
127 .map(|turn| (turn.start_seconds.round(), turn.end_seconds.round()))
128 .collect::<Vec<_>>()
104 ),
129 ),
105 Err(error) => println!("# transcript: error {}", error_shape(&error)),
130 Err(error) => println!("# transcript: error {}", error_shape(&error)),
106 }
131 }
@@ -123,7 +148,11 @@ async fn main() {
123 text.contains("word/document.xml")
148 text.contains("word/document.xml")
124 );
149 );
125 }
150 }
126 Err(error) => println!("# transcript file {}: error {}", format.query(), error_shape(&error)),
151 Err(error) => println!(
152 "# transcript file {}: error {}",
153 format.query(),
154 error_shape(&error)
155 ),
127 }
156 }
128 }
157 }
129 let _ = std::fs::remove_dir_all(&directory);
158 let _ = std::fs::remove_dir_all(&directory);
crates/chatsvc/examples/tab_raw_probe.rs +43 −8
@@ -4,25 +4,60 @@ use session::{DEFAULT_ENDPOINT, Request, Scope, Session};
4 4 #[tokio::main]
5 5 async fn main() {
6 6 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
7 let needle = std::env::args().nth(1).unwrap_or_else(|| "Lunch".to_owned());
7 let needle = std::env::args()
8 .nth(1)
9 .unwrap_or_else(|| "Lunch".to_owned());
8 10 let session = Session::connect(&endpoint).await.expect("browser");
9 11 let url = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true";
10 let scope = Scope::new("https://chatsvcagg.teams.microsoft.com", "user_impersonation");
11 let answer = session.batch(&[Request::get(url)], &scope).await.expect("csa").remove(0);
12 let scope = Scope::new(
13 "https://chatsvcagg.teams.microsoft.com",
14 "user_impersonation",
15 );
16 let answer = session
17 .batch(&[Request::get(url)], &scope)
18 .await
19 .expect("csa")
20 .remove(0);
12 21 println!("# status {}", answer.status);
13 for team in answer.body.get("teams").and_then(Value::as_array).into_iter().flatten() {
14 for channel in team.get("channels").and_then(Value::as_array).into_iter().flatten() {
15 let name = channel.get("displayName").and_then(Value::as_str).unwrap_or_default();
22 for team in answer
23 .body
24 .get("teams")
25 .and_then(Value::as_array)
26 .into_iter()
27 .flatten()
28 {
29 for channel in team
30 .get("channels")
31 .and_then(Value::as_array)
32 .into_iter()
33 .flatten()
34 {
35 let name = channel
36 .get("displayName")
37 .and_then(Value::as_str)
38 .unwrap_or_default();
16 39 if !name.contains(&needle) {
17 40 continue;
18 41 }
19 42 println!("channel {name}");
20 for tab in channel.get("tabs").and_then(Value::as_array).into_iter().flatten() {
43 for tab in channel
44 .get("tabs")
45 .and_then(Value::as_array)
46 .into_iter()
47 .flatten()
48 {
21 49 let mut shown = tab.clone();
22 50 if let Some(object) = shown.as_object_mut() {
23 51 object.retain(|key, _| key != "replyChainId");
24 52 }
25 println!(" {}", serde_json::to_string(&shown).unwrap_or_default().chars().take(1500).collect::<String>());
53 println!(
54 " {}",
55 serde_json::to_string(&shown)
56 .unwrap_or_default()
57 .chars()
58 .take(1500)
59 .collect::<String>()
60 );
26 61 }
27 62 }
28 63 }
@@ -4,25 +4,60 @@ use session::{DEFAULT_ENDPOINT, Request, Scope, Session};
4#[tokio::main]
4#[tokio::main]
5async fn main() {
5async fn main() {
6 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
6 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
7 let needle = std::env::args().nth(1).unwrap_or_else(|| "Lunch".to_owned());
7 let needle = std::env::args()
8 .nth(1)
9 .unwrap_or_else(|| "Lunch".to_owned());
8 let session = Session::connect(&endpoint).await.expect("browser");
10 let session = Session::connect(&endpoint).await.expect("browser");
9 let url = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true";
11 let url = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true";
10 let scope = Scope::new("https://chatsvcagg.teams.microsoft.com", "user_impersonation");
12 let scope = Scope::new(
11 let answer = session.batch(&[Request::get(url)], &scope).await.expect("csa").remove(0);
13 "https://chatsvcagg.teams.microsoft.com",
14 "user_impersonation",
15 );
16 let answer = session
17 .batch(&[Request::get(url)], &scope)
18 .await
19 .expect("csa")
20 .remove(0);
12 println!("# status {}", answer.status);
21 println!("# status {}", answer.status);
13 for team in answer.body.get("teams").and_then(Value::as_array).into_iter().flatten() {
22 for team in answer
14 for channel in team.get("channels").and_then(Value::as_array).into_iter().flatten() {
23 .body
15 let name = channel.get("displayName").and_then(Value::as_str).unwrap_or_default();
24 .get("teams")
25 .and_then(Value::as_array)
26 .into_iter()
27 .flatten()
28 {
29 for channel in team
30 .get("channels")
31 .and_then(Value::as_array)
32 .into_iter()
33 .flatten()
34 {
35 let name = channel
36 .get("displayName")
37 .and_then(Value::as_str)
38 .unwrap_or_default();
16 if !name.contains(&needle) {
39 if !name.contains(&needle) {
17 continue;
40 continue;
18 }
41 }
19 println!("channel {name}");
42 println!("channel {name}");
20 for tab in channel.get("tabs").and_then(Value::as_array).into_iter().flatten() {
43 for tab in channel
44 .get("tabs")
45 .and_then(Value::as_array)
46 .into_iter()
47 .flatten()
48 {
21 let mut shown = tab.clone();
49 let mut shown = tab.clone();
22 if let Some(object) = shown.as_object_mut() {
50 if let Some(object) = shown.as_object_mut() {
23 object.retain(|key, _| key != "replyChainId");
51 object.retain(|key, _| key != "replyChainId");
24 }
52 }
25 println!(" {}", serde_json::to_string(&shown).unwrap_or_default().chars().take(1500).collect::<String>());
53 println!(
54 " {}",
55 serde_json::to_string(&shown)
56 .unwrap_or_default()
57 .chars()
58 .take(1500)
59 .collect::<String>()
60 );
26 }
61 }
27 }
62 }
28 }
63 }
crates/chatsvc/examples/tabs_probe.rs +21 −4
@@ -8,14 +8,31 @@ async fn main() {
8 8 let pins = Pins::new(&session);
9 9 match pins.folders().await {
10 10 Ok(folders) => println!("# folders ok: {}", folders.folders.len()),
11 Err(error) => println!("# folders failed: {}", error.to_string().chars().take(160).collect::<String>()),
11 Err(error) => println!(
12 "# folders failed: {}",
13 error.to_string().chars().take(160).collect::<String>()
14 ),
12 15 }
13 16 match pins.pinned_channels().await {
14 17 Ok(channels) => println!("# pinned channels ok: {}", channels.channel_ids.len()),
15 Err(error) => println!("# pinned channels failed: {}", error.to_string().chars().take(160).collect::<String>()),
18 Err(error) => println!(
19 "# pinned channels failed: {}",
20 error.to_string().chars().take(160).collect::<String>()
21 ),
16 22 }
17 23 match pins.team_layout().await {
18 Ok(layout) => println!("# team layout ok: {} teams, {} tabs", layout.len(), layout.iter().flat_map(|team| team.channels.iter()).map(|channel| channel.tabs.len()).sum::<usize>()),
19 Err(error) => println!("# team layout failed: {}", error.to_string().chars().take(160).collect::<String>()),
24 Ok(layout) => println!(
25 "# team layout ok: {} teams, {} tabs",
26 layout.len(),
27 layout
28 .iter()
29 .flat_map(|team| team.channels.iter())
30 .map(|channel| channel.tabs.len())
31 .sum::<usize>()
32 ),
33 Err(error) => println!(
34 "# team layout failed: {}",
35 error.to_string().chars().take(160).collect::<String>()
36 ),
20 37 }
21 38 }
@@ -8,14 +8,31 @@ async fn main() {
8 let pins = Pins::new(&session);
8 let pins = Pins::new(&session);
9 match pins.folders().await {
9 match pins.folders().await {
10 Ok(folders) => println!("# folders ok: {}", folders.folders.len()),
10 Ok(folders) => println!("# folders ok: {}", folders.folders.len()),
11 Err(error) => println!("# folders failed: {}", error.to_string().chars().take(160).collect::<String>()),
11 Err(error) => println!(
12 "# folders failed: {}",
13 error.to_string().chars().take(160).collect::<String>()
14 ),
12 }
15 }
13 match pins.pinned_channels().await {
16 match pins.pinned_channels().await {
14 Ok(channels) => println!("# pinned channels ok: {}", channels.channel_ids.len()),
17 Ok(channels) => println!("# pinned channels ok: {}", channels.channel_ids.len()),
15 Err(error) => println!("# pinned channels failed: {}", error.to_string().chars().take(160).collect::<String>()),
18 Err(error) => println!(
19 "# pinned channels failed: {}",
20 error.to_string().chars().take(160).collect::<String>()
21 ),
16 }
22 }
17 match pins.team_layout().await {
23 match pins.team_layout().await {
18 Ok(layout) => println!("# team layout ok: {} teams, {} tabs", layout.len(), layout.iter().flat_map(|team| team.channels.iter()).map(|channel| channel.tabs.len()).sum::<usize>()),
24 Ok(layout) => println!(
19 Err(error) => println!("# team layout failed: {}", error.to_string().chars().take(160).collect::<String>()),
25 "# team layout ok: {} teams, {} tabs",
26 layout.len(),
27 layout
28 .iter()
29 .flat_map(|team| team.channels.iter())
30 .map(|channel| channel.tabs.len())
31 .sum::<usize>()
32 ),
33 Err(error) => println!(
34 "# team layout failed: {}",
35 error.to_string().chars().take(160).collect::<String>()
36 ),
20 }
37 }
21}
38}
crates/chatsvc/src/conversations.rs +8 −1
@@ -304,7 +304,14 @@ mod tests {
304 304 let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();
305 305 assert_eq!(
306 306 hidden,
307 [Some(true), Some(false), Some(true), None, Some(true), Some(true)]
307 [
308 Some(true),
309 Some(false),
310 Some(true),
311 None,
312 Some(true),
313 Some(true)
314 ]
308 315 );
309 316 }
310 317
@@ -304,7 +304,14 @@ mod tests {
304 let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();
304 let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect();
305 assert_eq!(
305 assert_eq!(
306 hidden,
306 hidden,
307 [Some(true), Some(false), Some(true), None, Some(true), Some(true)]
307 [
308 Some(true),
309 Some(false),
310 Some(true),
311 None,
312 Some(true),
313 Some(true)
314 ]
308 );
315 );
309 }
316 }
310
317
crates/chatsvc/src/emotions.rs +1 −5
@@ -57,11 +57,7 @@ pub fn parse_message_emotions(body: &Value) -> Vec<MessageEmotions> {
57 57 .into_iter()
58 58 .flatten()
59 59 .filter_map(|message| {
60 let message_id = match message.get("id")? {
61 Value::String(text) if !text.is_empty() => text.clone(),
62 Value::Number(number) => number.to_string(),
63 _ => return None,
64 };
60 let message_id = crate::json_id::id_text(message.get("id")?)?;
65 61 Some(MessageEmotions {
66 62 message_id,
67 63 reactions: reactions(message.pointer("/properties/emotions")),
@@ -57,11 +57,7 @@ pub fn parse_message_emotions(body: &Value) -> Vec<MessageEmotions> {
57 .into_iter()
57 .into_iter()
58 .flatten()
58 .flatten()
59 .filter_map(|message| {
59 .filter_map(|message| {
60 let message_id = match message.get("id")? {
60 let message_id = crate::json_id::id_text(message.get("id")?)?;
61 Value::String(text) if !text.is_empty() => text.clone(),
62 Value::Number(number) => number.to_string(),
63 _ => return None,
64 };
65 Some(MessageEmotions {
61 Some(MessageEmotions {
66 message_id,
62 message_id,
67 reactions: reactions(message.pointer("/properties/emotions")),
63 reactions: reactions(message.pointer("/properties/emotions")),
crates/chatsvc/src/json_id.rs added +42 −0
@@ -0,0 +1,42 @@
1 use serde_json::{Number, Value};
2
3 pub(crate) fn id_text(value: &Value) -> Option<String> {
4 match value {
5 Value::String(text) if !text.is_empty() => Some(text.clone()),
6 Value::Number(number) => Some(integer_text(number)),
7 _ => None,
8 }
9 }
10
11 fn integer_text(number: &Number) -> String {
12 match number.as_f64() {
13 Some(float) if number.is_f64() && float.fract() == 0.0 && float >= 0.0 => {
14 format!("{float:.0}")
15 }
16 _ => number.to_string(),
17 }
18 }
19
20 #[cfg(test)]
21 mod tests {
22 use serde_json::json;
23
24 use super::*;
25
26 #[test]
27 fn float_ids_read_as_integers() {
28 assert_eq!(
29 id_text(&json!(1783430602049.0)).as_deref(),
30 Some("1783430602049")
31 );
32 assert_eq!(
33 id_text(&json!(1783430602049u64)).as_deref(),
34 Some("1783430602049")
35 );
36 assert_eq!(
37 id_text(&json!("1783430602049")).as_deref(),
38 Some("1783430602049")
39 );
40 assert_eq!(id_text(&json!("")), None);
41 }
42 }
@@ -0,0 +1,42 @@
1use serde_json::{Number, Value};
2
3pub(crate) fn id_text(value: &Value) -> Option<String> {
4 match value {
5 Value::String(text) if !text.is_empty() => Some(text.clone()),
6 Value::Number(number) => Some(integer_text(number)),
7 _ => None,
8 }
9}
10
11fn integer_text(number: &Number) -> String {
12 match number.as_f64() {
13 Some(float) if number.is_f64() && float.fract() == 0.0 && float >= 0.0 => {
14 format!("{float:.0}")
15 }
16 _ => number.to_string(),
17 }
18}
19
20#[cfg(test)]
21mod tests {
22 use serde_json::json;
23
24 use super::*;
25
26 #[test]
27 fn float_ids_read_as_integers() {
28 assert_eq!(
29 id_text(&json!(1783430602049.0)).as_deref(),
30 Some("1783430602049")
31 );
32 assert_eq!(
33 id_text(&json!(1783430602049u64)).as_deref(),
34 Some("1783430602049")
35 );
36 assert_eq!(
37 id_text(&json!("1783430602049")).as_deref(),
38 Some("1783430602049")
39 );
40 assert_eq!(id_text(&json!("")), None);
41 }
42}
crates/chatsvc/src/lib.rs +17 −13
@@ -8,6 +8,7 @@ pub mod emotions;
8 8 mod error;
9 9 pub mod forward;
10 10 pub mod gifs;
11 mod json_id;
11 12 pub mod language_settings;
12 13 pub mod links;
13 14 mod mask;
@@ -16,10 +17,10 @@ pub mod pins;
16 17 pub mod presence;
17 18 pub mod reactions;
18 19 pub mod read_horizon;
19 pub mod recap;
20 20 pub mod realtime;
21 pub mod recording_policy;
21 pub mod recap;
22 22 pub mod receipts;
23 pub mod recording_policy;
23 24 pub mod saved;
24 25 pub mod settings;
25 26 pub mod sound_settings;
@@ -29,8 +30,8 @@ pub mod translate;
29 30 pub mod window;
30 31
31 32 pub use calendar::{
32 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply, ResponseType,
33 meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
33 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
34 ResponseType, meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
34 35 };
35 36 pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
36 37 pub use cards::{
@@ -38,8 +39,8 @@ pub use cards::{
38 39 };
39 40 pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
40 41 pub use conversations::{ConversationState, Conversations};
41 pub use read_horizon::ReadHorizon;
42 42 pub use drafts::{ScheduledDraft, ScheduledDrafts};
43 pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
43 44 pub use error::{Error, Result};
44 45 pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
45 46 pub use gifs::{Gif, Gifs};
@@ -47,7 +48,6 @@ pub use language_settings::{
47 48 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
48 49 parse_language_settings, target_patch,
49 50 };
50 pub use recording_policy::{RecordingPolicy, parse_recording_policy};
51 51 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
52 52 pub use mask::mask_conversation_id;
53 53 pub use messages::{ConversationRef, Messages};
@@ -56,23 +56,27 @@ pub use pins::{
56 56 PinnedMessage, Pins, TeamLayout,
57 57 };
58 58 pub use presence::{
59 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
60 WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
59 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,
60 WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
61 61 };
62 pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
63 pub use reactions::{emotion_glyph, insert_skin_tone, reaction_glyph_for_key, emotion_key, emotion_keys, reaction_key, reaction_keys};
62 pub use reactions::{
63 emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,
64 reaction_key, reaction_keys,
65 };
66 pub use read_horizon::ReadHorizon;
64 67 pub use realtime::{
65 68 CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,
66 69 RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,
67 70 TypingEvent,
68 71 };
69 pub use receipts::{MemberHorizon, Receipts};
70 pub use saved::SavedMessage;
71 pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
72 72 pub use recap::{
73 73 Attendance, AttendanceRecord, Occurrence, Recap, RecordingDetails, TranscriptFormat,
74 74 days_until_expiry,
75 75 };
76 pub use receipts::{MemberHorizon, Receipts};
77 pub use recording_policy::{RecordingPolicy, parse_recording_policy};
78 pub use saved::SavedMessage;
79 pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
76 80 pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
77 81 pub use translate::{
78 82 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
@@ -8,6 +8,7 @@ pub mod emotions;
8mod error;
8mod error;
9pub mod forward;
9pub mod forward;
10pub mod gifs;
10pub mod gifs;
11mod json_id;
11pub mod language_settings;
12pub mod language_settings;
12pub mod links;
13pub mod links;
13mod mask;
14mod mask;
@@ -16,10 +17,10 @@ pub mod pins;
16pub mod presence;
17pub mod presence;
17pub mod reactions;
18pub mod reactions;
18pub mod read_horizon;
19pub mod read_horizon;
19pub mod recap;
20pub mod realtime;
20pub mod realtime;
21pub mod recording_policy;
21pub mod recap;
22pub mod receipts;
22pub mod receipts;
23pub mod recording_policy;
23pub mod saved;
24pub mod saved;
24pub mod settings;
25pub mod settings;
25pub mod sound_settings;
26pub mod sound_settings;
@@ -29,8 +30,8 @@ pub mod translate;
29pub mod window;
30pub mod window;
30
31
31pub use calendar::{
32pub use calendar::{
32 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply, ResponseType,
33 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
33 meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
34 ResponseType, meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
34};
35};
35pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
36pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
36pub use cards::{
37pub use cards::{
@@ -38,8 +39,8 @@ pub use cards::{
38};
39};
39pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
40pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
40pub use conversations::{ConversationState, Conversations};
41pub use conversations::{ConversationState, Conversations};
41pub use read_horizon::ReadHorizon;
42pub use drafts::{ScheduledDraft, ScheduledDrafts};
42pub use drafts::{ScheduledDraft, ScheduledDrafts};
43pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
43pub use error::{Error, Result};
44pub use error::{Error, Result};
44pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
45pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
45pub use gifs::{Gif, Gifs};
46pub use gifs::{Gif, Gifs};
@@ -47,7 +48,6 @@ pub use language_settings::{
47 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
48 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
48 parse_language_settings, target_patch,
49 parse_language_settings, target_patch,
49};
50};
50pub use recording_policy::{RecordingPolicy, parse_recording_policy};
51pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
51pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
52pub use mask::mask_conversation_id;
52pub use mask::mask_conversation_id;
53pub use messages::{ConversationRef, Messages};
53pub use messages::{ConversationRef, Messages};
@@ -56,23 +56,27 @@ pub use pins::{
56 PinnedMessage, Pins, TeamLayout,
56 PinnedMessage, Pins, TeamLayout,
57};
57};
58pub use presence::{
58pub use presence::{
59 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
59 ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,
60 WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
60 WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
61};
61};
62pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
62pub use reactions::{
63pub use reactions::{emotion_glyph, insert_skin_tone, reaction_glyph_for_key, emotion_key, emotion_keys, reaction_key, reaction_keys};
63 emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,
64 reaction_key, reaction_keys,
65};
66pub use read_horizon::ReadHorizon;
64pub use realtime::{
67pub use realtime::{
65 CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,
68 CallbackReplier, EventKind, InstanceNames, MessageEvent, PresenceUpdate, Realtime,
66 RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,
69 RealtimeConfig, RealtimeEvent, StatusEvent, StatusKind, TrouterCallback, TrouterEndpoint,
67 TypingEvent,
70 TypingEvent,
68};
71};
69pub use receipts::{MemberHorizon, Receipts};
70pub use saved::SavedMessage;
71pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
72pub use recap::{
72pub use recap::{
73 Attendance, AttendanceRecord, Occurrence, Recap, RecordingDetails, TranscriptFormat,
73 Attendance, AttendanceRecord, Occurrence, Recap, RecordingDetails, TranscriptFormat,
74 days_until_expiry,
74 days_until_expiry,
75};
75};
76pub use receipts::{MemberHorizon, Receipts};
77pub use recording_policy::{RecordingPolicy, parse_recording_policy};
78pub use saved::SavedMessage;
79pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
76pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
80pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
77pub use translate::{
81pub use translate::{
78 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
82 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
crates/chatsvc/src/pins/state.rs +1 −3
@@ -24,9 +24,7 @@ pub(super) fn hierarchy_version(body: &Value) -> Result<i64> {
24 24 number
25 25 .as_f64()
26 26 .filter(|float| float.is_finite() && float.fract() == 0.0)
27 .filter(|float| {
28 *float >= i64::MIN as f64 && *float < i64::MAX as f64
29 })
27 .filter(|float| *float >= i64::MIN as f64 && *float < i64::MAX as f64)
30 28 .map(|float| float as i64)
31 29 }),
32 30 Value::String(text) => text.trim().parse::<i64>().ok(),
@@ -24,9 +24,7 @@ pub(super) fn hierarchy_version(body: &Value) -> Result<i64> {
24 number
24 number
25 .as_f64()
25 .as_f64()
26 .filter(|float| float.is_finite() && float.fract() == 0.0)
26 .filter(|float| float.is_finite() && float.fract() == 0.0)
27 .filter(|float| {
27 .filter(|float| *float >= i64::MIN as f64 && *float < i64::MAX as f64)
28 *float >= i64::MIN as f64 && *float < i64::MAX as f64
29 })
30 .map(|float| float as i64)
28 .map(|float| float as i64)
31 }),
29 }),
32 Value::String(text) => text.trim().parse::<i64>().ok(),
30 Value::String(text) => text.trim().parse::<i64>().ok(),
crates/chatsvc/src/pins/teams.rs +5 −1
@@ -297,7 +297,11 @@ mod tests {
297 297 .collect();
298 298 assert_eq!(
299 299 names,
300 ["Lunch Order Board \u{1F37D}\u{FE0F}", "100% done", "Bad%FFbytes"]
300 [
301 "Lunch Order Board \u{1F37D}\u{FE0F}",
302 "100% done",
303 "Bad%FFbytes"
304 ]
301 305 );
302 306 }
303 307
@@ -297,7 +297,11 @@ mod tests {
297 .collect();
297 .collect();
298 assert_eq!(
298 assert_eq!(
299 names,
299 names,
300 ["Lunch Order Board \u{1F37D}\u{FE0F}", "100% done", "Bad%FFbytes"]
300 [
301 "Lunch Order Board \u{1F37D}\u{FE0F}",
302 "100% done",
303 "Bad%FFbytes"
304 ]
301 );
305 );
302 }
306 }
303
307
crates/chatsvc/src/presence.rs +15 −4
@@ -147,9 +147,14 @@ impl<T: CardTransport> PresenceService<T> {
147 147 self.send(request, &url).await.map(drop)
148 148 }
149 149
150 pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {
150 pub async fn register_endpoint(
151 &self,
152 endpoint_id: &str,
153 reporting: ActivityReporting,
154 ) -> Result<()> {
151 155 let url = format!("{BASE_URL}/me/endpoints/");
152 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
156 let mut request =
157 Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
153 158 request.headers = endpoint_headers(endpoint_id);
154 159 self.send(request, &url).await.map(drop)
155 160 }
@@ -502,7 +507,10 @@ mod tests {
502 507 #[tokio::test]
503 508 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
504 509 let service = service(200, Value::Null);
505 service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();
510 service
511 .register_endpoint("epid-1", ActivityReporting::Transport)
512 .await
513 .unwrap();
506 514 let (request, scope) = only_request(&service);
507 515 assert_eq!(request.method, Method::Put);
508 516 assert_eq!(
@@ -533,7 +541,10 @@ mod tests {
533 541 #[tokio::test]
534 542 async fn register_endpoint_can_switch_to_direct_reporting() {
535 543 let service = service(200, Value::Null);
536 service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();
544 service
545 .register_endpoint("epid-1", ActivityReporting::Direct)
546 .await
547 .unwrap();
537 548 let (request, _) = only_request(&service);
538 549 assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
539 550 }
@@ -147,9 +147,14 @@ impl<T: CardTransport> PresenceService<T> {
147 self.send(request, &url).await.map(drop)
147 self.send(request, &url).await.map(drop)
148 }
148 }
149
149
150 pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {
150 pub async fn register_endpoint(
151 &self,
152 endpoint_id: &str,
153 reporting: ActivityReporting,
154 ) -> Result<()> {
151 let url = format!("{BASE_URL}/me/endpoints/");
155 let url = format!("{BASE_URL}/me/endpoints/");
152 let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
156 let mut request =
157 Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
153 request.headers = endpoint_headers(endpoint_id);
158 request.headers = endpoint_headers(endpoint_id);
154 self.send(request, &url).await.map(drop)
159 self.send(request, &url).await.map(drop)
155 }
160 }
@@ -502,7 +507,10 @@ mod tests {
502 #[tokio::test]
507 #[tokio::test]
503 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
508 async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
504 let service = service(200, Value::Null);
509 let service = service(200, Value::Null);
505 service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();
510 service
511 .register_endpoint("epid-1", ActivityReporting::Transport)
512 .await
513 .unwrap();
506 let (request, scope) = only_request(&service);
514 let (request, scope) = only_request(&service);
507 assert_eq!(request.method, Method::Put);
515 assert_eq!(request.method, Method::Put);
508 assert_eq!(
516 assert_eq!(
@@ -533,7 +541,10 @@ mod tests {
533 #[tokio::test]
541 #[tokio::test]
534 async fn register_endpoint_can_switch_to_direct_reporting() {
542 async fn register_endpoint_can_switch_to_direct_reporting() {
535 let service = service(200, Value::Null);
543 let service = service(200, Value::Null);
536 service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();
544 service
545 .register_endpoint("epid-1", ActivityReporting::Direct)
546 .await
547 .unwrap();
537 let (request, _) = only_request(&service);
548 let (request, _) = only_request(&service);
538 assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
549 assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
539 }
550 }
crates/chatsvc/src/realtime/event.rs +4 −1
@@ -180,7 +180,10 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
180 180 activity: if entry.out_of_office {
181 181 Some(OUT_OF_OFFICE_ACTIVITY.to_owned())
182 182 } else {
183 entry.activity.map(bounded).filter(|value| !value.is_empty())
183 entry
184 .activity
185 .map(bounded)
186 .filter(|value| !value.is_empty())
184 187 },
185 188 })
186 189 })
@@ -180,7 +180,10 @@ pub fn decode_payload(payload: &str) -> Result<RealtimeEvent> {
180 activity: if entry.out_of_office {
180 activity: if entry.out_of_office {
181 Some(OUT_OF_OFFICE_ACTIVITY.to_owned())
181 Some(OUT_OF_OFFICE_ACTIVITY.to_owned())
182 } else {
182 } else {
183 entry.activity.map(bounded).filter(|value| !value.is_empty())
183 entry
184 .activity
185 .map(bounded)
186 .filter(|value| !value.is_empty())
184 },
187 },
185 })
188 })
186 })
189 })
crates/chatsvc/src/realtime/mod.rs +1 −1
@@ -13,11 +13,11 @@ use session::Session;
13 13 use tokio::sync::{Notify, mpsc, oneshot, watch};
14 14 use tokio::task::JoinHandle;
15 15
16 pub use callback::{CallbackReplier, TrouterCallback};
16 17 pub use event::{
17 18 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
18 19 TrouterEndpoint, TypingEvent, decode_payload,
19 20 };
20 pub use callback::{CallbackReplier, TrouterCallback};
21 21 pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
22 22
23 23 use crate::error::Result;
@@ -13,11 +13,11 @@ use session::Session;
13use tokio::sync::{Notify, mpsc, oneshot, watch};
13use tokio::sync::{Notify, mpsc, oneshot, watch};
14use tokio::task::JoinHandle;
14use tokio::task::JoinHandle;
15
15
16pub use callback::{CallbackReplier, TrouterCallback};
16pub use event::{
17pub use event::{
17 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
18 EventKind, MessageEvent, PresenceUpdate, RealtimeEvent, StatusEvent, StatusKind,
18 TrouterEndpoint, TypingEvent, decode_payload,
19 TrouterEndpoint, TypingEvent, decode_payload,
19};
20};
20pub use callback::{CallbackReplier, TrouterCallback};
21pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
21pub use host::{DEFAULT_TROUTER_HOST, is_trouter_host};
22
22
23use crate::error::Result;
23use crate::error::Result;
crates/chatsvc/src/realtime/runner.rs +42 −14
@@ -34,9 +34,13 @@ impl PageScript {
34 34 let mut worker_source = WORKER_TEMPLATE
35 35 .replace(&quoted(DEFAULT_GLOBAL_NAME), &quoted(&names.global))
36 36 .replace(&quoted(DEFAULT_BINDING_NAME), &quoted(&names.binding))
37 .replace(&quoted(DEFAULT_EPID_KEY), &quoted(&names.endpoint_storage_key));
37 .replace(
38 &quoted(DEFAULT_EPID_KEY),
39 &quoted(&names.endpoint_storage_key),
40 );
38 41 if config.forward_callbacks {
39 worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
42 worker_source =
43 worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
40 44 }
41 45 if config.ringable {
42 46 worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");
@@ -90,7 +94,10 @@ pub(super) struct Attached {
90 94 stop_expression: String,
91 95 }
92 96
93 pub(super) async fn attach(session: &Session, script: &PageScript) -> crate::error::Result<Attached> {
97 pub(super) async fn attach(
98 session: &Session,
99 script: &PageScript,
100 ) -> crate::error::Result<Attached> {
94 101 let (control, events) = session.subscribe(App::Teams).await?;
95 102 control.enable_events().await?;
96 103 control.add_binding(&script.binding_name).await?;
@@ -378,11 +385,9 @@ mod tests {
378 385 fn ensure_body_embeds_the_worker_once_before_the_call() {
379 386 let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();
380 387 assert!(ensure_body.starts_with("(() => {"));
381 assert!(
382 ensure_body
383 .trim_end()
384 .ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")
385 );
388 assert!(ensure_body.trim_end().ends_with(
389 "window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});"
390 ));
386 391 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
387 392 }
388 393
@@ -399,9 +404,20 @@ mod tests {
399 404 };
400 405 let script = PageScript::new(&config);
401 406 assert!(!script.worker_source.contains("__chatsvc"));
402 assert!(script.worker_source.contains("const GLOBAL_NAME = '__callingTrouter';"));
403 assert!(script.worker_source.contains("const FORWARD_CALLBACKS = true;"));
404 assert_eq!(script.stop_expression(), "window.__callingTrouter ? window.__callingTrouter.stop() : null");
407 assert!(
408 script
409 .worker_source
410 .contains("const GLOBAL_NAME = '__callingTrouter';")
411 );
412 assert!(
413 script
414 .worker_source
415 .contains("const FORWARD_CALLBACKS = true;")
416 );
417 assert_eq!(
418 script.stop_expression(),
419 "window.__callingTrouter ? window.__callingTrouter.stop() : null"
420 );
405 421 let default_script = PageScript::new(&RealtimeConfig::default());
406 422 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
407 423 }
@@ -416,9 +432,21 @@ mod tests {
416 432 let quiet = PageScript::new(&RealtimeConfig::default());
417 433 assert!(quiet.worker_source.contains(REGISTRATION_OFF));
418 434 for script in [ringable, quiet] {
419 assert!(script.worker_source.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}"));
420 assert!(script.worker_source.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}"));
421 assert!(script.worker_source.contains("RINGABLE ? {productContext: ''} : {}"));
435 assert!(
436 script
437 .worker_source
438 .contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}")
439 );
440 assert!(
441 script
442 .worker_source
443 .contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}")
444 );
445 assert!(
446 script
447 .worker_source
448 .contains("RINGABLE ? {productContext: ''} : {}")
449 );
422 450 }
423 451 }
424 452 }
@@ -34,9 +34,13 @@ impl PageScript {
34 let mut worker_source = WORKER_TEMPLATE
34 let mut worker_source = WORKER_TEMPLATE
35 .replace(&quoted(DEFAULT_GLOBAL_NAME), &quoted(&names.global))
35 .replace(&quoted(DEFAULT_GLOBAL_NAME), &quoted(&names.global))
36 .replace(&quoted(DEFAULT_BINDING_NAME), &quoted(&names.binding))
36 .replace(&quoted(DEFAULT_BINDING_NAME), &quoted(&names.binding))
37 .replace(&quoted(DEFAULT_EPID_KEY), &quoted(&names.endpoint_storage_key));
37 .replace(
38 &quoted(DEFAULT_EPID_KEY),
39 &quoted(&names.endpoint_storage_key),
40 );
38 if config.forward_callbacks {
41 if config.forward_callbacks {
39 worker_source = worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
42 worker_source =
43 worker_source.replace(FORWARD_CALLBACKS_OFF, "const FORWARD_CALLBACKS = true;");
40 }
44 }
41 if config.ringable {
45 if config.ringable {
42 worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");
46 worker_source = worker_source.replace(REGISTRATION_OFF, "const RINGABLE = true;");
@@ -90,7 +94,10 @@ pub(super) struct Attached {
90 stop_expression: String,
94 stop_expression: String,
91}
95}
92
96
93pub(super) async fn attach(session: &Session, script: &PageScript) -> crate::error::Result<Attached> {
97pub(super) async fn attach(
98 session: &Session,
99 script: &PageScript,
100) -> crate::error::Result<Attached> {
94 let (control, events) = session.subscribe(App::Teams).await?;
101 let (control, events) = session.subscribe(App::Teams).await?;
95 control.enable_events().await?;
102 control.enable_events().await?;
96 control.add_binding(&script.binding_name).await?;
103 control.add_binding(&script.binding_name).await?;
@@ -378,11 +385,9 @@ mod tests {
378 fn ensure_body_embeds_the_worker_once_before_the_call() {
385 fn ensure_body_embeds_the_worker_once_before_the_call() {
379 let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();
386 let ensure_body = PageScript::new(&RealtimeConfig::default()).ensure_body();
380 assert!(ensure_body.starts_with("(() => {"));
387 assert!(ensure_body.starts_with("(() => {"));
381 assert!(
388 assert!(ensure_body.trim_end().ends_with(
382 ensure_body
389 "window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});"
383 .trim_end()
390 ));
384 .ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")
385 );
386 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
391 assert_eq!(ensure_body.matches("const VERSION").count(), 1);
387 }
392 }
388
393
@@ -399,9 +404,20 @@ mod tests {
399 };
404 };
400 let script = PageScript::new(&config);
405 let script = PageScript::new(&config);
401 assert!(!script.worker_source.contains("__chatsvc"));
406 assert!(!script.worker_source.contains("__chatsvc"));
402 assert!(script.worker_source.contains("const GLOBAL_NAME = '__callingTrouter';"));
407 assert!(
403 assert!(script.worker_source.contains("const FORWARD_CALLBACKS = true;"));
408 script
404 assert_eq!(script.stop_expression(), "window.__callingTrouter ? window.__callingTrouter.stop() : null");
409 .worker_source
410 .contains("const GLOBAL_NAME = '__callingTrouter';")
411 );
412 assert!(
413 script
414 .worker_source
415 .contains("const FORWARD_CALLBACKS = true;")
416 );
417 assert_eq!(
418 script.stop_expression(),
419 "window.__callingTrouter ? window.__callingTrouter.stop() : null"
420 );
405 let default_script = PageScript::new(&RealtimeConfig::default());
421 let default_script = PageScript::new(&RealtimeConfig::default());
406 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
422 assert!(default_script.worker_source.contains(FORWARD_CALLBACKS_OFF));
407 }
423 }
@@ -416,9 +432,21 @@ mod tests {
416 let quiet = PageScript::new(&RealtimeConfig::default());
432 let quiet = PageScript::new(&RealtimeConfig::default());
417 assert!(quiet.worker_source.contains(REGISTRATION_OFF));
433 assert!(quiet.worker_source.contains(REGISTRATION_OFF));
418 for script in [ringable, quiet] {
434 for script in [ringable, quiet] {
419 assert!(script.worker_source.contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}"));
435 assert!(
420 assert!(script.worker_source.contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}"));
436 script
421 assert!(script.worker_source.contains("RINGABLE ? {productContext: ''} : {}"));
437 .worker_source
438 .contains("{appId: 'SkypeSpacesWeb', templateKey: 'SkypeSpacesWeb_2.6'}")
439 );
440 assert!(
441 script
442 .worker_source
443 .contains("{appId: 'TeamsCDLWebWorker', templateKey: 'TeamsCDLWebWorker_2.6'}")
444 );
445 assert!(
446 script
447 .worker_source
448 .contains("RINGABLE ? {productContext: ''} : {}")
449 );
422 }
450 }
423 }
451 }
424}
452}
crates/chatsvc/src/recap.rs +12 −14
@@ -344,10 +344,7 @@ impl<'a> Recap<'a> {
344 344 }
345 345 Err(error) => return Err(error),
346 346 };
347 let Some(report_id) = reports
348 .pointer("/value/0/id")
349 .and_then(Value::as_str)
350 else {
347 let Some(report_id) = reports.pointer("/value/0/id").and_then(Value::as_str) else {
351 348 return Ok(Attendance::TurnedOff);
352 349 };
353 350 let report = self
@@ -386,7 +383,9 @@ fn item_url(site: &str, item: &Value) -> Option<String> {
386 383 .pointer("/parentReference/driveId")
387 384 .and_then(Value::as_str)?;
388 385 let item_id = item.get("id").and_then(Value::as_str)?;
389 Some(format!("{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"))
386 Some(format!(
387 "{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"
388 ))
390 389 }
391 390
392 391 fn decode_binary(body: &Value) -> Option<Vec<u8>> {
@@ -443,7 +442,8 @@ pub fn parse_audio_only_names(chatsvc_messages_json: &Value) -> HashSet<String>
443 442 .into_iter()
444 443 .flatten()
445 444 .filter(|message| {
446 message.get("messagetype").and_then(Value::as_str) == Some("RichText/Media_CallRecording")
445 message.get("messagetype").and_then(Value::as_str)
446 == Some("RichText/Media_CallRecording")
447 447 })
448 448 .filter_map(|message| message.get("content").and_then(Value::as_str))
449 449 .filter(|content| content.contains(AUDIO_ONLY_MARKER))
@@ -505,9 +505,7 @@ pub fn parse_iso_duration(text: &str) -> Option<u64> {
505 505 }
506 506
507 507 pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {
508 let stamp = listing_json
509 .pointer("/fields/_ExpirationDate")?
510 .as_str()?;
508 let stamp = listing_json.pointer("/fields/_ExpirationDate")?.as_str()?;
511 509 DateTime::parse_from_rfc3339(stamp)
512 510 .ok()
513 511 .map(|stamp| stamp.with_timezone(&Utc))
@@ -589,10 +587,7 @@ mod tests {
589 587 use super::*;
590 588
591 589 fn fixture(name: &str) -> Value {
592 let path = format!(
593 "{}/tests/fixtures/recap/{name}",
594 env!("CARGO_MANIFEST_DIR")
595 );
590 let path = format!("{}/tests/fixtures/recap/{name}", env!("CARGO_MANIFEST_DIR"));
596 591 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
597 592 }
598 593
@@ -602,7 +597,10 @@ mod tests {
602 597 assert_eq!(occurrences.len(), 2);
603 598 assert_eq!(occurrences[0].message_id, "2002");
604 599 assert_eq!(occurrences[0].duration_seconds, Some(1832));
605 assert_eq!(occurrences[0].organizer_id.as_deref(), Some("user-organizer"));
600 assert_eq!(
601 occurrences[0].organizer_id.as_deref(),
602 Some("user-organizer")
603 );
606 604 assert_eq!(occurrences[1].message_id, "2001");
607 605 assert_eq!(occurrences[1].duration_seconds, None);
608 606 }
@@ -344,10 +344,7 @@ impl<'a> Recap<'a> {
344 }
344 }
345 Err(error) => return Err(error),
345 Err(error) => return Err(error),
346 };
346 };
347 let Some(report_id) = reports
347 let Some(report_id) = reports.pointer("/value/0/id").and_then(Value::as_str) else {
348 .pointer("/value/0/id")
349 .and_then(Value::as_str)
350 else {
351 return Ok(Attendance::TurnedOff);
348 return Ok(Attendance::TurnedOff);
352 };
349 };
353 let report = self
350 let report = self
@@ -386,7 +383,9 @@ fn item_url(site: &str, item: &Value) -> Option<String> {
386 .pointer("/parentReference/driveId")
383 .pointer("/parentReference/driveId")
387 .and_then(Value::as_str)?;
384 .and_then(Value::as_str)?;
388 let item_id = item.get("id").and_then(Value::as_str)?;
385 let item_id = item.get("id").and_then(Value::as_str)?;
389 Some(format!("{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"))
386 Some(format!(
387 "{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"
388 ))
390}
389}
391
390
392fn decode_binary(body: &Value) -> Option<Vec<u8>> {
391fn decode_binary(body: &Value) -> Option<Vec<u8>> {
@@ -443,7 +442,8 @@ pub fn parse_audio_only_names(chatsvc_messages_json: &Value) -> HashSet<String>
443 .into_iter()
442 .into_iter()
444 .flatten()
443 .flatten()
445 .filter(|message| {
444 .filter(|message| {
446 message.get("messagetype").and_then(Value::as_str) == Some("RichText/Media_CallRecording")
445 message.get("messagetype").and_then(Value::as_str)
446 == Some("RichText/Media_CallRecording")
447 })
447 })
448 .filter_map(|message| message.get("content").and_then(Value::as_str))
448 .filter_map(|message| message.get("content").and_then(Value::as_str))
449 .filter(|content| content.contains(AUDIO_ONLY_MARKER))
449 .filter(|content| content.contains(AUDIO_ONLY_MARKER))
@@ -505,9 +505,7 @@ pub fn parse_iso_duration(text: &str) -> Option<u64> {
505}
505}
506
506
507pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {
507pub fn parse_expiration(listing_json: &Value) -> Option<DateTime<Utc>> {
508 let stamp = listing_json
508 let stamp = listing_json.pointer("/fields/_ExpirationDate")?.as_str()?;
509 .pointer("/fields/_ExpirationDate")?
510 .as_str()?;
511 DateTime::parse_from_rfc3339(stamp)
509 DateTime::parse_from_rfc3339(stamp)
512 .ok()
510 .ok()
513 .map(|stamp| stamp.with_timezone(&Utc))
511 .map(|stamp| stamp.with_timezone(&Utc))
@@ -589,10 +587,7 @@ mod tests {
589 use super::*;
587 use super::*;
590
588
591 fn fixture(name: &str) -> Value {
589 fn fixture(name: &str) -> Value {
592 let path = format!(
590 let path = format!("{}/tests/fixtures/recap/{name}", env!("CARGO_MANIFEST_DIR"));
593 "{}/tests/fixtures/recap/{name}",
594 env!("CARGO_MANIFEST_DIR")
595 );
596 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
591 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
597 }
592 }
598
593
@@ -602,7 +597,10 @@ mod tests {
602 assert_eq!(occurrences.len(), 2);
597 assert_eq!(occurrences.len(), 2);
603 assert_eq!(occurrences[0].message_id, "2002");
598 assert_eq!(occurrences[0].message_id, "2002");
604 assert_eq!(occurrences[0].duration_seconds, Some(1832));
599 assert_eq!(occurrences[0].duration_seconds, Some(1832));
605 assert_eq!(occurrences[0].organizer_id.as_deref(), Some("user-organizer"));
600 assert_eq!(
601 occurrences[0].organizer_id.as_deref(),
602 Some("user-organizer")
603 );
606 assert_eq!(occurrences[1].message_id, "2001");
604 assert_eq!(occurrences[1].message_id, "2001");
607 assert_eq!(occurrences[1].duration_seconds, None);
605 assert_eq!(occurrences[1].duration_seconds, None);
608 }
606 }
crates/chatsvc/src/saved.rs +1 −5
@@ -24,11 +24,7 @@ pub struct SavedMessage {
24 24 }
25 25
26 26 fn text_or_number(value: &Value, key: &str) -> Option<String> {
27 match value.get(key)? {
28 Value::String(text) if !text.is_empty() => Some(text.clone()),
29 Value::Number(number) => Some(number.to_string()),
30 _ => None,
31 }
27 crate::json_id::id_text(value.get(key)?)
32 28 }
33 29
34 30 fn activity_of(message: &Value) -> Option<Value> {
@@ -24,11 +24,7 @@ pub struct SavedMessage {
24}
24}
25
25
26fn text_or_number(value: &Value, key: &str) -> Option<String> {
26fn text_or_number(value: &Value, key: &str) -> Option<String> {
27 match value.get(key)? {
27 crate::json_id::id_text(value.get(key)?)
28 Value::String(text) if !text.is_empty() => Some(text.clone()),
29 Value::Number(number) => Some(number.to_string()),
30 _ => None,
31 }
32}
28}
33
29
34fn activity_of(message: &Value) -> Option<Value> {
30fn activity_of(message: &Value) -> Option<Value> {
crates/chatsvc/src/settings.rs +21 −5
@@ -12,6 +12,7 @@ const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12 12 const MAX_SKIN_TONE: u8 = 5;
13 13 const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
14 14 const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
15 const ADAPTIVE_RAIL_FIELD: &str = "hasUserEnabledAdaptiveRailForDesktop";
15 16 const MUTED_DEFAULT: bool = false;
16 17 const MEETING_DEFAULT: bool = false;
17 18
@@ -34,6 +35,7 @@ impl ChatSection {
34 35 pub struct ChatSectionSettings {
35 36 pub muted: Option<bool>,
36 37 pub meeting: Option<bool>,
38 pub adaptive_rail: Option<bool>,
37 39 }
38 40
39 41 impl ChatSectionSettings {
@@ -44,6 +46,10 @@ impl ChatSectionSettings {
44 46 }
45 47 }
46 48
49 pub fn adaptive_rail(&self) -> bool {
50 self.adaptive_rail.unwrap_or(false)
51 }
52
47 53 pub fn set(&mut self, section: ChatSection, enabled: bool) {
48 54 match section {
49 55 ChatSection::Muted => self.muted = Some(enabled),
@@ -128,6 +134,7 @@ pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {
128 134 ChatSectionSettings {
129 135 muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),
130 136 meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),
137 adaptive_rail: settings.get(ADAPTIVE_RAIL_FIELD).and_then(Value::as_bool),
131 138 }
132 139 }
133 140
@@ -210,8 +217,14 @@ mod tests {
210 217
211 218 #[test]
212 219 fn skin_tone_is_read_from_the_string_property() {
213 assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})), Some(2));
214 assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})), None);
220 assert_eq!(
221 parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})),
222 Some(2)
223 );
224 assert_eq!(
225 parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})),
226 None
227 );
215 228 assert_eq!(parse_skin_tone(&json!({})), None);
216 229 }
217 230
@@ -221,15 +234,17 @@ mod tests {
221 234 assert_eq!(parsed, ChatSectionSettings::default());
222 235 assert!(!parsed.enabled(ChatSection::Muted));
223 236 assert!(!parsed.enabled(ChatSection::Meeting));
237 assert!(!parsed.adaptive_rail());
224 238 }
225 239
226 240 #[test]
227 fn reads_both_flags_from_the_json_string() {
241 fn reads_every_flag_from_the_json_string() {
228 242 let parsed = parse_chat_sections(&properties(
229 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true}"#,
243 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true,"hasUserEnabledAdaptiveRailForDesktop":true}"#,
230 244 ));
231 245 assert!(!parsed.enabled(ChatSection::Muted));
232 246 assert!(parsed.enabled(ChatSection::Meeting));
247 assert!(parsed.adaptive_rail());
233 248 }
234 249
235 250 #[test]
@@ -275,7 +290,8 @@ mod tests {
275 290 parse_chat_sections(&json!({SETTINGS_KEY: merged})),
276 291 ChatSectionSettings {
277 292 muted: Some(false),
278 meeting: Some(true)
293 meeting: Some(true),
294 adaptive_rail: None,
279 295 }
280 296 );
281 297 }
@@ -12,6 +12,7 @@ const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12const MAX_SKIN_TONE: u8 = 5;
12const MAX_SKIN_TONE: u8 = 5;
13const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
13const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
14const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
14const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
15const ADAPTIVE_RAIL_FIELD: &str = "hasUserEnabledAdaptiveRailForDesktop";
15const MUTED_DEFAULT: bool = false;
16const MUTED_DEFAULT: bool = false;
16const MEETING_DEFAULT: bool = false;
17const MEETING_DEFAULT: bool = false;
17
18
@@ -34,6 +35,7 @@ impl ChatSection {
34pub struct ChatSectionSettings {
35pub struct ChatSectionSettings {
35 pub muted: Option<bool>,
36 pub muted: Option<bool>,
36 pub meeting: Option<bool>,
37 pub meeting: Option<bool>,
38 pub adaptive_rail: Option<bool>,
37}
39}
38
40
39impl ChatSectionSettings {
41impl ChatSectionSettings {
@@ -44,6 +46,10 @@ impl ChatSectionSettings {
44 }
46 }
45 }
47 }
46
48
49 pub fn adaptive_rail(&self) -> bool {
50 self.adaptive_rail.unwrap_or(false)
51 }
52
47 pub fn set(&mut self, section: ChatSection, enabled: bool) {
53 pub fn set(&mut self, section: ChatSection, enabled: bool) {
48 match section {
54 match section {
49 ChatSection::Muted => self.muted = Some(enabled),
55 ChatSection::Muted => self.muted = Some(enabled),
@@ -128,6 +134,7 @@ pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {
128 ChatSectionSettings {
134 ChatSectionSettings {
129 muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),
135 muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),
130 meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),
136 meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),
137 adaptive_rail: settings.get(ADAPTIVE_RAIL_FIELD).and_then(Value::as_bool),
131 }
138 }
132}
139}
133
140
@@ -210,8 +217,14 @@ mod tests {
210
217
211 #[test]
218 #[test]
212 fn skin_tone_is_read_from_the_string_property() {
219 fn skin_tone_is_read_from_the_string_property() {
213 assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})), Some(2));
220 assert_eq!(
214 assert_eq!(parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})), None);
221 parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})),
222 Some(2)
223 );
224 assert_eq!(
225 parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})),
226 None
227 );
215 assert_eq!(parse_skin_tone(&json!({})), None);
228 assert_eq!(parse_skin_tone(&json!({})), None);
216 }
229 }
217
230
@@ -221,15 +234,17 @@ mod tests {
221 assert_eq!(parsed, ChatSectionSettings::default());
234 assert_eq!(parsed, ChatSectionSettings::default());
222 assert!(!parsed.enabled(ChatSection::Muted));
235 assert!(!parsed.enabled(ChatSection::Muted));
223 assert!(!parsed.enabled(ChatSection::Meeting));
236 assert!(!parsed.enabled(ChatSection::Meeting));
237 assert!(!parsed.adaptive_rail());
224 }
238 }
225
239
226 #[test]
240 #[test]
227 fn reads_both_flags_from_the_json_string() {
241 fn reads_every_flag_from_the_json_string() {
228 let parsed = parse_chat_sections(&properties(
242 let parsed = parse_chat_sections(&properties(
229 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true}"#,
243 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true,"hasUserEnabledAdaptiveRailForDesktop":true}"#,
230 ));
244 ));
231 assert!(!parsed.enabled(ChatSection::Muted));
245 assert!(!parsed.enabled(ChatSection::Muted));
232 assert!(parsed.enabled(ChatSection::Meeting));
246 assert!(parsed.enabled(ChatSection::Meeting));
247 assert!(parsed.adaptive_rail());
233 }
248 }
234
249
235 #[test]
250 #[test]
@@ -275,7 +290,8 @@ mod tests {
275 parse_chat_sections(&json!({SETTINGS_KEY: merged})),
290 parse_chat_sections(&json!({SETTINGS_KEY: merged})),
276 ChatSectionSettings {
291 ChatSectionSettings {
277 muted: Some(false),
292 muted: Some(false),
278 meeting: Some(true)
293 meeting: Some(true),
294 adaptive_rail: None,
279 }
295 }
280 );
296 );
281 }
297 }
crates/chatsvc/src/sound_settings.rs +15 −6
@@ -148,7 +148,11 @@ pub fn merge_sound_settings(
148 148 ));
149 149 }
150 150 if previous.urgent_sound != updated.urgent_sound {
151 changes.push((TOAST_SETTINGS, URGENT_SOUND, switch_value(updated.urgent_sound)));
151 changes.push((
152 TOAST_SETTINGS,
153 URGENT_SOUND,
154 switch_value(updated.urgent_sound),
155 ));
152 156 }
153 157 if previous.urgent_sound_type != updated.urgent_sound_type {
154 158 changes.push((
@@ -200,8 +204,10 @@ pub fn aggregate_read_body() -> Value {
200 204 json!({"voiceAdminSettings": true})
201 205 }
202 206
203 pub struct SoundSettingsClient<P: MessageTransport = SessionMessageTransport, M: CsaTransport = SessionTransport>
204 {
207 pub struct SoundSettingsClient<
208 P: MessageTransport = SessionMessageTransport,
209 M: CsaTransport = SessionTransport,
210 > {
205 211 properties: UserSettings<P>,
206 212 middle_tier: M,
207 213 middle_tier_url: String,
@@ -356,9 +362,12 @@ mod tests {
356 362 sound_when_busy: false,
357 363 ..previous.clone()
358 364 };
359 let merged: Value =
360 serde_json::from_str(&merge_sound_settings(&properties(personal), &previous, &updated))
361 .unwrap();
365 let merged: Value = serde_json::from_str(&merge_sound_settings(
366 &properties(personal),
367 &previous,
368 &updated,
369 ))
370 .unwrap();
362 371 assert_eq!(
363 372 merged,
364 373 json!({
@@ -148,7 +148,11 @@ pub fn merge_sound_settings(
148 ));
148 ));
149 }
149 }
150 if previous.urgent_sound != updated.urgent_sound {
150 if previous.urgent_sound != updated.urgent_sound {
151 changes.push((TOAST_SETTINGS, URGENT_SOUND, switch_value(updated.urgent_sound)));
151 changes.push((
152 TOAST_SETTINGS,
153 URGENT_SOUND,
154 switch_value(updated.urgent_sound),
155 ));
152 }
156 }
153 if previous.urgent_sound_type != updated.urgent_sound_type {
157 if previous.urgent_sound_type != updated.urgent_sound_type {
154 changes.push((
158 changes.push((
@@ -200,8 +204,10 @@ pub fn aggregate_read_body() -> Value {
200 json!({"voiceAdminSettings": true})
204 json!({"voiceAdminSettings": true})
201}
205}
202
206
203pub struct SoundSettingsClient<P: MessageTransport = SessionMessageTransport, M: CsaTransport = SessionTransport>
207pub struct SoundSettingsClient<
204{
208 P: MessageTransport = SessionMessageTransport,
209 M: CsaTransport = SessionTransport,
210> {
205 properties: UserSettings<P>,
211 properties: UserSettings<P>,
206 middle_tier: M,
212 middle_tier: M,
207 middle_tier_url: String,
213 middle_tier_url: String,
@@ -356,9 +362,12 @@ mod tests {
356 sound_when_busy: false,
362 sound_when_busy: false,
357 ..previous.clone()
363 ..previous.clone()
358 };
364 };
359 let merged: Value =
365 let merged: Value = serde_json::from_str(&merge_sound_settings(
360 serde_json::from_str(&merge_sound_settings(&properties(personal), &previous, &updated))
366 &properties(personal),
361 .unwrap();
367 &previous,
368 &updated,
369 ))
370 .unwrap();
362 assert_eq!(
371 assert_eq!(
363 merged,
372 merged,
364 json!({
373 json!({
crates/chatsvc/src/sounds.rs +4 −1
@@ -315,7 +315,10 @@ mod tests {
315 315 format!("{}.mp3", ringtone.name().to_lowercase())
316 316 );
317 317 }
318 assert_eq!(Ringtone::from_name("wishgranted"), Some(Ringtone::WishGranted));
318 assert_eq!(
319 Ringtone::from_name("wishgranted"),
320 Some(Ringtone::WishGranted)
321 );
319 322 assert_eq!(Ringtone::from_name("Chime"), None);
320 323 assert_eq!(Ringtone::Ring.label(), "Default");
321 324 }
@@ -315,7 +315,10 @@ mod tests {
315 format!("{}.mp3", ringtone.name().to_lowercase())
315 format!("{}.mp3", ringtone.name().to_lowercase())
316 );
316 );
317 }
317 }
318 assert_eq!(Ringtone::from_name("wishgranted"), Some(Ringtone::WishGranted));
318 assert_eq!(
319 Ringtone::from_name("wishgranted"),
320 Some(Ringtone::WishGranted)
321 );
319 assert_eq!(Ringtone::from_name("Chime"), None);
322 assert_eq!(Ringtone::from_name("Chime"), None);
320 assert_eq!(Ringtone::Ring.label(), "Default");
323 assert_eq!(Ringtone::Ring.label(), "Default");
321 }
324 }
crates/chatsvc/src/window.rs +1 −5
@@ -38,11 +38,7 @@ fn is_user_message(message: &Value) -> bool {
38 38 }
39 39
40 40 fn message_id(message: &Value) -> Option<String> {
41 match message.get("id")? {
42 Value::String(text) if !text.is_empty() => Some(text.clone()),
43 Value::Number(number) => Some(number.to_string()),
44 _ => None,
45 }
41 crate::json_id::id_text(message.get("id")?)
46 42 }
47 43
48 44 fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
@@ -38,11 +38,7 @@ fn is_user_message(message: &Value) -> bool {
38}
38}
39
39
40fn message_id(message: &Value) -> Option<String> {
40fn message_id(message: &Value) -> Option<String> {
41 match message.get("id")? {
41 crate::json_id::id_text(message.get("id")?)
42 Value::String(text) if !text.is_empty() => Some(text.clone()),
43 Value::Number(number) => Some(number.to_string()),
44 _ => None,
45 }
46}
42}
47
43
48fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
44fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
crates/core/src/folders.rs +3 −0
@@ -383,6 +383,7 @@ const KIND_MEETING: &str = "MeetingChats";
383 383 const KIND_MUTED: &str = "MutedChats";
384 384 const META_MUTED_SECTION: &str = "chat_section_muted";
385 385 const META_MEETING_SECTION: &str = "chat_section_meeting";
386 const META_ADAPTIVE_RAIL: &str = "adaptive_rail";
386 387
387 388 fn to_record(folder: &ChatFolder) -> FolderRecord {
388 389 FolderRecord {
@@ -428,6 +429,7 @@ pub fn stored_section_settings(store: &Store) -> ChatSectionSettings {
428 429 ChatSectionSettings {
429 430 muted: read(META_MUTED_SECTION),
430 431 meeting: read(META_MEETING_SECTION),
432 adaptive_rail: read(META_ADAPTIVE_RAIL),
431 433 }
432 434 }
433 435
@@ -435,6 +437,7 @@ pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) ->
435 437 for (key, value) in [
436 438 (META_MUTED_SECTION, settings.muted),
437 439 (META_MEETING_SECTION, settings.meeting),
440 (META_ADAPTIVE_RAIL, settings.adaptive_rail),
438 441 ] {
439 442 let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();
440 443 store.set_meta(key, &text)?;
@@ -383,6 +383,7 @@ const KIND_MEETING: &str = "MeetingChats";
383const KIND_MUTED: &str = "MutedChats";
383const KIND_MUTED: &str = "MutedChats";
384const META_MUTED_SECTION: &str = "chat_section_muted";
384const META_MUTED_SECTION: &str = "chat_section_muted";
385const META_MEETING_SECTION: &str = "chat_section_meeting";
385const META_MEETING_SECTION: &str = "chat_section_meeting";
386const META_ADAPTIVE_RAIL: &str = "adaptive_rail";
386
387
387fn to_record(folder: &ChatFolder) -> FolderRecord {
388fn to_record(folder: &ChatFolder) -> FolderRecord {
388 FolderRecord {
389 FolderRecord {
@@ -428,6 +429,7 @@ pub fn stored_section_settings(store: &Store) -> ChatSectionSettings {
428 ChatSectionSettings {
429 ChatSectionSettings {
429 muted: read(META_MUTED_SECTION),
430 muted: read(META_MUTED_SECTION),
430 meeting: read(META_MEETING_SECTION),
431 meeting: read(META_MEETING_SECTION),
432 adaptive_rail: read(META_ADAPTIVE_RAIL),
431 }
433 }
432}
434}
433
435
@@ -435,6 +437,7 @@ pub fn store_section_settings(store: &Store, settings: &ChatSectionSettings) ->
435 for (key, value) in [
437 for (key, value) in [
436 (META_MUTED_SECTION, settings.muted),
438 (META_MUTED_SECTION, settings.muted),
437 (META_MEETING_SECTION, settings.meeting),
439 (META_MEETING_SECTION, settings.meeting),
440 (META_ADAPTIVE_RAIL, settings.adaptive_rail),
438 ] {
441 ] {
439 let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();
442 let text = value.map(|enabled| enabled.to_string()).unwrap_or_default();
440 store.set_meta(key, &text)?;
443 store.set_meta(key, &text)?;
crates/core/tests/engine.rs +2 −0
@@ -3106,6 +3106,7 @@ async fn collapse_and_section_settings_go_through_the_source() {
3106 3106 Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings {
3107 3107 muted: Some(false),
3108 3108 meeting: Some(true),
3109 adaptive_rail: Some(true),
3109 3110 };
3110 3111 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3111 3112 let mut events = engine.subscribe();
@@ -3117,6 +3118,7 @@ async fn collapse_and_section_settings_go_through_the_source() {
3117 3118 ChatSectionSettings {
3118 3119 muted: Some(false),
3119 3120 meeting: Some(true),
3121 adaptive_rail: Some(true),
3120 3122 }
3121 3123 );
3122 3124
@@ -3106,6 +3106,7 @@ async fn collapse_and_section_settings_go_through_the_source() {
3106 Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings {
3106 Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings {
3107 muted: Some(false),
3107 muted: Some(false),
3108 meeting: Some(true),
3108 meeting: Some(true),
3109 adaptive_rail: Some(true),
3109 };
3110 };
3110 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3111 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3111 let mut events = engine.subscribe();
3112 let mut events = engine.subscribe();
@@ -3117,6 +3118,7 @@ async fn collapse_and_section_settings_go_through_the_source() {
3117 ChatSectionSettings {
3118 ChatSectionSettings {
3118 muted: Some(false),
3119 muted: Some(false),
3119 meeting: Some(true),
3120 meeting: Some(true),
3121 adaptive_rail: Some(true),
3120 }
3122 }
3121 );
3123 );
3122
3124