BlueGit

ict rusty-teams

feat(calls): upcoming meetings with join and Meet now in the Calls tab, virtualized call history

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-11 · 7 weeks ago

Hash
1a10a5a528ed053e909e4461961941fc37329f19
Parent
ff739ffa
16 files changed +1391 −37
crates/app/src/app_state.rs +9 −0
@@ -105,6 +105,9 @@ pub struct AppState {
105 105 pub scheduled_polling: bool,
106 106 pub saved: SavedSet,
107 107 pub call_history: Vec<teams_core::CallLogEntry>,
108 pub calendar_events: Vec<chatsvc::CalendarEvent>,
109 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
110 pub calls_list: crate::call::CallsList,
108 111 pub pins: HashMap<String, Vec<PinnedMessage>>,
109 112 pub forward_request: Option<ForwardSource>,
110 113 pub own_status: PresenceStatus,
@@ -200,6 +203,9 @@ impl AppState {
200 203 scheduled_polling: false,
201 204 saved: SavedSet::default(),
202 205 call_history: Vec::new(),
206 calendar_events: Vec::new(),
207 calendar_nudge: None,
208 calls_list: crate::call::CallsList::default(),
203 209 pins: HashMap::new(),
204 210 forward_request: None,
205 211 own_status: PresenceStatus::default(),
@@ -714,6 +720,7 @@ impl AppState {
714 720 self.sidebar = sidebar;
715 721 self.apply_bot_titles();
716 722 }
723 self.calls_list.invalidate();
717 724 if !self.mode.demo {
718 725 self.reload_directory();
719 726 }
@@ -728,6 +735,8 @@ impl AppState {
728 735 cx.emit(AppEvent::Status);
729 736 }
730 737 BackendEvent::Calls(launcher) => self.call_launcher = Some(launcher),
738 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
739 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
731 740 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
732 741 BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),
733 742 BackendEvent::Engine(engine) => {
@@ -105,6 +105,9 @@ pub struct AppState {
105 pub scheduled_polling: bool,
105 pub scheduled_polling: bool,
106 pub saved: SavedSet,
106 pub saved: SavedSet,
107 pub call_history: Vec<teams_core::CallLogEntry>,
107 pub call_history: Vec<teams_core::CallLogEntry>,
108 pub calendar_events: Vec<chatsvc::CalendarEvent>,
109 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
110 pub calls_list: crate::call::CallsList,
108 pub pins: HashMap<String, Vec<PinnedMessage>>,
111 pub pins: HashMap<String, Vec<PinnedMessage>>,
109 pub forward_request: Option<ForwardSource>,
112 pub forward_request: Option<ForwardSource>,
110 pub own_status: PresenceStatus,
113 pub own_status: PresenceStatus,
@@ -200,6 +203,9 @@ impl AppState {
200 scheduled_polling: false,
203 scheduled_polling: false,
201 saved: SavedSet::default(),
204 saved: SavedSet::default(),
202 call_history: Vec::new(),
205 call_history: Vec::new(),
206 calendar_events: Vec::new(),
207 calendar_nudge: None,
208 calls_list: crate::call::CallsList::default(),
203 pins: HashMap::new(),
209 pins: HashMap::new(),
204 forward_request: None,
210 forward_request: None,
205 own_status: PresenceStatus::default(),
211 own_status: PresenceStatus::default(),
@@ -714,6 +720,7 @@ impl AppState {
714 self.sidebar = sidebar;
720 self.sidebar = sidebar;
715 self.apply_bot_titles();
721 self.apply_bot_titles();
716 }
722 }
723 self.calls_list.invalidate();
717 if !self.mode.demo {
724 if !self.mode.demo {
718 self.reload_directory();
725 self.reload_directory();
719 }
726 }
@@ -728,6 +735,8 @@ impl AppState {
728 cx.emit(AppEvent::Status);
735 cx.emit(AppEvent::Status);
729 }
736 }
730 BackendEvent::Calls(launcher) => self.call_launcher = Some(launcher),
737 BackendEvent::Calls(launcher) => self.call_launcher = Some(launcher),
738 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
739 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
731 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
740 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
732 BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),
741 BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),
733 BackendEvent::Engine(engine) => {
742 BackendEvent::Engine(engine) => {
crates/app/src/backend.rs +40 −3
@@ -2,15 +2,15 @@ use std::sync::Arc;
2 2 use std::time::Duration;
3 3
4 4 use calling::EngineEvent;
5 use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
6 use chrono::{DateTime, Utc};
5 use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
6 use chrono::{DateTime, Local, Offset, Utc};
7 7 use graph::Graph;
8 8 use session::{Session, SessionConfig, Transport};
9 9 use store::Store;
10 10 use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
11 11 use tokio::sync::mpsc;
12 12
13 use crate::call::CallLauncher;
13 use crate::call::{CallLauncher, fetch_window};
14 14
15 15 pub type Engine = SyncEngine<Graph>;
16 16
@@ -18,6 +18,8 @@ const CONNECT_RETRY: Duration = Duration::from_secs(8);
18 18 const REFRESH_INTERVAL: Duration = Duration::from_secs(120);
19 19 const REFRESH_SETTLE: Duration = Duration::from_secs(2);
20 20 const PINS_INTERVAL: Duration = Duration::from_secs(90);
21 const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);
22 const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);
21 23 const REALTIME_RETRY: Duration = Duration::from_secs(15);
22 24 const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
23 25 const MAX_ERROR_CHARS: usize = 120;
@@ -48,6 +50,8 @@ pub enum BackendEvent {
48 50 Connection(ConnectionState),
49 51 Engine(Arc<Engine>),
50 52 Calls(Arc<CallLauncher>),
53 Calendar(Vec<CalendarEvent>),
54 CalendarNudge(mpsc::UnboundedSender<()>),
51 55 Ring(EngineEvent),
52 56 ThreadChanged(String),
53 57 Core(CoreEvent),
@@ -142,6 +146,7 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: b
142 146 events.clone(),
143 147 nudge,
144 148 ));
149 tokio::spawn(calendar_loop(session.clone(), events.clone()));
145 150 tokio::spawn(pins_loop(session, events.clone()));
146 151 tokio::spawn(presence_resubscribe_loop(engine.clone()));
147 152 refresh_loop(engine, events, nudges).await;
@@ -324,6 +329,38 @@ async fn handle_message_event(
324 329 }
325 330 }
326 331
332 async fn calendar_loop(session: Session, events: EventSender) {
333 let calendar = Calendar::new(&session);
334 let (nudge, mut nudges) = mpsc::unbounded_channel();
335 let _ = events.send(BackendEvent::CalendarNudge(nudge));
336 let mut interval = tokio::time::interval(CALENDAR_INTERVAL);
337 let mut last_fetch: Option<tokio::time::Instant> = None;
338 loop {
339 tokio::select! {
340 _ = interval.tick() => {}
341 nudge = nudges.recv() => {
342 if nudge.is_none() {
343 return;
344 }
345 while nudges.try_recv().is_ok() {}
346 if last_fetch.is_some_and(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {
347 continue;
348 }
349 }
350 }
351 last_fetch = Some(tokio::time::Instant::now());
352 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
353 match calendar.calendar_view(start, end).await {
354 Ok(fetched) => {
355 if events.send(BackendEvent::Calendar(fetched)).is_err() {
356 return;
357 }
358 }
359 Err(error) => eprintln!("calls: calendar not loaded: {}", shorten(&error.to_string())),
360 }
361 }
362 }
363
327 364 async fn pins_loop(session: Session, events: EventSender) {
328 365 let pins = Pins::new(&session);
329 366 let mut chat_ids: Vec<String> = Vec::new();
@@ -2,15 +2,15 @@ use std::sync::Arc;
2use std::time::Duration;
2use std::time::Duration;
3
3
4use calling::EngineEvent;
4use calling::EngineEvent;
5use chatsvc::{EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
5use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeEvent, StatusKind, TypingEvent};
6use chrono::{DateTime, Utc};
6use chrono::{DateTime, Local, Offset, Utc};
7use graph::Graph;
7use graph::Graph;
8use session::{Session, SessionConfig, Transport};
8use session::{Session, SessionConfig, Transport};
9use store::Store;
9use store::Store;
10use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
10use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
11use tokio::sync::mpsc;
11use tokio::sync::mpsc;
12
12
13use crate::call::CallLauncher;
13use crate::call::{CallLauncher, fetch_window};
14
14
15pub type Engine = SyncEngine<Graph>;
15pub type Engine = SyncEngine<Graph>;
16
16
@@ -18,6 +18,8 @@ const CONNECT_RETRY: Duration = Duration::from_secs(8);
18const REFRESH_INTERVAL: Duration = Duration::from_secs(120);
18const REFRESH_INTERVAL: Duration = Duration::from_secs(120);
19const REFRESH_SETTLE: Duration = Duration::from_secs(2);
19const REFRESH_SETTLE: Duration = Duration::from_secs(2);
20const PINS_INTERVAL: Duration = Duration::from_secs(90);
20const PINS_INTERVAL: Duration = Duration::from_secs(90);
21const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);
22const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);
21const REALTIME_RETRY: Duration = Duration::from_secs(15);
23const REALTIME_RETRY: Duration = Duration::from_secs(15);
22const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
24const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
23const MAX_ERROR_CHARS: usize = 120;
25const MAX_ERROR_CHARS: usize = 120;
@@ -48,6 +50,8 @@ pub enum BackendEvent {
48 Connection(ConnectionState),
50 Connection(ConnectionState),
49 Engine(Arc<Engine>),
51 Engine(Arc<Engine>),
50 Calls(Arc<CallLauncher>),
52 Calls(Arc<CallLauncher>),
53 Calendar(Vec<CalendarEvent>),
54 CalendarNudge(mpsc::UnboundedSender<()>),
51 Ring(EngineEvent),
55 Ring(EngineEvent),
52 ThreadChanged(String),
56 ThreadChanged(String),
53 Core(CoreEvent),
57 Core(CoreEvent),
@@ -142,6 +146,7 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: b
142 events.clone(),
146 events.clone(),
143 nudge,
147 nudge,
144 ));
148 ));
149 tokio::spawn(calendar_loop(session.clone(), events.clone()));
145 tokio::spawn(pins_loop(session, events.clone()));
150 tokio::spawn(pins_loop(session, events.clone()));
146 tokio::spawn(presence_resubscribe_loop(engine.clone()));
151 tokio::spawn(presence_resubscribe_loop(engine.clone()));
147 refresh_loop(engine, events, nudges).await;
152 refresh_loop(engine, events, nudges).await;
@@ -324,6 +329,38 @@ async fn handle_message_event(
324 }
329 }
325}
330}
326
331
332async fn calendar_loop(session: Session, events: EventSender) {
333 let calendar = Calendar::new(&session);
334 let (nudge, mut nudges) = mpsc::unbounded_channel();
335 let _ = events.send(BackendEvent::CalendarNudge(nudge));
336 let mut interval = tokio::time::interval(CALENDAR_INTERVAL);
337 let mut last_fetch: Option<tokio::time::Instant> = None;
338 loop {
339 tokio::select! {
340 _ = interval.tick() => {}
341 nudge = nudges.recv() => {
342 if nudge.is_none() {
343 return;
344 }
345 while nudges.try_recv().is_ok() {}
346 if last_fetch.is_some_and(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {
347 continue;
348 }
349 }
350 }
351 last_fetch = Some(tokio::time::Instant::now());
352 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
353 match calendar.calendar_view(start, end).await {
354 Ok(fetched) => {
355 if events.send(BackendEvent::Calendar(fetched)).is_err() {
356 return;
357 }
358 }
359 Err(error) => eprintln!("calls: calendar not loaded: {}", shorten(&error.to_string())),
360 }
361 }
362}
363
327async fn pins_loop(session: Session, events: EventSender) {
364async fn pins_loop(session: Session, events: EventSender) {
328 let pins = Pins::new(&session);
365 let pins = Pins::new(&session);
329 let mut chat_ids: Vec<String> = Vec::new();
366 let mut chat_ids: Vec<String> = Vec::new();
crates/app/src/call/agenda.rs added +347 −0
@@ -0,0 +1,347 @@
1 use chatsvc::{CalendarEvent, ResponseType};
2 use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
3
4 const JOIN_LEAD_MINUTES: i64 = 5;
5 const AGENDA_DAYS: i64 = 7;
6 const ALL_DAY_LABEL: &str = "All day";
7
8 #[derive(Debug, Clone, PartialEq, Eq)]
9 pub struct AgendaRow {
10 pub key: String,
11 pub time_label: String,
12 pub subject: String,
13 pub detail: String,
14 pub all_day: bool,
15 pub join_url: Option<String>,
16 pub thread_id: Option<String>,
17 pub start: DateTime<Utc>,
18 pub end: DateTime<Utc>,
19 }
20
21 #[derive(Debug, Clone, PartialEq, Eq)]
22 pub struct AgendaDay {
23 pub date: NaiveDate,
24 pub label: String,
25 pub rows: Vec<AgendaRow>,
26 }
27
28 pub fn fetch_window(now: DateTime<Utc>, offset: FixedOffset) -> (DateTime<Utc>, DateTime<Utc>) {
29 let midnight = now
30 .with_timezone(&offset)
31 .date_naive()
32 .and_hms_opt(0, 0, 0)
33 .and_then(|local| local.and_local_timezone(offset).single())
34 .map_or(now, |local| local.with_timezone(&Utc));
35 (midnight, midnight + Duration::days(AGENDA_DAYS))
36 }
37
38 pub fn join_available(
39 row_start: DateTime<Utc>,
40 row_end: DateTime<Utc>,
41 now: DateTime<Utc>,
42 ) -> bool {
43 now >= row_start - Duration::minutes(JOIN_LEAD_MINUTES) && now < row_end
44 }
45
46 pub fn rsvp_label(response: ResponseType) -> Option<&'static str> {
47 match response {
48 ResponseType::Organizer | ResponseType::Accepted => None,
49 ResponseType::Tentative => Some("tentative"),
50 ResponseType::Declined => Some("declined"),
51 ResponseType::NotResponded => Some("not answered"),
52 }
53 }
54
55 pub fn day_heading(day: NaiveDate, today: NaiveDate) -> String {
56 if day == today {
57 "Today".to_owned()
58 } else if today.succ_opt() == Some(day) {
59 "Tomorrow".to_owned()
60 } else {
61 day.format("%a, %b %-d").to_string()
62 }
63 }
64
65 fn detail_label(event: &CalendarEvent) -> String {
66 let rsvp = rsvp_label(event.response);
67 match (event.organizer_name.as_deref(), rsvp) {
68 (Some(organizer), Some(rsvp)) => format!("{organizer} \u{b7} {rsvp}"),
69 (Some(organizer), None) => organizer.to_owned(),
70 (None, Some(rsvp)) => rsvp.to_owned(),
71 (None, None) => String::new(),
72 }
73 }
74
75 fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {
76 if event.all_day {
77 return ALL_DAY_LABEL.to_owned();
78 }
79 format!(
80 "{} - {}",
81 event.start.with_timezone(&offset).format("%H:%M"),
82 event.end.with_timezone(&offset).format("%H:%M")
83 )
84 }
85
86 fn agenda_day(event: &CalendarEvent, today: NaiveDate, offset: FixedOffset) -> NaiveDate {
87 let start_day = if event.all_day {
88 event.start.date_naive()
89 } else {
90 event.start.with_timezone(&offset).date_naive()
91 };
92 start_day.max(today)
93 }
94
95 fn agenda_row(event: &CalendarEvent, offset: FixedOffset) -> AgendaRow {
96 AgendaRow {
97 key: event.object_id.clone(),
98 time_label: time_label(event, offset),
99 subject: if event.subject.is_empty() {
100 "(No title)".to_owned()
101 } else {
102 event.subject.clone()
103 },
104 detail: detail_label(event),
105 all_day: event.all_day,
106 join_url: event.join_url.clone().filter(|_| event.online),
107 thread_id: event.thread_id.clone(),
108 start: event.start,
109 end: event.end,
110 }
111 }
112
113 pub fn group_by_day(
114 events: &[CalendarEvent],
115 now: DateTime<Utc>,
116 offset: FixedOffset,
117 ) -> Vec<AgendaDay> {
118 let today = now.with_timezone(&offset).date_naive();
119 let last_day = today + Duration::days(AGENDA_DAYS - 1);
120 let mut placed: Vec<(NaiveDate, &CalendarEvent)> = events
121 .iter()
122 .filter(|event| !event.cancelled && event.end > now)
123 .map(|event| (agenda_day(event, today, offset), event))
124 .filter(|(day, _)| *day <= last_day)
125 .collect();
126 placed.sort_by_key(|(day, event)| (*day, !event.all_day, event.start, event.end));
127 let mut days: Vec<AgendaDay> = Vec::new();
128 for (date, event) in placed {
129 if days.last().is_none_or(|day| day.date != date) {
130 days.push(AgendaDay {
131 date,
132 label: day_heading(date, today),
133 rows: Vec::new(),
134 });
135 }
136 if let Some(day) = days.last_mut() {
137 day.rows.push(agenda_row(event, offset));
138 }
139 }
140 days
141 }
142
143 pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
144 let event = |id: &str,
145 subject: &str,
146 minutes_from_now: i64,
147 length_minutes: i64,
148 organizer: &str,
149 response: ResponseType| CalendarEvent {
150 object_id: id.to_owned(),
151 subject: subject.to_owned(),
152 start: now + Duration::minutes(minutes_from_now),
153 end: now + Duration::minutes(minutes_from_now + length_minutes),
154 all_day: false,
155 cancelled: false,
156 online: true,
157 join_url: Some(format!(
158 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_{id}%40thread.v2/0"
159 )),
160 thread_id: None,
161 organizer_name: Some(organizer.to_owned()),
162 organizer_address: None,
163 response,
164 };
165 vec![
166 event(
167 "demo-event-1",
168 "Team standup",
169 3,
170 15,
171 "Mara Lindqvist",
172 ResponseType::Accepted,
173 ),
174 event(
175 "demo-event-2",
176 "Design review",
177 240,
178 60,
179 "Jonas Ortega",
180 ResponseType::NotResponded,
181 ),
182 event(
183 "demo-event-3",
184 "Planning",
185 1700,
186 45,
187 "Priya Nair",
188 ResponseType::Tentative,
189 ),
190 event(
191 "demo-event-4",
192 "Retro",
193 3200,
194 30,
195 "Mara Lindqvist",
196 ResponseType::Accepted,
197 ),
198 ]
199 }
200
201 #[cfg(test)]
202 mod tests {
203 use chrono::TimeZone;
204
205 use super::*;
206
207 fn utc(day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
208 Utc.with_ymd_and_hms(2026, 10, day, hour, minute, 0)
209 .unwrap()
210 }
211
212 fn zero() -> FixedOffset {
213 FixedOffset::east_opt(0).unwrap()
214 }
215
216 fn event(id: &str, start: DateTime<Utc>, minutes: i64) -> CalendarEvent {
217 CalendarEvent {
218 object_id: id.into(),
219 subject: id.into(),
220 start,
221 end: start + Duration::minutes(minutes),
222 all_day: false,
223 cancelled: false,
224 online: true,
225 join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
226 thread_id: None,
227 organizer_name: Some("Mara".into()),
228 organizer_address: None,
229 response: ResponseType::Accepted,
230 }
231 }
232
233 #[test]
234 fn the_join_window_runs_from_five_minutes_before_start_to_the_end() {
235 let start = utc(12, 9, 0);
236 let end = utc(12, 9, 30);
237 assert!(!join_available(start, end, utc(12, 8, 54)));
238 assert!(join_available(start, end, utc(12, 8, 55)));
239 assert!(join_available(start, end, utc(12, 9, 29)));
240 assert!(!join_available(start, end, utc(12, 9, 30)));
241 }
242
243 #[test]
244 fn rsvp_labels_only_show_when_not_accepted() {
245 assert_eq!(rsvp_label(ResponseType::Accepted), None);
246 assert_eq!(rsvp_label(ResponseType::Organizer), None);
247 assert_eq!(rsvp_label(ResponseType::NotResponded), Some("not answered"));
248 assert_eq!(rsvp_label(ResponseType::Tentative), Some("tentative"));
249 assert_eq!(rsvp_label(ResponseType::Declined), Some("declined"));
250 }
251
252 #[test]
253 fn events_group_by_local_day_with_headings() {
254 let now = utc(12, 8, 0);
255 let events = [
256 event("later", utc(14, 10, 0), 30),
257 event("today", utc(12, 9, 0), 30),
258 event("tomorrow", utc(13, 9, 0), 30),
259 ];
260 let days = group_by_day(&events, now, zero());
261 let labels: Vec<&str> = days.iter().map(|day| day.label.as_str()).collect();
262 assert_eq!(labels, ["Today", "Tomorrow", "Wed, Oct 14"]);
263 assert_eq!(days[0].rows[0].time_label, "09:00 - 09:30");
264 }
265
266 #[test]
267 fn the_offset_moves_late_events_to_the_next_day() {
268 let now = utc(12, 8, 0);
269 let plus_two = FixedOffset::east_opt(2 * 3600).unwrap();
270 let days = group_by_day(&[event("late", utc(12, 23, 0), 30)], now, plus_two);
271 assert_eq!(days[0].label, "Tomorrow");
272 assert_eq!(days[0].rows[0].time_label, "01:00 - 01:30");
273 }
274
275 #[test]
276 fn cancelled_ended_and_out_of_range_events_are_hidden() {
277 let now = utc(12, 8, 0);
278 let cancelled = CalendarEvent {
279 cancelled: true,
280 ..event("cancelled", utc(12, 9, 0), 30)
281 };
282 let events = [
283 cancelled,
284 event("ended", utc(12, 6, 0), 30),
285 event("running", utc(12, 7, 45), 30),
286 event("far", utc(19, 9, 0), 30),
287 event("edge", utc(18, 9, 0), 30),
288 ];
289 let days = group_by_day(&events, now, zero());
290 let keys: Vec<&str> = days
291 .iter()
292 .flat_map(|day| day.rows.iter().map(|row| row.key.as_str()))
293 .collect();
294 assert_eq!(keys, ["running", "edge"]);
295 }
296
297 #[test]
298 fn all_day_events_lead_their_day_without_times() {
299 let now = utc(12, 8, 0);
300 let all_day = CalendarEvent {
301 all_day: true,
302 online: false,
303 join_url: None,
304 ..event("offsite", utc(12, 0, 0), 24 * 60)
305 };
306 let days = group_by_day(&[event("early", utc(12, 8, 30), 30), all_day], now, zero());
307 assert_eq!(days[0].rows[0].key, "offsite");
308 assert_eq!(days[0].rows[0].time_label, "All day");
309 assert_eq!(days[0].rows[1].key, "early");
310 }
311
312 #[test]
313 fn a_running_all_day_event_from_yesterday_shows_today() {
314 let now = utc(12, 8, 0);
315 let all_day = CalendarEvent {
316 all_day: true,
317 ..event("trip", utc(11, 0, 0), 48 * 60)
318 };
319 let days = group_by_day(&[all_day], now, zero());
320 assert_eq!(days[0].label, "Today");
321 }
322
323 #[test]
324 fn rows_carry_organizer_and_rsvp_and_only_online_join_urls() {
325 let now = utc(12, 8, 0);
326 let open = CalendarEvent {
327 response: ResponseType::NotResponded,
328 ..event("open", utc(12, 9, 0), 30)
329 };
330 let offline = CalendarEvent {
331 online: false,
332 ..event("offline", utc(12, 10, 0), 30)
333 };
334 let days = group_by_day(&[open, offline], now, zero());
335 assert_eq!(days[0].rows[0].detail, "Mara \u{b7} not answered");
336 assert!(days[0].rows[0].join_url.is_some());
337 assert_eq!(days[0].rows[1].join_url, None);
338 }
339
340 #[test]
341 fn the_fetch_window_is_seven_days_from_local_midnight() {
342 let plus_two = FixedOffset::east_opt(2 * 3600).unwrap();
343 let (start, end) = fetch_window(utc(12, 8, 0), plus_two);
344 assert_eq!(start, utc(11, 22, 0));
345 assert_eq!(end, utc(18, 22, 0));
346 }
347 }
@@ -0,0 +1,347 @@
1use chatsvc::{CalendarEvent, ResponseType};
2use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
3
4const JOIN_LEAD_MINUTES: i64 = 5;
5const AGENDA_DAYS: i64 = 7;
6const ALL_DAY_LABEL: &str = "All day";
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct AgendaRow {
10 pub key: String,
11 pub time_label: String,
12 pub subject: String,
13 pub detail: String,
14 pub all_day: bool,
15 pub join_url: Option<String>,
16 pub thread_id: Option<String>,
17 pub start: DateTime<Utc>,
18 pub end: DateTime<Utc>,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct AgendaDay {
23 pub date: NaiveDate,
24 pub label: String,
25 pub rows: Vec<AgendaRow>,
26}
27
28pub fn fetch_window(now: DateTime<Utc>, offset: FixedOffset) -> (DateTime<Utc>, DateTime<Utc>) {
29 let midnight = now
30 .with_timezone(&offset)
31 .date_naive()
32 .and_hms_opt(0, 0, 0)
33 .and_then(|local| local.and_local_timezone(offset).single())
34 .map_or(now, |local| local.with_timezone(&Utc));
35 (midnight, midnight + Duration::days(AGENDA_DAYS))
36}
37
38pub fn join_available(
39 row_start: DateTime<Utc>,
40 row_end: DateTime<Utc>,
41 now: DateTime<Utc>,
42) -> bool {
43 now >= row_start - Duration::minutes(JOIN_LEAD_MINUTES) && now < row_end
44}
45
46pub fn rsvp_label(response: ResponseType) -> Option<&'static str> {
47 match response {
48 ResponseType::Organizer | ResponseType::Accepted => None,
49 ResponseType::Tentative => Some("tentative"),
50 ResponseType::Declined => Some("declined"),
51 ResponseType::NotResponded => Some("not answered"),
52 }
53}
54
55pub fn day_heading(day: NaiveDate, today: NaiveDate) -> String {
56 if day == today {
57 "Today".to_owned()
58 } else if today.succ_opt() == Some(day) {
59 "Tomorrow".to_owned()
60 } else {
61 day.format("%a, %b %-d").to_string()
62 }
63}
64
65fn detail_label(event: &CalendarEvent) -> String {
66 let rsvp = rsvp_label(event.response);
67 match (event.organizer_name.as_deref(), rsvp) {
68 (Some(organizer), Some(rsvp)) => format!("{organizer} \u{b7} {rsvp}"),
69 (Some(organizer), None) => organizer.to_owned(),
70 (None, Some(rsvp)) => rsvp.to_owned(),
71 (None, None) => String::new(),
72 }
73}
74
75fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {
76 if event.all_day {
77 return ALL_DAY_LABEL.to_owned();
78 }
79 format!(
80 "{} - {}",
81 event.start.with_timezone(&offset).format("%H:%M"),
82 event.end.with_timezone(&offset).format("%H:%M")
83 )
84}
85
86fn agenda_day(event: &CalendarEvent, today: NaiveDate, offset: FixedOffset) -> NaiveDate {
87 let start_day = if event.all_day {
88 event.start.date_naive()
89 } else {
90 event.start.with_timezone(&offset).date_naive()
91 };
92 start_day.max(today)
93}
94
95fn agenda_row(event: &CalendarEvent, offset: FixedOffset) -> AgendaRow {
96 AgendaRow {
97 key: event.object_id.clone(),
98 time_label: time_label(event, offset),
99 subject: if event.subject.is_empty() {
100 "(No title)".to_owned()
101 } else {
102 event.subject.clone()
103 },
104 detail: detail_label(event),
105 all_day: event.all_day,
106 join_url: event.join_url.clone().filter(|_| event.online),
107 thread_id: event.thread_id.clone(),
108 start: event.start,
109 end: event.end,
110 }
111}
112
113pub fn group_by_day(
114 events: &[CalendarEvent],
115 now: DateTime<Utc>,
116 offset: FixedOffset,
117) -> Vec<AgendaDay> {
118 let today = now.with_timezone(&offset).date_naive();
119 let last_day = today + Duration::days(AGENDA_DAYS - 1);
120 let mut placed: Vec<(NaiveDate, &CalendarEvent)> = events
121 .iter()
122 .filter(|event| !event.cancelled && event.end > now)
123 .map(|event| (agenda_day(event, today, offset), event))
124 .filter(|(day, _)| *day <= last_day)
125 .collect();
126 placed.sort_by_key(|(day, event)| (*day, !event.all_day, event.start, event.end));
127 let mut days: Vec<AgendaDay> = Vec::new();
128 for (date, event) in placed {
129 if days.last().is_none_or(|day| day.date != date) {
130 days.push(AgendaDay {
131 date,
132 label: day_heading(date, today),
133 rows: Vec::new(),
134 });
135 }
136 if let Some(day) = days.last_mut() {
137 day.rows.push(agenda_row(event, offset));
138 }
139 }
140 days
141}
142
143pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
144 let event = |id: &str,
145 subject: &str,
146 minutes_from_now: i64,
147 length_minutes: i64,
148 organizer: &str,
149 response: ResponseType| CalendarEvent {
150 object_id: id.to_owned(),
151 subject: subject.to_owned(),
152 start: now + Duration::minutes(minutes_from_now),
153 end: now + Duration::minutes(minutes_from_now + length_minutes),
154 all_day: false,
155 cancelled: false,
156 online: true,
157 join_url: Some(format!(
158 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_{id}%40thread.v2/0"
159 )),
160 thread_id: None,
161 organizer_name: Some(organizer.to_owned()),
162 organizer_address: None,
163 response,
164 };
165 vec![
166 event(
167 "demo-event-1",
168 "Team standup",
169 3,
170 15,
171 "Mara Lindqvist",
172 ResponseType::Accepted,
173 ),
174 event(
175 "demo-event-2",
176 "Design review",
177 240,
178 60,
179 "Jonas Ortega",
180 ResponseType::NotResponded,
181 ),
182 event(
183 "demo-event-3",
184 "Planning",
185 1700,
186 45,
187 "Priya Nair",
188 ResponseType::Tentative,
189 ),
190 event(
191 "demo-event-4",
192 "Retro",
193 3200,
194 30,
195 "Mara Lindqvist",
196 ResponseType::Accepted,
197 ),
198 ]
199}
200
201#[cfg(test)]
202mod tests {
203 use chrono::TimeZone;
204
205 use super::*;
206
207 fn utc(day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
208 Utc.with_ymd_and_hms(2026, 10, day, hour, minute, 0)
209 .unwrap()
210 }
211
212 fn zero() -> FixedOffset {
213 FixedOffset::east_opt(0).unwrap()
214 }
215
216 fn event(id: &str, start: DateTime<Utc>, minutes: i64) -> CalendarEvent {
217 CalendarEvent {
218 object_id: id.into(),
219 subject: id.into(),
220 start,
221 end: start + Duration::minutes(minutes),
222 all_day: false,
223 cancelled: false,
224 online: true,
225 join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
226 thread_id: None,
227 organizer_name: Some("Mara".into()),
228 organizer_address: None,
229 response: ResponseType::Accepted,
230 }
231 }
232
233 #[test]
234 fn the_join_window_runs_from_five_minutes_before_start_to_the_end() {
235 let start = utc(12, 9, 0);
236 let end = utc(12, 9, 30);
237 assert!(!join_available(start, end, utc(12, 8, 54)));
238 assert!(join_available(start, end, utc(12, 8, 55)));
239 assert!(join_available(start, end, utc(12, 9, 29)));
240 assert!(!join_available(start, end, utc(12, 9, 30)));
241 }
242
243 #[test]
244 fn rsvp_labels_only_show_when_not_accepted() {
245 assert_eq!(rsvp_label(ResponseType::Accepted), None);
246 assert_eq!(rsvp_label(ResponseType::Organizer), None);
247 assert_eq!(rsvp_label(ResponseType::NotResponded), Some("not answered"));
248 assert_eq!(rsvp_label(ResponseType::Tentative), Some("tentative"));
249 assert_eq!(rsvp_label(ResponseType::Declined), Some("declined"));
250 }
251
252 #[test]
253 fn events_group_by_local_day_with_headings() {
254 let now = utc(12, 8, 0);
255 let events = [
256 event("later", utc(14, 10, 0), 30),
257 event("today", utc(12, 9, 0), 30),
258 event("tomorrow", utc(13, 9, 0), 30),
259 ];
260 let days = group_by_day(&events, now, zero());
261 let labels: Vec<&str> = days.iter().map(|day| day.label.as_str()).collect();
262 assert_eq!(labels, ["Today", "Tomorrow", "Wed, Oct 14"]);
263 assert_eq!(days[0].rows[0].time_label, "09:00 - 09:30");
264 }
265
266 #[test]
267 fn the_offset_moves_late_events_to_the_next_day() {
268 let now = utc(12, 8, 0);
269 let plus_two = FixedOffset::east_opt(2 * 3600).unwrap();
270 let days = group_by_day(&[event("late", utc(12, 23, 0), 30)], now, plus_two);
271 assert_eq!(days[0].label, "Tomorrow");
272 assert_eq!(days[0].rows[0].time_label, "01:00 - 01:30");
273 }
274
275 #[test]
276 fn cancelled_ended_and_out_of_range_events_are_hidden() {
277 let now = utc(12, 8, 0);
278 let cancelled = CalendarEvent {
279 cancelled: true,
280 ..event("cancelled", utc(12, 9, 0), 30)
281 };
282 let events = [
283 cancelled,
284 event("ended", utc(12, 6, 0), 30),
285 event("running", utc(12, 7, 45), 30),
286 event("far", utc(19, 9, 0), 30),
287 event("edge", utc(18, 9, 0), 30),
288 ];
289 let days = group_by_day(&events, now, zero());
290 let keys: Vec<&str> = days
291 .iter()
292 .flat_map(|day| day.rows.iter().map(|row| row.key.as_str()))
293 .collect();
294 assert_eq!(keys, ["running", "edge"]);
295 }
296
297 #[test]
298 fn all_day_events_lead_their_day_without_times() {
299 let now = utc(12, 8, 0);
300 let all_day = CalendarEvent {
301 all_day: true,
302 online: false,
303 join_url: None,
304 ..event("offsite", utc(12, 0, 0), 24 * 60)
305 };
306 let days = group_by_day(&[event("early", utc(12, 8, 30), 30), all_day], now, zero());
307 assert_eq!(days[0].rows[0].key, "offsite");
308 assert_eq!(days[0].rows[0].time_label, "All day");
309 assert_eq!(days[0].rows[1].key, "early");
310 }
311
312 #[test]
313 fn a_running_all_day_event_from_yesterday_shows_today() {
314 let now = utc(12, 8, 0);
315 let all_day = CalendarEvent {
316 all_day: true,
317 ..event("trip", utc(11, 0, 0), 48 * 60)
318 };
319 let days = group_by_day(&[all_day], now, zero());
320 assert_eq!(days[0].label, "Today");
321 }
322
323 #[test]
324 fn rows_carry_organizer_and_rsvp_and_only_online_join_urls() {
325 let now = utc(12, 8, 0);
326 let open = CalendarEvent {
327 response: ResponseType::NotResponded,
328 ..event("open", utc(12, 9, 0), 30)
329 };
330 let offline = CalendarEvent {
331 online: false,
332 ..event("offline", utc(12, 10, 0), 30)
333 };
334 let days = group_by_day(&[open, offline], now, zero());
335 assert_eq!(days[0].rows[0].detail, "Mara \u{b7} not answered");
336 assert!(days[0].rows[0].join_url.is_some());
337 assert_eq!(days[0].rows[1].join_url, None);
338 }
339
340 #[test]
341 fn the_fetch_window_is_seven_days_from_local_midnight() {
342 let plus_two = FixedOffset::east_opt(2 * 3600).unwrap();
343 let (start, end) = fetch_window(utc(12, 8, 0), plus_two);
344 assert_eq!(start, utc(11, 22, 0));
345 assert_eq!(end, utc(18, 22, 0));
346 }
347}
crates/app/src/call/calendar.rs added +58 −0
@@ -0,0 +1,58 @@
1 use chatsvc::CalendarEvent;
2 use chrono::{Local, Offset, Utc};
3 use gpui_kit::Context;
4
5 use super::agenda::{AgendaRow, demo_events};
6 use crate::app_state::{AppEvent, AppState, Selection};
7 use crate::notify::selection_for;
8
9 const NO_MEETING_CHAT_NOTICE: &str = "This meeting chat is not available";
10
11 impl AppState {
12 pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {
13 self.calendar_events = events;
14 self.calls_list.invalidate();
15 cx.emit(AppEvent::CallHistory);
16 cx.notify();
17 }
18
19 pub fn refresh_calendar(&mut self, cx: &mut Context<Self>) {
20 if self.mode.demo {
21 self.apply_calendar(demo_events(Utc::now()), cx);
22 return;
23 }
24 if let Some(nudge) = &self.calendar_nudge {
25 let _ = nudge.send(());
26 }
27 }
28
29 pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {
30 let now = Utc::now();
31 let offset = Local::now().offset().fix();
32 self.calls_list.rebuild(
33 &self.call_history,
34 &self.sidebar.chats,
35 &self.calendar_events,
36 now,
37 offset,
38 );
39 cx.emit(AppEvent::CallHistory);
40 cx.notify();
41 }
42
43 pub fn join_agenda_row(&mut self, row: &AgendaRow, cx: &mut Context<Self>) {
44 if let Some(url) = &row.join_url {
45 self.join_meeting_link(url, cx);
46 }
47 }
48
49 pub fn open_agenda_chat(&mut self, row: &AgendaRow, cx: &mut Context<Self>) {
50 let Some(thread_id) = &row.thread_id else {
51 return;
52 };
53 match selection_for(&self.sidebar, thread_id) {
54 Some(selection @ Selection::Chat(_)) => self.select(selection, cx),
55 _ => self.raise_notice(NO_MEETING_CHAT_NOTICE.to_owned(), None, cx),
56 }
57 }
58 }
@@ -0,0 +1,58 @@
1use chatsvc::CalendarEvent;
2use chrono::{Local, Offset, Utc};
3use gpui_kit::Context;
4
5use super::agenda::{AgendaRow, demo_events};
6use crate::app_state::{AppEvent, AppState, Selection};
7use crate::notify::selection_for;
8
9const NO_MEETING_CHAT_NOTICE: &str = "This meeting chat is not available";
10
11impl AppState {
12 pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {
13 self.calendar_events = events;
14 self.calls_list.invalidate();
15 cx.emit(AppEvent::CallHistory);
16 cx.notify();
17 }
18
19 pub fn refresh_calendar(&mut self, cx: &mut Context<Self>) {
20 if self.mode.demo {
21 self.apply_calendar(demo_events(Utc::now()), cx);
22 return;
23 }
24 if let Some(nudge) = &self.calendar_nudge {
25 let _ = nudge.send(());
26 }
27 }
28
29 pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {
30 let now = Utc::now();
31 let offset = Local::now().offset().fix();
32 self.calls_list.rebuild(
33 &self.call_history,
34 &self.sidebar.chats,
35 &self.calendar_events,
36 now,
37 offset,
38 );
39 cx.emit(AppEvent::CallHistory);
40 cx.notify();
41 }
42
43 pub fn join_agenda_row(&mut self, row: &AgendaRow, cx: &mut Context<Self>) {
44 if let Some(url) = &row.join_url {
45 self.join_meeting_link(url, cx);
46 }
47 }
48
49 pub fn open_agenda_chat(&mut self, row: &AgendaRow, cx: &mut Context<Self>) {
50 let Some(thread_id) = &row.thread_id else {
51 return;
52 };
53 match selection_for(&self.sidebar, thread_id) {
54 Some(selection @ Selection::Chat(_)) => self.select(selection, cx),
55 _ => self.raise_notice(NO_MEETING_CHAT_NOTICE.to_owned(), None, cx),
56 }
57 }
58}
crates/app/src/call/history.rs +5 −1
@@ -82,6 +82,8 @@ pub fn call_rows(
82 82 offset: FixedOffset,
83 83 ) -> Vec<CallRow> {
84 84 let names = known_names(chats);
85 let chats_by_id: HashMap<&str, &ChatRecord> =
86 chats.iter().map(|chat| (chat.id.as_str(), chat)).collect();
85 87 let today = now.with_timezone(&offset).date_naive();
86 88 entries
87 89 .iter()
@@ -94,7 +96,7 @@ pub fn call_rows(
94 96 let thread_chat = entry
95 97 .thread_id
96 98 .as_deref()
97 .and_then(|thread_id| chats.iter().find(|chat| chat.id == thread_id));
99 .and_then(|thread_id| chats_by_id.get(thread_id).copied());
98 100 let title = if entry.is_meeting {
99 101 thread_chat.map_or_else(|| MEETING_TITLE.to_owned(), chat_title)
100 102 } else {
@@ -216,6 +218,7 @@ impl AppState {
216 218 pub fn refresh_call_history(&mut self, cx: &mut Context<Self>) {
217 219 if self.mode.demo {
218 220 self.call_history = demo_call_log(Utc::now());
221 self.calls_list.invalidate();
219 222 cx.emit(AppEvent::CallHistory);
220 223 cx.notify();
221 224 return;
@@ -228,6 +231,7 @@ impl AppState {
228 231 Ok(Ok(entries)) => {
229 232 this.update(cx, |state, cx| {
230 233 state.call_history = entries;
234 state.calls_list.invalidate();
231 235 cx.emit(AppEvent::CallHistory);
232 236 cx.notify();
233 237 })
@@ -82,6 +82,8 @@ pub fn call_rows(
82 offset: FixedOffset,
82 offset: FixedOffset,
83) -> Vec<CallRow> {
83) -> Vec<CallRow> {
84 let names = known_names(chats);
84 let names = known_names(chats);
85 let chats_by_id: HashMap<&str, &ChatRecord> =
86 chats.iter().map(|chat| (chat.id.as_str(), chat)).collect();
85 let today = now.with_timezone(&offset).date_naive();
87 let today = now.with_timezone(&offset).date_naive();
86 entries
88 entries
87 .iter()
89 .iter()
@@ -94,7 +96,7 @@ pub fn call_rows(
94 let thread_chat = entry
96 let thread_chat = entry
95 .thread_id
97 .thread_id
96 .as_deref()
98 .as_deref()
97 .and_then(|thread_id| chats.iter().find(|chat| chat.id == thread_id));
99 .and_then(|thread_id| chats_by_id.get(thread_id).copied());
98 let title = if entry.is_meeting {
100 let title = if entry.is_meeting {
99 thread_chat.map_or_else(|| MEETING_TITLE.to_owned(), chat_title)
101 thread_chat.map_or_else(|| MEETING_TITLE.to_owned(), chat_title)
100 } else {
102 } else {
@@ -216,6 +218,7 @@ impl AppState {
216 pub fn refresh_call_history(&mut self, cx: &mut Context<Self>) {
218 pub fn refresh_call_history(&mut self, cx: &mut Context<Self>) {
217 if self.mode.demo {
219 if self.mode.demo {
218 self.call_history = demo_call_log(Utc::now());
220 self.call_history = demo_call_log(Utc::now());
221 self.calls_list.invalidate();
219 cx.emit(AppEvent::CallHistory);
222 cx.emit(AppEvent::CallHistory);
220 cx.notify();
223 cx.notify();
221 return;
224 return;
@@ -228,6 +231,7 @@ impl AppState {
228 Ok(Ok(entries)) => {
231 Ok(Ok(entries)) => {
229 this.update(cx, |state, cx| {
232 this.update(cx, |state, cx| {
230 state.call_history = entries;
233 state.call_history = entries;
234 state.calls_list.invalidate();
231 cx.emit(AppEvent::CallHistory);
235 cx.emit(AppEvent::CallHistory);
232 cx.notify();
236 cx.notify();
233 })
237 })
crates/app/src/call/join.rs +34 −0
@@ -18,6 +18,8 @@ const BAD_ID_MESSAGE: &str = "Enter the meeting ID from the invitation.";
18 18 const DEMO_GUEST_COUNT: usize = 4;
19 19 const DEMO_CODE_THREAD: &str = "19:meeting_demo@thread.v2";
20 20 const MEETING_TITLE: &str = "Meeting";
21 const MEET_NOW_SUBJECT: &str = "Meet now";
22 const MEET_NOW_FAILED_NOTICE: &str = "Could not start the meeting";
21 23
22 24 pub fn meeting_target(meeting: &ThreadMeeting) -> MeetingTarget {
23 25 MeetingTarget {
@@ -101,6 +103,38 @@ impl AppState {
101 103 }
102 104 }
103 105
106 pub fn start_meet_now(&mut self, cx: &mut Context<Self>) {
107 if self.call.is_some() {
108 self.show_call(true, cx);
109 return;
110 }
111 if self.mode.demo {
112 let target = MeetingTarget {
113 thread_id: DEMO_CODE_THREAD.to_owned(),
114 tenant_id: "demo-tenant".to_owned(),
115 organizer_id: "demo-organizer".to_owned(),
116 meeting_data: None,
117 };
118 self.join_resolved_meeting(target, cx);
119 return;
120 }
121 let Some(launcher) = self.call_launcher.clone() else {
122 self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
123 return;
124 };
125 let receiver =
126 runtime::spawn(async move { launcher.create_meet_now(MEET_NOW_SUBJECT).await });
127 cx.spawn(async move |this, cx| {
128 let created = receiver.await.ok().and_then(Result::ok);
129 this.update(cx, |state, cx| match created {
130 Some(url) => state.join_meeting_link(&url, cx),
131 None => state.raise_notice(MEET_NOW_FAILED_NOTICE.to_owned(), None, cx),
132 })
133 .ok();
134 })
135 .detach();
136 }
137
104 138 pub fn join_meeting_from_clipboard(&mut self, cx: &mut Context<Self>) {
105 139 let link = cx
106 140 .read_from_clipboard()
@@ -18,6 +18,8 @@ const BAD_ID_MESSAGE: &str = "Enter the meeting ID from the invitation.";
18const DEMO_GUEST_COUNT: usize = 4;
18const DEMO_GUEST_COUNT: usize = 4;
19const DEMO_CODE_THREAD: &str = "19:meeting_demo@thread.v2";
19const DEMO_CODE_THREAD: &str = "19:meeting_demo@thread.v2";
20const MEETING_TITLE: &str = "Meeting";
20const MEETING_TITLE: &str = "Meeting";
21const MEET_NOW_SUBJECT: &str = "Meet now";
22const MEET_NOW_FAILED_NOTICE: &str = "Could not start the meeting";
21
23
22pub fn meeting_target(meeting: &ThreadMeeting) -> MeetingTarget {
24pub fn meeting_target(meeting: &ThreadMeeting) -> MeetingTarget {
23 MeetingTarget {
25 MeetingTarget {
@@ -101,6 +103,38 @@ impl AppState {
101 }
103 }
102 }
104 }
103
105
106 pub fn start_meet_now(&mut self, cx: &mut Context<Self>) {
107 if self.call.is_some() {
108 self.show_call(true, cx);
109 return;
110 }
111 if self.mode.demo {
112 let target = MeetingTarget {
113 thread_id: DEMO_CODE_THREAD.to_owned(),
114 tenant_id: "demo-tenant".to_owned(),
115 organizer_id: "demo-organizer".to_owned(),
116 meeting_data: None,
117 };
118 self.join_resolved_meeting(target, cx);
119 return;
120 }
121 let Some(launcher) = self.call_launcher.clone() else {
122 self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
123 return;
124 };
125 let receiver =
126 runtime::spawn(async move { launcher.create_meet_now(MEET_NOW_SUBJECT).await });
127 cx.spawn(async move |this, cx| {
128 let created = receiver.await.ok().and_then(Result::ok);
129 this.update(cx, |state, cx| match created {
130 Some(url) => state.join_meeting_link(&url, cx),
131 None => state.raise_notice(MEET_NOW_FAILED_NOTICE.to_owned(), None, cx),
132 })
133 .ok();
134 })
135 .detach();
136 }
137
104 pub fn join_meeting_from_clipboard(&mut self, cx: &mut Context<Self>) {
138 pub fn join_meeting_from_clipboard(&mut self, cx: &mut Context<Self>) {
105 let link = cx
139 let link = cx
106 .read_from_clipboard()
140 .read_from_clipboard()
crates/app/src/call/launcher.rs +8 −0
@@ -94,6 +94,14 @@ impl CallLauncher {
94 94 .map_err(|error| error.to_string())
95 95 }
96 96
97 pub async fn create_meet_now(&self, subject: &str) -> Result<String, String> {
98 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
99 chatsvc::Calendar::new(&session)
100 .create_meet_now(subject)
101 .await
102 .map_err(|error| error.to_string())
103 }
104
97 105 pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
98 106 let session = self.engine()?.session();
99 107 fetch_live_meeting(&session, thread_id).await.ok().flatten()
@@ -94,6 +94,14 @@ impl CallLauncher {
94 .map_err(|error| error.to_string())
94 .map_err(|error| error.to_string())
95 }
95 }
96
96
97 pub async fn create_meet_now(&self, subject: &str) -> Result<String, String> {
98 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
99 chatsvc::Calendar::new(&session)
100 .create_meet_now(subject)
101 .await
102 .map_err(|error| error.to_string())
103 }
104
97 pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
105 pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
98 let session = self.engine()?.session();
106 let session = self.engine()?.session();
99 fetch_live_meeting(&session, thread_id).await.ok().flatten()
107 fetch_live_meeting(&session, thread_id).await.ok().flatten()
crates/app/src/call/list.rs added +289 −0
@@ -0,0 +1,289 @@
1 use std::ops::Range;
2
3 use chatsvc::CalendarEvent;
4 use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
5 use store::ChatRecord;
6 use teams_core::CallLogEntry;
7
8 use super::agenda::{AgendaRow, group_by_day};
9 use super::history::{CallRow, call_rows};
10
11 pub const SECTION_HEIGHT: f32 = 34.;
12 pub const DAY_HEIGHT: f32 = 26.;
13 pub const AGENDA_ROW_HEIGHT: f32 = 58.;
14 pub const CALL_ROW_HEIGHT: f32 = 54.;
15 pub const EMPTY_HEIGHT: f32 = 56.;
16 const MAX_AGE_SECONDS: i64 = 60;
17 const UPCOMING_TITLE: &str = "Upcoming";
18 const RECENT_TITLE: &str = "Recent";
19 const NO_MEETINGS_TEXT: &str = "No meetings in the next 7 days";
20 const NO_CALLS_TEXT: &str = "No calls yet";
21
22 #[derive(Debug, Clone, PartialEq, Eq)]
23 pub enum ListEntry {
24 Section(&'static str),
25 Day(String),
26 Agenda(AgendaRow),
27 Call(CallRow),
28 Empty(&'static str),
29 }
30
31 impl ListEntry {
32 pub fn height(&self) -> f32 {
33 match self {
34 ListEntry::Section(_) => SECTION_HEIGHT,
35 ListEntry::Day(_) => DAY_HEIGHT,
36 ListEntry::Agenda(_) => AGENDA_ROW_HEIGHT,
37 ListEntry::Call(_) => CALL_ROW_HEIGHT,
38 ListEntry::Empty(_) => EMPTY_HEIGHT,
39 }
40 }
41 }
42
43 #[derive(Debug, Clone, PartialEq)]
44 pub struct VisibleWindow {
45 pub range: Range<usize>,
46 pub before: f32,
47 pub after: f32,
48 }
49
50 #[derive(Debug, Clone)]
51 struct BuiltAt {
52 day: NaiveDate,
53 time: DateTime<Utc>,
54 }
55
56 #[derive(Debug, Default)]
57 pub struct CallsList {
58 entries: Vec<ListEntry>,
59 starts: Vec<f32>,
60 ends: Vec<f32>,
61 built_at: Option<BuiltAt>,
62 invalidated: bool,
63 }
64
65 impl CallsList {
66 pub fn invalidate(&mut self) {
67 self.invalidated = true;
68 }
69
70 pub fn needs_rebuild(&self, now: DateTime<Utc>, offset: FixedOffset) -> bool {
71 let Some(built_at) = &self.built_at else {
72 return true;
73 };
74 self.invalidated
75 || built_at.day != now.with_timezone(&offset).date_naive()
76 || now - built_at.time >= Duration::seconds(MAX_AGE_SECONDS)
77 }
78
79 pub fn entries(&self) -> &[ListEntry] {
80 &self.entries
81 }
82
83 pub fn rebuild(
84 &mut self,
85 history: &[CallLogEntry],
86 chats: &[ChatRecord],
87 events: &[CalendarEvent],
88 now: DateTime<Utc>,
89 offset: FixedOffset,
90 ) {
91 let mut entries = vec![ListEntry::Section(UPCOMING_TITLE)];
92 let days = group_by_day(events, now, offset);
93 if days.is_empty() {
94 entries.push(ListEntry::Empty(NO_MEETINGS_TEXT));
95 }
96 for day in days {
97 entries.push(ListEntry::Day(day.label));
98 entries.extend(day.rows.into_iter().map(ListEntry::Agenda));
99 }
100 entries.push(ListEntry::Section(RECENT_TITLE));
101 let calls = call_rows(history, chats, now, offset);
102 if calls.is_empty() {
103 entries.push(ListEntry::Empty(NO_CALLS_TEXT));
104 }
105 entries.extend(calls.into_iter().map(ListEntry::Call));
106 self.set_entries(entries);
107 self.built_at = Some(BuiltAt {
108 day: now.with_timezone(&offset).date_naive(),
109 time: now,
110 });
111 self.invalidated = false;
112 }
113
114 fn set_entries(&mut self, entries: Vec<ListEntry>) {
115 let mut position = 0.;
116 self.starts = Vec::with_capacity(entries.len());
117 self.ends = Vec::with_capacity(entries.len());
118 for entry in &entries {
119 self.starts.push(position);
120 position += entry.height();
121 self.ends.push(position);
122 }
123 self.entries = entries;
124 }
125
126 pub fn total_height(&self) -> f32 {
127 self.ends.last().copied().unwrap_or(0.)
128 }
129
130 pub fn window(&self, from: f32, to: f32) -> VisibleWindow {
131 let first = self.ends.partition_point(|end| *end < from);
132 let last = self.starts.partition_point(|start| *start <= to).max(first);
133 VisibleWindow {
134 before: self
135 .starts
136 .get(first)
137 .copied()
138 .unwrap_or(self.total_height()),
139 after: match last.checked_sub(1).and_then(|index| self.ends.get(index)) {
140 Some(end) if last > first => self.total_height() - end,
141 _ => 0.,
142 },
143 range: first..last,
144 }
145 }
146 }
147
148 #[cfg(test)]
149 mod tests {
150 use chatsvc::ResponseType;
151 use chrono::TimeZone;
152 use teams_core::{CallDirection, CallOutcome};
153
154 use super::*;
155
156 fn now() -> DateTime<Utc> {
157 Utc.with_ymd_and_hms(2026, 10, 12, 8, 0, 0).unwrap()
158 }
159
160 fn zero() -> FixedOffset {
161 FixedOffset::east_opt(0).unwrap()
162 }
163
164 fn call(id: &str) -> CallLogEntry {
165 CallLogEntry {
166 call_id: id.into(),
167 started_at: now() - Duration::hours(3),
168 duration_seconds: Some(60),
169 direction: CallDirection::Outgoing,
170 outcome: CallOutcome::Accepted,
171 is_meeting: false,
172 peer_id: Some("8:orgid:bea".into()),
173 peer_name: Some("Bea".into()),
174 thread_id: None,
175 }
176 }
177
178 fn event(id: &str, minutes_from_now: i64) -> CalendarEvent {
179 CalendarEvent {
180 object_id: id.into(),
181 subject: id.into(),
182 start: now() + Duration::minutes(minutes_from_now),
183 end: now() + Duration::minutes(minutes_from_now + 30),
184 all_day: false,
185 cancelled: false,
186 online: true,
187 join_url: None,
188 thread_id: None,
189 organizer_name: None,
190 organizer_address: None,
191 response: ResponseType::Accepted,
192 }
193 }
194
195 fn built(calls: usize, events: usize) -> CallsList {
196 let history: Vec<CallLogEntry> =
197 (0..calls).map(|index| call(&format!("c{index}"))).collect();
198 let agenda: Vec<CalendarEvent> = (0..events)
199 .map(|index| event(&format!("e{index}"), 30 + index as i64 * 60))
200 .collect();
201 let mut list = CallsList::default();
202 list.rebuild(&history, &[], &agenda, now(), zero());
203 list
204 }
205
206 #[test]
207 fn empty_sections_show_their_empty_text() {
208 let list = built(0, 0);
209 assert_eq!(
210 list.entries(),
211 [
212 ListEntry::Section("Upcoming"),
213 ListEntry::Empty("No meetings in the next 7 days"),
214 ListEntry::Section("Recent"),
215 ListEntry::Empty("No calls yet"),
216 ]
217 );
218 }
219
220 #[test]
221 fn upcoming_comes_before_recent_with_day_headers() {
222 let list = built(2, 2);
223 let kinds: Vec<&str> = list
224 .entries()
225 .iter()
226 .map(|entry| match entry {
227 ListEntry::Section(_) => "section",
228 ListEntry::Day(_) => "day",
229 ListEntry::Agenda(_) => "agenda",
230 ListEntry::Call(_) => "call",
231 ListEntry::Empty(_) => "empty",
232 })
233 .collect();
234 assert_eq!(
235 kinds,
236 [
237 "section", "day", "agenda", "agenda", "section", "call", "call"
238 ]
239 );
240 }
241
242 #[test]
243 fn a_fresh_list_needs_a_rebuild_until_built() {
244 let mut list = CallsList::default();
245 assert!(list.needs_rebuild(now(), zero()));
246 list.rebuild(&[], &[], &[], now(), zero());
247 assert!(!list.needs_rebuild(now() + Duration::seconds(30), zero()));
248 }
249
250 #[test]
251 fn invalidation_age_and_a_new_day_force_a_rebuild() {
252 let mut list = built(0, 0);
253 list.invalidate();
254 assert!(list.needs_rebuild(now(), zero()));
255 list.rebuild(&[], &[], &[], now(), zero());
256 assert!(list.needs_rebuild(now() + Duration::seconds(61), zero()));
257 assert!(list.needs_rebuild(now() + Duration::hours(17), zero()));
258 }
259
260 #[test]
261 fn the_window_keeps_only_rows_on_screen_and_spacers_for_the_rest() {
262 let list = built(100, 0);
263 let total = list.total_height();
264 let window = list.window(1000., 1200.);
265 assert!(window.range.len() < 12);
266 assert!(window.range.start > 10);
267 assert_eq!(window.before, list.starts[window.range.start]);
268 let shown: f32 = list.entries()[window.range.clone()]
269 .iter()
270 .map(ListEntry::height)
271 .sum();
272 assert!((window.before + shown + window.after - total).abs() < 0.01);
273 }
274
275 #[test]
276 fn the_window_clamps_at_both_ends() {
277 let list = built(100, 0);
278 let top = list.window(-300., 100.);
279 assert_eq!(top.range.start, 0);
280 assert_eq!(top.before, 0.);
281 let bottom = list.window(list.total_height() - 100., list.total_height() + 500.);
282 assert_eq!(bottom.range.end, list.entries().len());
283 assert_eq!(bottom.after, 0.);
284 let empty = CallsList::default().window(0., 100.);
285 assert_eq!(empty.range, 0..0);
286 assert_eq!(empty.before, 0.);
287 assert_eq!(empty.after, 0.);
288 }
289 }
@@ -0,0 +1,289 @@
1use std::ops::Range;
2
3use chatsvc::CalendarEvent;
4use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
5use store::ChatRecord;
6use teams_core::CallLogEntry;
7
8use super::agenda::{AgendaRow, group_by_day};
9use super::history::{CallRow, call_rows};
10
11pub const SECTION_HEIGHT: f32 = 34.;
12pub const DAY_HEIGHT: f32 = 26.;
13pub const AGENDA_ROW_HEIGHT: f32 = 58.;
14pub const CALL_ROW_HEIGHT: f32 = 54.;
15pub const EMPTY_HEIGHT: f32 = 56.;
16const MAX_AGE_SECONDS: i64 = 60;
17const UPCOMING_TITLE: &str = "Upcoming";
18const RECENT_TITLE: &str = "Recent";
19const NO_MEETINGS_TEXT: &str = "No meetings in the next 7 days";
20const NO_CALLS_TEXT: &str = "No calls yet";
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum ListEntry {
24 Section(&'static str),
25 Day(String),
26 Agenda(AgendaRow),
27 Call(CallRow),
28 Empty(&'static str),
29}
30
31impl ListEntry {
32 pub fn height(&self) -> f32 {
33 match self {
34 ListEntry::Section(_) => SECTION_HEIGHT,
35 ListEntry::Day(_) => DAY_HEIGHT,
36 ListEntry::Agenda(_) => AGENDA_ROW_HEIGHT,
37 ListEntry::Call(_) => CALL_ROW_HEIGHT,
38 ListEntry::Empty(_) => EMPTY_HEIGHT,
39 }
40 }
41}
42
43#[derive(Debug, Clone, PartialEq)]
44pub struct VisibleWindow {
45 pub range: Range<usize>,
46 pub before: f32,
47 pub after: f32,
48}
49
50#[derive(Debug, Clone)]
51struct BuiltAt {
52 day: NaiveDate,
53 time: DateTime<Utc>,
54}
55
56#[derive(Debug, Default)]
57pub struct CallsList {
58 entries: Vec<ListEntry>,
59 starts: Vec<f32>,
60 ends: Vec<f32>,
61 built_at: Option<BuiltAt>,
62 invalidated: bool,
63}
64
65impl CallsList {
66 pub fn invalidate(&mut self) {
67 self.invalidated = true;
68 }
69
70 pub fn needs_rebuild(&self, now: DateTime<Utc>, offset: FixedOffset) -> bool {
71 let Some(built_at) = &self.built_at else {
72 return true;
73 };
74 self.invalidated
75 || built_at.day != now.with_timezone(&offset).date_naive()
76 || now - built_at.time >= Duration::seconds(MAX_AGE_SECONDS)
77 }
78
79 pub fn entries(&self) -> &[ListEntry] {
80 &self.entries
81 }
82
83 pub fn rebuild(
84 &mut self,
85 history: &[CallLogEntry],
86 chats: &[ChatRecord],
87 events: &[CalendarEvent],
88 now: DateTime<Utc>,
89 offset: FixedOffset,
90 ) {
91 let mut entries = vec![ListEntry::Section(UPCOMING_TITLE)];
92 let days = group_by_day(events, now, offset);
93 if days.is_empty() {
94 entries.push(ListEntry::Empty(NO_MEETINGS_TEXT));
95 }
96 for day in days {
97 entries.push(ListEntry::Day(day.label));
98 entries.extend(day.rows.into_iter().map(ListEntry::Agenda));
99 }
100 entries.push(ListEntry::Section(RECENT_TITLE));
101 let calls = call_rows(history, chats, now, offset);
102 if calls.is_empty() {
103 entries.push(ListEntry::Empty(NO_CALLS_TEXT));
104 }
105 entries.extend(calls.into_iter().map(ListEntry::Call));
106 self.set_entries(entries);
107 self.built_at = Some(BuiltAt {
108 day: now.with_timezone(&offset).date_naive(),
109 time: now,
110 });
111 self.invalidated = false;
112 }
113
114 fn set_entries(&mut self, entries: Vec<ListEntry>) {
115 let mut position = 0.;
116 self.starts = Vec::with_capacity(entries.len());
117 self.ends = Vec::with_capacity(entries.len());
118 for entry in &entries {
119 self.starts.push(position);
120 position += entry.height();
121 self.ends.push(position);
122 }
123 self.entries = entries;
124 }
125
126 pub fn total_height(&self) -> f32 {
127 self.ends.last().copied().unwrap_or(0.)
128 }
129
130 pub fn window(&self, from: f32, to: f32) -> VisibleWindow {
131 let first = self.ends.partition_point(|end| *end < from);
132 let last = self.starts.partition_point(|start| *start <= to).max(first);
133 VisibleWindow {
134 before: self
135 .starts
136 .get(first)
137 .copied()
138 .unwrap_or(self.total_height()),
139 after: match last.checked_sub(1).and_then(|index| self.ends.get(index)) {
140 Some(end) if last > first => self.total_height() - end,
141 _ => 0.,
142 },
143 range: first..last,
144 }
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use chatsvc::ResponseType;
151 use chrono::TimeZone;
152 use teams_core::{CallDirection, CallOutcome};
153
154 use super::*;
155
156 fn now() -> DateTime<Utc> {
157 Utc.with_ymd_and_hms(2026, 10, 12, 8, 0, 0).unwrap()
158 }
159
160 fn zero() -> FixedOffset {
161 FixedOffset::east_opt(0).unwrap()
162 }
163
164 fn call(id: &str) -> CallLogEntry {
165 CallLogEntry {
166 call_id: id.into(),
167 started_at: now() - Duration::hours(3),
168 duration_seconds: Some(60),
169 direction: CallDirection::Outgoing,
170 outcome: CallOutcome::Accepted,
171 is_meeting: false,
172 peer_id: Some("8:orgid:bea".into()),
173 peer_name: Some("Bea".into()),
174 thread_id: None,
175 }
176 }
177
178 fn event(id: &str, minutes_from_now: i64) -> CalendarEvent {
179 CalendarEvent {
180 object_id: id.into(),
181 subject: id.into(),
182 start: now() + Duration::minutes(minutes_from_now),
183 end: now() + Duration::minutes(minutes_from_now + 30),
184 all_day: false,
185 cancelled: false,
186 online: true,
187 join_url: None,
188 thread_id: None,
189 organizer_name: None,
190 organizer_address: None,
191 response: ResponseType::Accepted,
192 }
193 }
194
195 fn built(calls: usize, events: usize) -> CallsList {
196 let history: Vec<CallLogEntry> =
197 (0..calls).map(|index| call(&format!("c{index}"))).collect();
198 let agenda: Vec<CalendarEvent> = (0..events)
199 .map(|index| event(&format!("e{index}"), 30 + index as i64 * 60))
200 .collect();
201 let mut list = CallsList::default();
202 list.rebuild(&history, &[], &agenda, now(), zero());
203 list
204 }
205
206 #[test]
207 fn empty_sections_show_their_empty_text() {
208 let list = built(0, 0);
209 assert_eq!(
210 list.entries(),
211 [
212 ListEntry::Section("Upcoming"),
213 ListEntry::Empty("No meetings in the next 7 days"),
214 ListEntry::Section("Recent"),
215 ListEntry::Empty("No calls yet"),
216 ]
217 );
218 }
219
220 #[test]
221 fn upcoming_comes_before_recent_with_day_headers() {
222 let list = built(2, 2);
223 let kinds: Vec<&str> = list
224 .entries()
225 .iter()
226 .map(|entry| match entry {
227 ListEntry::Section(_) => "section",
228 ListEntry::Day(_) => "day",
229 ListEntry::Agenda(_) => "agenda",
230 ListEntry::Call(_) => "call",
231 ListEntry::Empty(_) => "empty",
232 })
233 .collect();
234 assert_eq!(
235 kinds,
236 [
237 "section", "day", "agenda", "agenda", "section", "call", "call"
238 ]
239 );
240 }
241
242 #[test]
243 fn a_fresh_list_needs_a_rebuild_until_built() {
244 let mut list = CallsList::default();
245 assert!(list.needs_rebuild(now(), zero()));
246 list.rebuild(&[], &[], &[], now(), zero());
247 assert!(!list.needs_rebuild(now() + Duration::seconds(30), zero()));
248 }
249
250 #[test]
251 fn invalidation_age_and_a_new_day_force_a_rebuild() {
252 let mut list = built(0, 0);
253 list.invalidate();
254 assert!(list.needs_rebuild(now(), zero()));
255 list.rebuild(&[], &[], &[], now(), zero());
256 assert!(list.needs_rebuild(now() + Duration::seconds(61), zero()));
257 assert!(list.needs_rebuild(now() + Duration::hours(17), zero()));
258 }
259
260 #[test]
261 fn the_window_keeps_only_rows_on_screen_and_spacers_for_the_rest() {
262 let list = built(100, 0);
263 let total = list.total_height();
264 let window = list.window(1000., 1200.);
265 assert!(window.range.len() < 12);
266 assert!(window.range.start > 10);
267 assert_eq!(window.before, list.starts[window.range.start]);
268 let shown: f32 = list.entries()[window.range.clone()]
269 .iter()
270 .map(ListEntry::height)
271 .sum();
272 assert!((window.before + shown + window.after - total).abs() < 0.01);
273 }
274
275 #[test]
276 fn the_window_clamps_at_both_ends() {
277 let list = built(100, 0);
278 let top = list.window(-300., 100.);
279 assert_eq!(top.range.start, 0);
280 assert_eq!(top.before, 0.);
281 let bottom = list.window(list.total_height() - 100., list.total_height() + 500.);
282 assert_eq!(bottom.range.end, list.entries().len());
283 assert_eq!(bottom.after, 0.);
284 let empty = CallsList::default().window(0., 100.);
285 assert_eq!(empty.range, 0..0);
286 assert_eq!(empty.before, 0.);
287 assert_eq!(empty.after, 0.);
288 }
289}
crates/app/src/call/mod.rs +6 −1
@@ -1,11 +1,14 @@
1 1 mod actions;
2 mod agenda;
2 3 mod background;
4 mod calendar;
3 5 mod demo;
4 6 mod demo_scene;
5 7 mod features;
6 8 mod history;
7 9 mod join;
8 10 mod launcher;
11 mod list;
9 12 mod model;
10 13 mod pictures;
11 14 mod ring;
@@ -15,8 +18,10 @@ pub use actions::load_share_sound;
15 18 pub use background::{BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background, load_custom_backgrounds};
16 19 pub use features::TransferCandidate;
17 20 pub use demo::DemoScene;
18 pub use history::{CallRow, call_rows};
21 pub use agenda::{AgendaRow, fetch_window, join_available};
22 pub use history::CallRow;
19 23 pub use launcher::CallLauncher;
24 pub use list::{AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry, SECTION_HEIGHT};
20 25 pub use model::{
21 26 ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,
22 27 grid_layout, tile_size,
@@ -1,11 +1,14 @@
1mod actions;
1mod actions;
2mod agenda;
2mod background;
3mod background;
4mod calendar;
3mod demo;
5mod demo;
4mod demo_scene;
6mod demo_scene;
5mod features;
7mod features;
6mod history;
8mod history;
7mod join;
9mod join;
8mod launcher;
10mod launcher;
11mod list;
9mod model;
12mod model;
10mod pictures;
13mod pictures;
11mod ring;
14mod ring;
@@ -15,8 +18,10 @@ pub use actions::load_share_sound;
15pub use background::{BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background, load_custom_backgrounds};
18pub use background::{BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background, load_custom_backgrounds};
16pub use features::TransferCandidate;
19pub use features::TransferCandidate;
17pub use demo::DemoScene;
20pub use demo::DemoScene;
18pub use history::{CallRow, call_rows};
21pub use agenda::{AgendaRow, fetch_window, join_available};
22pub use history::CallRow;
19pub use launcher::CallLauncher;
23pub use launcher::CallLauncher;
24pub use list::{AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry, SECTION_HEIGHT};
20pub use model::{
25pub use model::{
21 ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,
26 ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,
22 grid_layout, tile_size,
27 grid_layout, tile_size,
crates/app/src/views/calls_tab.rs +165 −30
@@ -1,7 +1,7 @@
1 1 use chrono::{Local, Offset, Utc};
2 2 use gpui_kit::assets::IconName;
3 3 use gpui_kit::component::Sizable as _;
4 use gpui_kit::component::button::Button;
4 use gpui_kit::component::button::{Button, ButtonVariants as _};
5 5 use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6 6 use gpui_kit::component::{h_flex, v_flex};
7 7 use gpui_kit::prelude::FluentBuilder as _;
@@ -11,13 +11,17 @@ use super::avatar::person_avatar;
11 11 use super::join_dialog::open_join_with_id;
12 12 use super::widgets::icon;
13 13 use crate::app_state::AppState;
14 use crate::call::{CallRow, call_rows};
14 use crate::call::{
15 AGENDA_ROW_HEIGHT, AgendaRow, CALL_ROW_HEIGHT, CallRow, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
16 SECTION_HEIGHT, join_available,
17 };
15 18 use crate::theme;
16 19
17 const ROW_HEIGHT: f32 = 54.;
20 const FALLBACK_VIEWPORT: f32 = 900.;
21 const VIEWPORT_MARGIN: f32 = 300.;
22 const TIME_COLUMN_WIDTH: f32 = 96.;
18 23 const AVATAR_SIZE: f32 = 36.;
19 24 const MENU_ICON_SIZE: f32 = 15.;
20 const EMPTY_TEXT: &str = "No calls yet";
21 25
22 26 fn meeting_avatar() -> Div {
23 27 div()
@@ -55,7 +59,7 @@ fn call_row(
55 59 h_flex()
56 60 .id(SharedString::from(format!("call-{}", row.key)))
57 61 .mx(px(8.))
58 .h(px(ROW_HEIGHT))
62 .h(px(CALL_ROW_HEIGHT))
59 63 .px(px(8.))
60 64 .gap(px(10.))
61 65 .items_center()
@@ -141,6 +145,7 @@ fn call_row(
141 145 }
142 146
143 147 fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
148 let meet_state = state.clone();
144 149 let id_state = state.clone();
145 150 let paste_state = state.clone();
146 151 h_flex()
@@ -148,6 +153,16 @@ fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
148 153 .px(px(12.))
149 154 .pb(px(8.))
150 155 .gap(px(8.))
156 .flex_wrap()
157 .child(
158 Button::new("meet-now")
159 .small()
160 .primary()
161 .label("Meet now")
162 .on_click(move |_, _, cx| {
163 meet_state.update(cx, |state, cx| state.start_meet_now(cx));
164 }),
165 )
151 166 .child(
152 167 Button::new("join-with-id")
153 168 .small()
@@ -164,34 +179,154 @@ fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
164 179 )
165 180 }
166 181
167 pub fn calls_body(state: &Entity<AppState>, scroll: &ScrollHandle, cx: &App) -> AnyElement {
168 let app = state.read(cx);
182 fn section_header(title: &'static str) -> AnyElement {
183 div()
184 .h(px(SECTION_HEIGHT))
185 .px(px(16.))
186 .flex()
187 .items_end()
188 .pb(px(4.))
189 .text_size(px(12.))
190 .font_weight(FontWeight::SEMIBOLD)
191 .text_color(theme::text_muted())
192 .child(title)
193 .into_any_element()
194 }
195
196 fn day_header(label: &str) -> AnyElement {
197 div()
198 .h(px(DAY_HEIGHT))
199 .px(px(16.))
200 .flex()
201 .items_center()
202 .text_size(px(11.5))
203 .text_color(theme::text_faint())
204 .child(label.to_owned())
205 .into_any_element()
206 }
207
208 fn empty_row(text: &'static str) -> AnyElement {
209 div()
210 .h(px(EMPTY_HEIGHT))
211 .flex()
212 .items_center()
213 .justify_center()
214 .text_size(px(13.))
215 .text_color(theme::text_muted())
216 .child(text)
217 .into_any_element()
218 }
219
220 fn agenda_row(state: &Entity<AppState>, row: &AgendaRow, joinable: bool) -> AnyElement {
221 let click_state = state.clone();
222 let click_row = row.clone();
223 let join_state = state.clone();
224 let join_row = row.clone();
225 h_flex()
226 .id(SharedString::from(format!("agenda-{}", row.key)))
227 .mx(px(8.))
228 .h(px(AGENDA_ROW_HEIGHT))
229 .px(px(8.))
230 .gap(px(10.))
231 .items_center()
232 .rounded(px(8.))
233 .cursor_pointer()
234 .hover(|row| row.bg(theme::row_hover()))
235 .child(
236 div()
237 .w(px(TIME_COLUMN_WIDTH))
238 .flex_none()
239 .text_size(px(12.))
240 .text_color(theme::text_muted())
241 .child(row.time_label.clone()),
242 )
243 .child(
244 v_flex()
245 .flex_1()
246 .min_w_0()
247 .gap(px(2.))
248 .child(
249 div()
250 .truncate()
251 .text_size(px(14.))
252 .text_color(theme::text())
253 .child(row.subject.clone()),
254 )
255 .when(!row.detail.is_empty(), |column| {
256 column.child(
257 div()
258 .truncate()
259 .text_size(px(12.5))
260 .text_color(theme::text_muted())
261 .child(row.detail.clone()),
262 )
263 }),
264 )
265 .when(joinable, |line| {
266 line.child(
267 Button::new(SharedString::from(format!("agenda-join-{}", row.key)))
268 .small()
269 .primary()
270 .label("Join")
271 .on_click(move |_, _, cx| {
272 cx.stop_propagation();
273 join_state.update(cx, |state, cx| state.join_agenda_row(&join_row, cx));
274 }),
275 )
276 })
277 .on_click(move |_, _, cx| {
278 click_state.update(cx, |state, cx| state.open_agenda_chat(&click_row, cx));
279 })
280 .into_any_element()
281 }
282
283 pub fn calls_body(
284 state: &Entity<AppState>,
285 scroll: &ScrollHandle,
286 window_height: f32,
287 cx: &mut App,
288 ) -> AnyElement {
289 let now = Utc::now();
169 290 let offset = Local::now().offset().fix();
170 let rows = call_rows(&app.call_history, &app.sidebar.chats, Utc::now(), offset);
171 let list = if rows.is_empty() {
172 div()
173 .w_full()
174 .py(px(24.))
175 .flex()
176 .justify_center()
177 .text_size(px(13.))
178 .text_color(theme::text_muted())
179 .child(EMPTY_TEXT)
180 .into_any_element()
291 if state.read(cx).calls_list.needs_rebuild(now, offset) {
292 let rebuild_state = state.clone();
293 cx.defer(move |cx| rebuild_state.update(cx, |state, cx| state.rebuild_calls_list(cx)));
294 }
295 let top = -f32::from(scroll.offset().y);
296 let measured = f32::from(scroll.bounds().size.height);
297 let height = if measured > 1. {
298 measured
181 299 } else {
182 v_flex()
183 .w_full()
184 .pb(px(12.))
185 .children(rows.iter().map(|row| {
186 call_row(
187 state,
188 row,
189 app.can_open_chat_of_call_row(row),
190 &app.directory,
191 )
192 }))
193 .into_any_element()
300 window_height.max(FALLBACK_VIEWPORT)
194 301 };
302 let app = state.read(cx);
303 let window = app
304 .calls_list
305 .window(top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
306 let entries = &app.calls_list.entries()[window.range.clone()];
307 let mut list = v_flex().w_full().pb(px(12.));
308 if window.before > 0. {
309 list = list.child(div().h(px(window.before)).flex_none());
310 }
311 for entry in entries {
312 list = list.child(match entry {
313 ListEntry::Section(title) => section_header(title),
314 ListEntry::Day(label) => day_header(label),
315 ListEntry::Empty(text) => empty_row(text),
316 ListEntry::Agenda(row) => {
317 agenda_row(state, row, join_available(row.start, row.end, now) && row.join_url.is_some())
318 }
319 ListEntry::Call(row) => call_row(
320 state,
321 row,
322 app.can_open_chat_of_call_row(row),
323 &app.directory,
324 ),
325 });
326 }
327 if window.after > 0. {
328 list = list.child(div().h(px(window.after)).flex_none());
329 }
195 330 v_flex()
196 331 .flex_1()
197 332 .min_h_0()
@@ -1,7 +1,7 @@
1use chrono::{Local, Offset, Utc};
1use chrono::{Local, Offset, Utc};
2use gpui_kit::assets::IconName;
2use gpui_kit::assets::IconName;
3use gpui_kit::component::Sizable as _;
3use gpui_kit::component::Sizable as _;
4use gpui_kit::component::button::Button;
4use gpui_kit::component::button::{Button, ButtonVariants as _};
5use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
5use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::prelude::FluentBuilder as _;
@@ -11,13 +11,17 @@ use super::avatar::person_avatar;
11use super::join_dialog::open_join_with_id;
11use super::join_dialog::open_join_with_id;
12use super::widgets::icon;
12use super::widgets::icon;
13use crate::app_state::AppState;
13use crate::app_state::AppState;
14use crate::call::{CallRow, call_rows};
14use crate::call::{
15 AGENDA_ROW_HEIGHT, AgendaRow, CALL_ROW_HEIGHT, CallRow, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
16 SECTION_HEIGHT, join_available,
17};
15use crate::theme;
18use crate::theme;
16
19
17const ROW_HEIGHT: f32 = 54.;
20const FALLBACK_VIEWPORT: f32 = 900.;
21const VIEWPORT_MARGIN: f32 = 300.;
22const TIME_COLUMN_WIDTH: f32 = 96.;
18const AVATAR_SIZE: f32 = 36.;
23const AVATAR_SIZE: f32 = 36.;
19const MENU_ICON_SIZE: f32 = 15.;
24const MENU_ICON_SIZE: f32 = 15.;
20const EMPTY_TEXT: &str = "No calls yet";
21
25
22fn meeting_avatar() -> Div {
26fn meeting_avatar() -> Div {
23 div()
27 div()
@@ -55,7 +59,7 @@ fn call_row(
55 h_flex()
59 h_flex()
56 .id(SharedString::from(format!("call-{}", row.key)))
60 .id(SharedString::from(format!("call-{}", row.key)))
57 .mx(px(8.))
61 .mx(px(8.))
58 .h(px(ROW_HEIGHT))
62 .h(px(CALL_ROW_HEIGHT))
59 .px(px(8.))
63 .px(px(8.))
60 .gap(px(10.))
64 .gap(px(10.))
61 .items_center()
65 .items_center()
@@ -141,6 +145,7 @@ fn call_row(
141}
145}
142
146
143fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
147fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
148 let meet_state = state.clone();
144 let id_state = state.clone();
149 let id_state = state.clone();
145 let paste_state = state.clone();
150 let paste_state = state.clone();
146 h_flex()
151 h_flex()
@@ -148,6 +153,16 @@ fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
148 .px(px(12.))
153 .px(px(12.))
149 .pb(px(8.))
154 .pb(px(8.))
150 .gap(px(8.))
155 .gap(px(8.))
156 .flex_wrap()
157 .child(
158 Button::new("meet-now")
159 .small()
160 .primary()
161 .label("Meet now")
162 .on_click(move |_, _, cx| {
163 meet_state.update(cx, |state, cx| state.start_meet_now(cx));
164 }),
165 )
151 .child(
166 .child(
152 Button::new("join-with-id")
167 Button::new("join-with-id")
153 .small()
168 .small()
@@ -164,34 +179,154 @@ fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
164 )
179 )
165}
180}
166
181
167pub fn calls_body(state: &Entity<AppState>, scroll: &ScrollHandle, cx: &App) -> AnyElement {
182fn section_header(title: &'static str) -> AnyElement {
168 let app = state.read(cx);
183 div()
184 .h(px(SECTION_HEIGHT))
185 .px(px(16.))
186 .flex()
187 .items_end()
188 .pb(px(4.))
189 .text_size(px(12.))
190 .font_weight(FontWeight::SEMIBOLD)
191 .text_color(theme::text_muted())
192 .child(title)
193 .into_any_element()
194}
195
196fn day_header(label: &str) -> AnyElement {
197 div()
198 .h(px(DAY_HEIGHT))
199 .px(px(16.))
200 .flex()
201 .items_center()
202 .text_size(px(11.5))
203 .text_color(theme::text_faint())
204 .child(label.to_owned())
205 .into_any_element()
206}
207
208fn empty_row(text: &'static str) -> AnyElement {
209 div()
210 .h(px(EMPTY_HEIGHT))
211 .flex()
212 .items_center()
213 .justify_center()
214 .text_size(px(13.))
215 .text_color(theme::text_muted())
216 .child(text)
217 .into_any_element()
218}
219
220fn agenda_row(state: &Entity<AppState>, row: &AgendaRow, joinable: bool) -> AnyElement {
221 let click_state = state.clone();
222 let click_row = row.clone();
223 let join_state = state.clone();
224 let join_row = row.clone();
225 h_flex()
226 .id(SharedString::from(format!("agenda-{}", row.key)))
227 .mx(px(8.))
228 .h(px(AGENDA_ROW_HEIGHT))
229 .px(px(8.))
230 .gap(px(10.))
231 .items_center()
232 .rounded(px(8.))
233 .cursor_pointer()
234 .hover(|row| row.bg(theme::row_hover()))
235 .child(
236 div()
237 .w(px(TIME_COLUMN_WIDTH))
238 .flex_none()
239 .text_size(px(12.))
240 .text_color(theme::text_muted())
241 .child(row.time_label.clone()),
242 )
243 .child(
244 v_flex()
245 .flex_1()
246 .min_w_0()
247 .gap(px(2.))
248 .child(
249 div()
250 .truncate()
251 .text_size(px(14.))
252 .text_color(theme::text())
253 .child(row.subject.clone()),
254 )
255 .when(!row.detail.is_empty(), |column| {
256 column.child(
257 div()
258 .truncate()
259 .text_size(px(12.5))
260 .text_color(theme::text_muted())
261 .child(row.detail.clone()),
262 )
263 }),
264 )
265 .when(joinable, |line| {
266 line.child(
267 Button::new(SharedString::from(format!("agenda-join-{}", row.key)))
268 .small()
269 .primary()
270 .label("Join")
271 .on_click(move |_, _, cx| {
272 cx.stop_propagation();
273 join_state.update(cx, |state, cx| state.join_agenda_row(&join_row, cx));
274 }),
275 )
276 })
277 .on_click(move |_, _, cx| {
278 click_state.update(cx, |state, cx| state.open_agenda_chat(&click_row, cx));
279 })
280 .into_any_element()
281}
282
283pub fn calls_body(
284 state: &Entity<AppState>,
285 scroll: &ScrollHandle,
286 window_height: f32,
287 cx: &mut App,
288) -> AnyElement {
289 let now = Utc::now();
169 let offset = Local::now().offset().fix();
290 let offset = Local::now().offset().fix();
170 let rows = call_rows(&app.call_history, &app.sidebar.chats, Utc::now(), offset);
291 if state.read(cx).calls_list.needs_rebuild(now, offset) {
171 let list = if rows.is_empty() {
292 let rebuild_state = state.clone();
172 div()
293 cx.defer(move |cx| rebuild_state.update(cx, |state, cx| state.rebuild_calls_list(cx)));
173 .w_full()
294 }
174 .py(px(24.))
295 let top = -f32::from(scroll.offset().y);
175 .flex()
296 let measured = f32::from(scroll.bounds().size.height);
176 .justify_center()
297 let height = if measured > 1. {
177 .text_size(px(13.))
298 measured
178 .text_color(theme::text_muted())
179 .child(EMPTY_TEXT)
180 .into_any_element()
181 } else {
299 } else {
182 v_flex()
300 window_height.max(FALLBACK_VIEWPORT)
183 .w_full()
184 .pb(px(12.))
185 .children(rows.iter().map(|row| {
186 call_row(
187 state,
188 row,
189 app.can_open_chat_of_call_row(row),
190 &app.directory,
191 )
192 }))
193 .into_any_element()
194 };
301 };
302 let app = state.read(cx);
303 let window = app
304 .calls_list
305 .window(top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
306 let entries = &app.calls_list.entries()[window.range.clone()];
307 let mut list = v_flex().w_full().pb(px(12.));
308 if window.before > 0. {
309 list = list.child(div().h(px(window.before)).flex_none());
310 }
311 for entry in entries {
312 list = list.child(match entry {
313 ListEntry::Section(title) => section_header(title),
314 ListEntry::Day(label) => day_header(label),
315 ListEntry::Empty(text) => empty_row(text),
316 ListEntry::Agenda(row) => {
317 agenda_row(state, row, join_available(row.start, row.end, now) && row.join_url.is_some())
318 }
319 ListEntry::Call(row) => call_row(
320 state,
321 row,
322 app.can_open_chat_of_call_row(row),
323 &app.directory,
324 ),
325 });
326 }
327 if window.after > 0. {
328 list = list.child(div().h(px(window.after)).flex_none());
329 }
195 v_flex()
330 v_flex()
196 .flex_1()
331 .flex_1()
197 .min_h_0()
332 .min_h_0()
crates/app/src/views/shell.rs +7 −0
@@ -71,6 +71,7 @@ pub struct AppShell {
71 71 _subscription: Subscription,
72 72 _activity_observation: Subscription,
73 73 _escape_observation: Subscription,
74 _activation_observation: Subscription,
74 75 }
75 76
76 77 impl AppShell {
@@ -127,6 +128,11 @@ impl AppShell {
127 128 this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));
128 129 }
129 130 });
131 let activation_observation = cx.observe_window_activation(window, |this, window, cx| {
132 if window.is_window_active() {
133 this.state.update(cx, |state, cx| state.refresh_calendar(cx));
134 }
135 });
130 136 let closing = notifications.clone();
131 137 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
132 138 let mut shell = AppShell {
@@ -149,6 +155,7 @@ impl AppShell {
149 155 _subscription: subscription,
150 156 _activity_observation: activity_observation,
151 157 _escape_observation: escape_observation,
158 _activation_observation: activation_observation,
152 159 };
153 160 shell.apply_open_target(cx);
154 161 let Startup {
@@ -71,6 +71,7 @@ pub struct AppShell {
71 _subscription: Subscription,
71 _subscription: Subscription,
72 _activity_observation: Subscription,
72 _activity_observation: Subscription,
73 _escape_observation: Subscription,
73 _escape_observation: Subscription,
74 _activation_observation: Subscription,
74}
75}
75
76
76impl AppShell {
77impl AppShell {
@@ -127,6 +128,11 @@ impl AppShell {
127 this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));
128 this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));
128 }
129 }
129 });
130 });
131 let activation_observation = cx.observe_window_activation(window, |this, window, cx| {
132 if window.is_window_active() {
133 this.state.update(cx, |state, cx| state.refresh_calendar(cx));
134 }
135 });
130 let closing = notifications.clone();
136 let closing = notifications.clone();
131 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
137 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
132 let mut shell = AppShell {
138 let mut shell = AppShell {
@@ -149,6 +155,7 @@ impl AppShell {
149 _subscription: subscription,
155 _subscription: subscription,
150 _activity_observation: activity_observation,
156 _activity_observation: activity_observation,
151 _escape_observation: escape_observation,
157 _escape_observation: escape_observation,
158 _activation_observation: activation_observation,
152 };
159 };
153 shell.apply_open_target(cx);
160 shell.apply_open_target(cx);
154 let Startup {
161 let Startup {
crates/app/src/views/sidebar.rs +6 −2
@@ -334,6 +334,7 @@ impl SidebarView {
334 334 if matches!(
335 335 event,
336 336 AppEvent::Sidebar
337 | AppEvent::CallHistory
337 338 | AppEvent::Selection
338 339 | AppEvent::Directory
339 340 | AppEvent::Typing
@@ -378,7 +379,10 @@ impl SidebarView {
378 379 fn open_tab(&mut self, tab: SidebarTab, cx: &mut Context<Self>) {
379 380 self.tab = tab;
380 381 if tab == SidebarTab::Calls {
381 self.state.update(cx, |state, cx| state.refresh_call_history(cx));
382 self.state.update(cx, |state, cx| {
383 state.refresh_call_history(cx);
384 state.refresh_calendar(cx);
385 });
382 386 }
383 387 cx.notify();
384 388 }
@@ -1476,7 +1480,7 @@ impl Render for SidebarView {
1476 1480 let body = match self.tab {
1477 1481 SidebarTab::Chats => self.chats_body(window_height, cx),
1478 1482 SidebarTab::Channels => self.channels_body(cx),
1479 SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, cx),
1483 SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, window_height, cx),
1480 1484 };
1481 1485 v_flex()
1482 1486 .w(px(SIDEBAR_WIDTH))
@@ -334,6 +334,7 @@ impl SidebarView {
334 if matches!(
334 if matches!(
335 event,
335 event,
336 AppEvent::Sidebar
336 AppEvent::Sidebar
337 | AppEvent::CallHistory
337 | AppEvent::Selection
338 | AppEvent::Selection
338 | AppEvent::Directory
339 | AppEvent::Directory
339 | AppEvent::Typing
340 | AppEvent::Typing
@@ -378,7 +379,10 @@ impl SidebarView {
378 fn open_tab(&mut self, tab: SidebarTab, cx: &mut Context<Self>) {
379 fn open_tab(&mut self, tab: SidebarTab, cx: &mut Context<Self>) {
379 self.tab = tab;
380 self.tab = tab;
380 if tab == SidebarTab::Calls {
381 if tab == SidebarTab::Calls {
381 self.state.update(cx, |state, cx| state.refresh_call_history(cx));
382 self.state.update(cx, |state, cx| {
383 state.refresh_call_history(cx);
384 state.refresh_calendar(cx);
385 });
382 }
386 }
383 cx.notify();
387 cx.notify();
384 }
388 }
@@ -1476,7 +1480,7 @@ impl Render for SidebarView {
1476 let body = match self.tab {
1480 let body = match self.tab {
1477 SidebarTab::Chats => self.chats_body(window_height, cx),
1481 SidebarTab::Chats => self.chats_body(window_height, cx),
1478 SidebarTab::Channels => self.channels_body(cx),
1482 SidebarTab::Channels => self.channels_body(cx),
1479 SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, cx),
1483 SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, window_height, cx),
1480 };
1484 };
1481 v_flex()
1485 v_flex()
1482 .w(px(SIDEBAR_WIDTH))
1486 .w(px(SIDEBAR_WIDTH))
crates/chatsvc/examples/calendar_probe.rs added +46 −0
@@ -0,0 +1,46 @@
1 use chatsvc::{Calendar, parse_calendar_events};
2 use chrono::{Duration, Utc};
3 use session::{DEFAULT_ENDPOINT, Session};
4
5 #[tokio::main]
6 async fn main() {
7 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
8 let session = Session::connect(&endpoint).await.expect("browser");
9 let start = Utc::now()
10 .date_naive()
11 .and_hms_opt(0, 0, 0)
12 .expect("midnight")
13 .and_utc();
14 let answer = Calendar::new(&session)
15 .view_response(start, start + Duration::days(7))
16 .await
17 .expect("calendar view");
18 let events = parse_calendar_events(&answer.body);
19 println!("# calendar view: HTTP {}", answer.status);
20 println!("# events: {}", events.len());
21 println!(
22 "# with join url: {}",
23 events
24 .iter()
25 .filter(|event| event.join_url.is_some())
26 .count()
27 );
28 println!(
29 "# online: {}",
30 events.iter().filter(|event| event.online).count()
31 );
32 println!(
33 "# with thread: {}",
34 events.iter().filter(|event| event.thread_id.is_some()).count()
35 );
36 println!(
37 "# with organizer name: {}",
38 events.iter().filter(|event| event.organizer_name.is_some()).count()
39 );
40 println!(
41 "# not responded: {}, cancelled: {}, all day: {}",
42 events.iter().filter(|event| event.response == chatsvc::ResponseType::NotResponded).count(),
43 events.iter().filter(|event| event.cancelled).count(),
44 events.iter().filter(|event| event.all_day).count()
45 );
46 }
@@ -0,0 +1,46 @@
1use chatsvc::{Calendar, parse_calendar_events};
2use chrono::{Duration, Utc};
3use session::{DEFAULT_ENDPOINT, Session};
4
5#[tokio::main]
6async fn main() {
7 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
8 let session = Session::connect(&endpoint).await.expect("browser");
9 let start = Utc::now()
10 .date_naive()
11 .and_hms_opt(0, 0, 0)
12 .expect("midnight")
13 .and_utc();
14 let answer = Calendar::new(&session)
15 .view_response(start, start + Duration::days(7))
16 .await
17 .expect("calendar view");
18 let events = parse_calendar_events(&answer.body);
19 println!("# calendar view: HTTP {}", answer.status);
20 println!("# events: {}", events.len());
21 println!(
22 "# with join url: {}",
23 events
24 .iter()
25 .filter(|event| event.join_url.is_some())
26 .count()
27 );
28 println!(
29 "# online: {}",
30 events.iter().filter(|event| event.online).count()
31 );
32 println!(
33 "# with thread: {}",
34 events.iter().filter(|event| event.thread_id.is_some()).count()
35 );
36 println!(
37 "# with organizer name: {}",
38 events.iter().filter(|event| event.organizer_name.is_some()).count()
39 );
40 println!(
41 "# not responded: {}, cancelled: {}, all day: {}",
42 events.iter().filter(|event| event.response == chatsvc::ResponseType::NotResponded).count(),
43 events.iter().filter(|event| event.cancelled).count(),
44 events.iter().filter(|event| event.all_day).count()
45 );
46}
crates/chatsvc/src/calendar.rs added +319 −0
@@ -0,0 +1,319 @@
1 use chrono::{DateTime, NaiveDateTime, Utc};
2 use serde_json::Value;
3 use session::{ApiResponse, Method, Request, Session};
4
5 use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, spaces_scope};
6 use crate::error::{Error, Result};
7
8 const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";
9 const NAIVE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.f";
10
11 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12 pub enum ResponseType {
13 Organizer,
14 Accepted,
15 Tentative,
16 Declined,
17 #[default]
18 NotResponded,
19 }
20
21 #[derive(Debug, Clone, PartialEq, Eq)]
22 pub struct CalendarEvent {
23 pub object_id: String,
24 pub subject: String,
25 pub start: DateTime<Utc>,
26 pub end: DateTime<Utc>,
27 pub all_day: bool,
28 pub cancelled: bool,
29 pub online: bool,
30 pub join_url: Option<String>,
31 pub thread_id: Option<String>,
32 pub organizer_name: Option<String>,
33 pub organizer_address: Option<String>,
34 pub response: ResponseType,
35 }
36
37 pub struct Calendar<T: CardTransport = SessionCardTransport> {
38 transport: T,
39 url: String,
40 create_url: String,
41 }
42
43 impl Calendar<SessionCardTransport> {
44 pub fn new(session: &Session) -> Self {
45 Calendar::with_transport(SessionCardTransport::new(session), DEFAULT_MT_REGION)
46 }
47 }
48
49 impl<T: CardTransport> Calendar<T> {
50 pub fn with_transport(transport: T, mt_region: &str) -> Self {
51 Calendar {
52 transport,
53 url: format!(
54 "https://teams.cloud.microsoft/api/mt/{mt_region}/v2.1/me/calendars/calendarView"
55 ),
56 create_url: format!(
57 "https://teams.cloud.microsoft/api/mt/{mt_region}/beta/me/calendarEvents/privateMeeting/schedulingService/create"
58 ),
59 }
60 }
61
62 pub async fn calendar_view(
63 &self,
64 start: DateTime<Utc>,
65 end: DateTime<Utc>,
66 ) -> Result<Vec<CalendarEvent>> {
67 let answer = self.view_response(start, end).await?;
68 if !answer.is_success() {
69 return Err(Error::Session(session::Error::api(
70 answer.status,
71 &self.url,
72 answer.body,
73 )));
74 }
75 Ok(parse_calendar_events(&answer.body))
76 }
77
78 pub async fn view_response(
79 &self,
80 start: DateTime<Utc>,
81 end: DateTime<Utc>,
82 ) -> Result<ApiResponse> {
83 let url = format!(
84 "{}?startDate={}&endDate={}",
85 self.url,
86 start.format(QUERY_TIME_FORMAT),
87 end.format(QUERY_TIME_FORMAT)
88 );
89 self.transport.send(Request::get(url), spaces_scope()).await
90 }
91 }
92
93 impl<T: CardTransport> Calendar<T> {
94 pub async fn create_meet_now(&self, subject: &str) -> Result<String> {
95 let body = serde_json::json!({
96 "meetingType": "MeetNow",
97 "isStreamEnabled": false,
98 "subject": subject,
99 "unhideChatThread": true,
100 });
101 let answer = self
102 .transport
103 .send(Request::with_body(Method::Post, &self.create_url, body), spaces_scope())
104 .await?;
105 if !answer.is_success() {
106 return Err(Error::Session(session::Error::api(
107 answer.status,
108 &self.create_url,
109 answer.body,
110 )));
111 }
112 meet_now_join_url(&answer.body).ok_or_else(|| {
113 Error::Session(session::Error::api(answer.status, &self.create_url, answer.body))
114 })
115 }
116 }
117
118 pub fn meet_now_join_url(body: &Value) -> Option<String> {
119 let value = body.get("value")?;
120 value
121 .pointer("/links/join")
122 .or_else(|| value.get("meetingUrl"))
123 .and_then(Value::as_str)
124 .map(str::to_owned)
125 }
126
127 pub fn parse_calendar_events(body: &Value) -> Vec<CalendarEvent> {
128 let entries = body.get("value").unwrap_or(body);
129 let mut events: Vec<CalendarEvent> = entries
130 .as_array()
131 .into_iter()
132 .flatten()
133 .filter_map(parse_event)
134 .collect();
135 events.sort_by_key(|event| (event.start, event.end));
136 events
137 }
138
139 fn text(entry: &Value, key: &str) -> Option<String> {
140 entry
141 .get(key)?
142 .as_str()
143 .filter(|text| !text.is_empty())
144 .map(str::to_owned)
145 }
146
147 fn flag(entry: &Value, key: &str) -> bool {
148 entry.get(key).and_then(Value::as_bool).unwrap_or(false)
149 }
150
151 fn time(entry: &Value, key: &str) -> Option<DateTime<Utc>> {
152 let text = entry.get(key)?.as_str()?;
153 DateTime::parse_from_rfc3339(text)
154 .map(|time| time.with_timezone(&Utc))
155 .or_else(|_| {
156 NaiveDateTime::parse_from_str(text, NAIVE_TIME_FORMAT).map(|time| time.and_utc())
157 })
158 .ok()
159 }
160
161 fn thread_id(entry: &Value) -> Option<String> {
162 text(entry, "threadId").or_else(|| {
163 let data: Value = serde_json::from_str(entry.get("skypeTeamsData")?.as_str()?).ok()?;
164 text(&data, "cid")
165 })
166 }
167
168 fn response_type(entry: &Value) -> ResponseType {
169 let label = text(entry, "myResponseType").or_else(|| {
170 let status = entry.get("responseStatus")?;
171 status
172 .as_str()
173 .map(str::to_owned)
174 .or_else(|| text(status, "response"))
175 });
176 match label.as_deref() {
177 Some("Organizer") => ResponseType::Organizer,
178 Some("Accepted") => ResponseType::Accepted,
179 Some("TentativelyAccepted" | "Tentative") => ResponseType::Tentative,
180 Some("Declined") => ResponseType::Declined,
181 _ => ResponseType::NotResponded,
182 }
183 }
184
185 fn parse_event(entry: &Value) -> Option<CalendarEvent> {
186 let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));
187 Some(CalendarEvent {
188 object_id: text(entry, "objectId").or_else(|| text(entry, "id"))?,
189 subject: text(entry, "subject").unwrap_or_default(),
190 start: time(entry, "startTime")?,
191 end: time(entry, "endTime")?,
192 all_day: flag(entry, "isAllDayEvent") || flag(entry, "isAllDay"),
193 cancelled: flag(entry, "isCancelled"),
194 online: flag(entry, "isOnlineMeeting") || join_url.is_some(),
195 join_url,
196 thread_id: thread_id(entry),
197 organizer_name: text(entry, "organizerName"),
198 organizer_address: text(entry, "organizerAddress"),
199 response: response_type(entry),
200 })
201 }
202
203 #[cfg(test)]
204 mod tests {
205 #[test]
206 fn meet_now_join_url_prefers_the_join_link() {
207 let body = serde_json::json!({"value": {
208 "links": {"join": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_a%40thread.v2/0"},
209 "meetingUrl": "https://example.invalid/other",
210 }});
211 assert_eq!(
212 meet_now_join_url(&body).as_deref(),
213 Some("https://teams.microsoft.com/l/meetup-join/19%3ameeting_a%40thread.v2/0")
214 );
215 assert_eq!(meet_now_join_url(&serde_json::json!({"value": {}})), None);
216 }
217
218 use std::sync::Mutex;
219
220 use chrono::{Duration, TimeZone};
221 use session::Scope;
222
223 use super::*;
224
225 struct Canned {
226 body: Value,
227 sent: Mutex<Vec<(Request, Scope)>>,
228 }
229
230 impl CardTransport for Canned {
231 async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {
232 self.sent.lock().unwrap().push((request, scope));
233 Ok(ApiResponse {
234 status: 200,
235 body: self.body.clone(),
236 retry_after: None,
237 })
238 }
239 }
240
241 fn fixture() -> Value {
242 serde_json::from_str(include_str!("../tests/fixtures/calendar_view.json")).unwrap()
243 }
244
245 #[test]
246 fn events_are_parsed_and_sorted_by_start() {
247 let events = parse_calendar_events(&fixture());
248 assert_eq!(events.len(), 4);
249 let offsite = &events[0];
250 assert!(offsite.all_day);
251 assert!(!offsite.online);
252 assert_eq!(offsite.join_url, None);
253 assert_eq!(offsite.thread_id, None);
254 assert_eq!(offsite.response, ResponseType::NotResponded);
255 let standup = &events[1];
256 assert_eq!(standup.subject, "Team standup");
257 assert_eq!(
258 standup.start,
259 Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap()
260 );
261 assert_eq!(standup.organizer_name.as_deref(), Some("Mara Lindqvist"));
262 assert_eq!(
263 standup.join_url.as_deref(),
264 Some("https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo1%40thread.v2/0")
265 );
266 assert!(standup.online);
267 assert_eq!(standup.response, ResponseType::Accepted);
268 assert_eq!(
269 standup.thread_id.as_deref(),
270 Some("19:meeting_demo1@thread.v2")
271 );
272 }
273
274 #[test]
275 fn zone_less_times_and_embedded_thread_data_are_understood() {
276 let events = parse_calendar_events(&fixture());
277 let review = &events[2];
278 assert_eq!(review.response, ResponseType::Tentative);
279 assert_eq!(
280 review.thread_id.as_deref(),
281 Some("19:meeting_demo2@thread.v2")
282 );
283 assert_eq!(
284 review.start,
285 Utc.with_ymd_and_hms(2026, 10, 12, 13, 0, 0).unwrap()
286 );
287 assert!(events[3].cancelled);
288 }
289
290 #[test]
291 fn entries_without_an_id_or_times_are_skipped() {
292 let body =
293 serde_json::json!({"value": [{"subject": "x"}, {"objectId": "a", "subject": "y"}]});
294 assert!(parse_calendar_events(&body).is_empty());
295 }
296
297 #[tokio::test]
298 async fn calendar_view_gets_the_range_with_the_spaces_scope() {
299 let calendar = Calendar::with_transport(
300 Canned {
301 body: fixture(),
302 sent: Mutex::new(Vec::new()),
303 },
304 "emea",
305 );
306 let start = Utc.with_ymd_and_hms(2026, 10, 12, 0, 0, 0).unwrap();
307 let events = calendar
308 .calendar_view(start, start + Duration::days(7))
309 .await
310 .unwrap();
311 assert_eq!(events.len(), 4);
312 let sent = calendar.transport.sent.lock().unwrap();
313 assert_eq!(
314 sent[0].0.url,
315 "https://teams.cloud.microsoft/api/mt/emea/v2.1/me/calendars/calendarView?startDate=2026-10-12T00:00:00Z&endDate=2026-10-19T00:00:00Z"
316 );
317 assert_eq!(sent[0].1, spaces_scope());
318 }
319 }
@@ -0,0 +1,319 @@
1use chrono::{DateTime, NaiveDateTime, Utc};
2use serde_json::Value;
3use session::{ApiResponse, Method, Request, Session};
4
5use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, spaces_scope};
6use crate::error::{Error, Result};
7
8const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";
9const NAIVE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.f";
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12pub enum ResponseType {
13 Organizer,
14 Accepted,
15 Tentative,
16 Declined,
17 #[default]
18 NotResponded,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct CalendarEvent {
23 pub object_id: String,
24 pub subject: String,
25 pub start: DateTime<Utc>,
26 pub end: DateTime<Utc>,
27 pub all_day: bool,
28 pub cancelled: bool,
29 pub online: bool,
30 pub join_url: Option<String>,
31 pub thread_id: Option<String>,
32 pub organizer_name: Option<String>,
33 pub organizer_address: Option<String>,
34 pub response: ResponseType,
35}
36
37pub struct Calendar<T: CardTransport = SessionCardTransport> {
38 transport: T,
39 url: String,
40 create_url: String,
41}
42
43impl Calendar<SessionCardTransport> {
44 pub fn new(session: &Session) -> Self {
45 Calendar::with_transport(SessionCardTransport::new(session), DEFAULT_MT_REGION)
46 }
47}
48
49impl<T: CardTransport> Calendar<T> {
50 pub fn with_transport(transport: T, mt_region: &str) -> Self {
51 Calendar {
52 transport,
53 url: format!(
54 "https://teams.cloud.microsoft/api/mt/{mt_region}/v2.1/me/calendars/calendarView"
55 ),
56 create_url: format!(
57 "https://teams.cloud.microsoft/api/mt/{mt_region}/beta/me/calendarEvents/privateMeeting/schedulingService/create"
58 ),
59 }
60 }
61
62 pub async fn calendar_view(
63 &self,
64 start: DateTime<Utc>,
65 end: DateTime<Utc>,
66 ) -> Result<Vec<CalendarEvent>> {
67 let answer = self.view_response(start, end).await?;
68 if !answer.is_success() {
69 return Err(Error::Session(session::Error::api(
70 answer.status,
71 &self.url,
72 answer.body,
73 )));
74 }
75 Ok(parse_calendar_events(&answer.body))
76 }
77
78 pub async fn view_response(
79 &self,
80 start: DateTime<Utc>,
81 end: DateTime<Utc>,
82 ) -> Result<ApiResponse> {
83 let url = format!(
84 "{}?startDate={}&endDate={}",
85 self.url,
86 start.format(QUERY_TIME_FORMAT),
87 end.format(QUERY_TIME_FORMAT)
88 );
89 self.transport.send(Request::get(url), spaces_scope()).await
90 }
91}
92
93impl<T: CardTransport> Calendar<T> {
94 pub async fn create_meet_now(&self, subject: &str) -> Result<String> {
95 let body = serde_json::json!({
96 "meetingType": "MeetNow",
97 "isStreamEnabled": false,
98 "subject": subject,
99 "unhideChatThread": true,
100 });
101 let answer = self
102 .transport
103 .send(Request::with_body(Method::Post, &self.create_url, body), spaces_scope())
104 .await?;
105 if !answer.is_success() {
106 return Err(Error::Session(session::Error::api(
107 answer.status,
108 &self.create_url,
109 answer.body,
110 )));
111 }
112 meet_now_join_url(&answer.body).ok_or_else(|| {
113 Error::Session(session::Error::api(answer.status, &self.create_url, answer.body))
114 })
115 }
116}
117
118pub fn meet_now_join_url(body: &Value) -> Option<String> {
119 let value = body.get("value")?;
120 value
121 .pointer("/links/join")
122 .or_else(|| value.get("meetingUrl"))
123 .and_then(Value::as_str)
124 .map(str::to_owned)
125}
126
127pub fn parse_calendar_events(body: &Value) -> Vec<CalendarEvent> {
128 let entries = body.get("value").unwrap_or(body);
129 let mut events: Vec<CalendarEvent> = entries
130 .as_array()
131 .into_iter()
132 .flatten()
133 .filter_map(parse_event)
134 .collect();
135 events.sort_by_key(|event| (event.start, event.end));
136 events
137}
138
139fn text(entry: &Value, key: &str) -> Option<String> {
140 entry
141 .get(key)?
142 .as_str()
143 .filter(|text| !text.is_empty())
144 .map(str::to_owned)
145}
146
147fn flag(entry: &Value, key: &str) -> bool {
148 entry.get(key).and_then(Value::as_bool).unwrap_or(false)
149}
150
151fn time(entry: &Value, key: &str) -> Option<DateTime<Utc>> {
152 let text = entry.get(key)?.as_str()?;
153 DateTime::parse_from_rfc3339(text)
154 .map(|time| time.with_timezone(&Utc))
155 .or_else(|_| {
156 NaiveDateTime::parse_from_str(text, NAIVE_TIME_FORMAT).map(|time| time.and_utc())
157 })
158 .ok()
159}
160
161fn thread_id(entry: &Value) -> Option<String> {
162 text(entry, "threadId").or_else(|| {
163 let data: Value = serde_json::from_str(entry.get("skypeTeamsData")?.as_str()?).ok()?;
164 text(&data, "cid")
165 })
166}
167
168fn response_type(entry: &Value) -> ResponseType {
169 let label = text(entry, "myResponseType").or_else(|| {
170 let status = entry.get("responseStatus")?;
171 status
172 .as_str()
173 .map(str::to_owned)
174 .or_else(|| text(status, "response"))
175 });
176 match label.as_deref() {
177 Some("Organizer") => ResponseType::Organizer,
178 Some("Accepted") => ResponseType::Accepted,
179 Some("TentativelyAccepted" | "Tentative") => ResponseType::Tentative,
180 Some("Declined") => ResponseType::Declined,
181 _ => ResponseType::NotResponded,
182 }
183}
184
185fn parse_event(entry: &Value) -> Option<CalendarEvent> {
186 let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));
187 Some(CalendarEvent {
188 object_id: text(entry, "objectId").or_else(|| text(entry, "id"))?,
189 subject: text(entry, "subject").unwrap_or_default(),
190 start: time(entry, "startTime")?,
191 end: time(entry, "endTime")?,
192 all_day: flag(entry, "isAllDayEvent") || flag(entry, "isAllDay"),
193 cancelled: flag(entry, "isCancelled"),
194 online: flag(entry, "isOnlineMeeting") || join_url.is_some(),
195 join_url,
196 thread_id: thread_id(entry),
197 organizer_name: text(entry, "organizerName"),
198 organizer_address: text(entry, "organizerAddress"),
199 response: response_type(entry),
200 })
201}
202
203#[cfg(test)]
204mod tests {
205 #[test]
206 fn meet_now_join_url_prefers_the_join_link() {
207 let body = serde_json::json!({"value": {
208 "links": {"join": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_a%40thread.v2/0"},
209 "meetingUrl": "https://example.invalid/other",
210 }});
211 assert_eq!(
212 meet_now_join_url(&body).as_deref(),
213 Some("https://teams.microsoft.com/l/meetup-join/19%3ameeting_a%40thread.v2/0")
214 );
215 assert_eq!(meet_now_join_url(&serde_json::json!({"value": {}})), None);
216 }
217
218 use std::sync::Mutex;
219
220 use chrono::{Duration, TimeZone};
221 use session::Scope;
222
223 use super::*;
224
225 struct Canned {
226 body: Value,
227 sent: Mutex<Vec<(Request, Scope)>>,
228 }
229
230 impl CardTransport for Canned {
231 async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {
232 self.sent.lock().unwrap().push((request, scope));
233 Ok(ApiResponse {
234 status: 200,
235 body: self.body.clone(),
236 retry_after: None,
237 })
238 }
239 }
240
241 fn fixture() -> Value {
242 serde_json::from_str(include_str!("../tests/fixtures/calendar_view.json")).unwrap()
243 }
244
245 #[test]
246 fn events_are_parsed_and_sorted_by_start() {
247 let events = parse_calendar_events(&fixture());
248 assert_eq!(events.len(), 4);
249 let offsite = &events[0];
250 assert!(offsite.all_day);
251 assert!(!offsite.online);
252 assert_eq!(offsite.join_url, None);
253 assert_eq!(offsite.thread_id, None);
254 assert_eq!(offsite.response, ResponseType::NotResponded);
255 let standup = &events[1];
256 assert_eq!(standup.subject, "Team standup");
257 assert_eq!(
258 standup.start,
259 Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap()
260 );
261 assert_eq!(standup.organizer_name.as_deref(), Some("Mara Lindqvist"));
262 assert_eq!(
263 standup.join_url.as_deref(),
264 Some("https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo1%40thread.v2/0")
265 );
266 assert!(standup.online);
267 assert_eq!(standup.response, ResponseType::Accepted);
268 assert_eq!(
269 standup.thread_id.as_deref(),
270 Some("19:meeting_demo1@thread.v2")
271 );
272 }
273
274 #[test]
275 fn zone_less_times_and_embedded_thread_data_are_understood() {
276 let events = parse_calendar_events(&fixture());
277 let review = &events[2];
278 assert_eq!(review.response, ResponseType::Tentative);
279 assert_eq!(
280 review.thread_id.as_deref(),
281 Some("19:meeting_demo2@thread.v2")
282 );
283 assert_eq!(
284 review.start,
285 Utc.with_ymd_and_hms(2026, 10, 12, 13, 0, 0).unwrap()
286 );
287 assert!(events[3].cancelled);
288 }
289
290 #[test]
291 fn entries_without_an_id_or_times_are_skipped() {
292 let body =
293 serde_json::json!({"value": [{"subject": "x"}, {"objectId": "a", "subject": "y"}]});
294 assert!(parse_calendar_events(&body).is_empty());
295 }
296
297 #[tokio::test]
298 async fn calendar_view_gets_the_range_with_the_spaces_scope() {
299 let calendar = Calendar::with_transport(
300 Canned {
301 body: fixture(),
302 sent: Mutex::new(Vec::new()),
303 },
304 "emea",
305 );
306 let start = Utc.with_ymd_and_hms(2026, 10, 12, 0, 0, 0).unwrap();
307 let events = calendar
308 .calendar_view(start, start + Duration::days(7))
309 .await
310 .unwrap();
311 assert_eq!(events.len(), 4);
312 let sent = calendar.transport.sent.lock().unwrap();
313 assert_eq!(
314 sent[0].0.url,
315 "https://teams.cloud.microsoft/api/mt/emea/v2.1/me/calendars/calendarView?startDate=2026-10-12T00:00:00Z&endDate=2026-10-19T00:00:00Z"
316 );
317 assert_eq!(sent[0].1, spaces_scope());
318 }
319}
crates/chatsvc/src/lib.rs +2 −0
@@ -1,3 +1,4 @@
1 pub mod calendar;
1 2 pub mod calllog;
2 3 pub mod cards;
3 4 pub mod channel_notifications;
@@ -19,6 +20,7 @@ pub mod saved;
19 20 pub mod settings;
20 21 pub mod translate;
21 22
23 pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
22 24 pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
23 25 pub use cards::{
24 26 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
@@ -1,3 +1,4 @@
1pub mod calendar;
1pub mod calllog;
2pub mod calllog;
2pub mod cards;
3pub mod cards;
3pub mod channel_notifications;
4pub mod channel_notifications;
@@ -19,6 +20,7 @@ pub mod saved;
19pub mod settings;
20pub mod settings;
20pub mod translate;
21pub mod translate;
21
22
23pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
22pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
24pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
23pub use cards::{
25pub use cards::{
24 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
26 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
crates/chatsvc/tests/fixtures/calendar_view.json added +50 −0
@@ -0,0 +1,50 @@
1 {
2 "value": [
3 {
4 "objectId": "evt-review",
5 "subject": "Design review",
6 "startTime": "2026-10-12T13:00:00.0000000",
7 "endTime": "2026-10-12T14:00:00.0000000",
8 "isAllDayEvent": false,
9 "isCancelled": false,
10 "isOnlineMeeting": true,
11 "organizerName": "Jonas Ortega",
12 "organizerAddress": "jonas@example.invalid",
13 "myResponseType": "TentativelyAccepted",
14 "skypeTeamsMeetingUrl": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo2%40thread.v2/0",
15 "skypeTeamsData": "{\"cid\":\"19:meeting_demo2@thread.v2\",\"mid\":0}"
16 },
17 {
18 "objectId": "evt-standup",
19 "subject": "Team standup",
20 "startTime": "2026-10-12T08:30:00Z",
21 "endTime": "2026-10-12T08:45:00Z",
22 "isAllDayEvent": false,
23 "isCancelled": false,
24 "isOnlineMeeting": true,
25 "organizerName": "Mara Lindqvist",
26 "organizerAddress": "mara@example.invalid",
27 "myResponseType": "Accepted",
28 "skypeTeamsMeetingUrl": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo1%40thread.v2/0",
29 "threadId": "19:meeting_demo1@thread.v2"
30 },
31 {
32 "objectId": "evt-offsite",
33 "subject": "Offsite day",
34 "startTime": "2026-10-12T00:00:00Z",
35 "endTime": "2026-10-13T00:00:00Z",
36 "isAllDayEvent": true,
37 "isCancelled": false,
38 "isOnlineMeeting": false
39 },
40 {
41 "objectId": "evt-cancelled",
42 "subject": "Cancelled sync",
43 "startTime": "2026-10-13T09:00:00Z",
44 "endTime": "2026-10-13T09:30:00Z",
45 "isCancelled": true,
46 "isOnlineMeeting": true,
47 "myResponseType": "None"
48 }
49 ]
50 }
@@ -0,0 +1,50 @@
1{
2 "value": [
3 {
4 "objectId": "evt-review",
5 "subject": "Design review",
6 "startTime": "2026-10-12T13:00:00.0000000",
7 "endTime": "2026-10-12T14:00:00.0000000",
8 "isAllDayEvent": false,
9 "isCancelled": false,
10 "isOnlineMeeting": true,
11 "organizerName": "Jonas Ortega",
12 "organizerAddress": "jonas@example.invalid",
13 "myResponseType": "TentativelyAccepted",
14 "skypeTeamsMeetingUrl": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo2%40thread.v2/0",
15 "skypeTeamsData": "{\"cid\":\"19:meeting_demo2@thread.v2\",\"mid\":0}"
16 },
17 {
18 "objectId": "evt-standup",
19 "subject": "Team standup",
20 "startTime": "2026-10-12T08:30:00Z",
21 "endTime": "2026-10-12T08:45:00Z",
22 "isAllDayEvent": false,
23 "isCancelled": false,
24 "isOnlineMeeting": true,
25 "organizerName": "Mara Lindqvist",
26 "organizerAddress": "mara@example.invalid",
27 "myResponseType": "Accepted",
28 "skypeTeamsMeetingUrl": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo1%40thread.v2/0",
29 "threadId": "19:meeting_demo1@thread.v2"
30 },
31 {
32 "objectId": "evt-offsite",
33 "subject": "Offsite day",
34 "startTime": "2026-10-12T00:00:00Z",
35 "endTime": "2026-10-13T00:00:00Z",
36 "isAllDayEvent": true,
37 "isCancelled": false,
38 "isOnlineMeeting": false
39 },
40 {
41 "objectId": "evt-cancelled",
42 "subject": "Cancelled sync",
43 "startTime": "2026-10-13T09:00:00Z",
44 "endTime": "2026-10-13T09:30:00Z",
45 "isCancelled": true,
46 "isOnlineMeeting": true,
47 "myResponseType": "None"
48 }
49 ]
50}