Merge pull request #16: feat(calendar): optional Google Calendar accounts beside Outlook
@@ -193,9 +193,10 @@ Feature parity with the Microsoft Teams desktop client.
193
193
| Calls in chat history | Done | Card per call in the chat on the caller's side: "Call ended" with duration and end time, red "Missed call" with Call back, "Meeting started" / "Meeting ended", live start with Join. Started card hides once the call ended. From Graph call events, cached chats refetch once. Missed incoming call not seen live yet |
194
194
| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |
195
195
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
196
| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Graph `POST /me/events` with `isOnlineMeeting` and `teamsForBusiness`, local wall time in the own mailbox time zone (series keep their time across DST, weekday from the local date). Body building unit tested; never run against a real calendar |
197
| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Graph `accept`, `tentativelyAccept`, `decline`, falls back to the iCalUId lookup when the Teams id is not a Graph id. Not run against a real invitation |
198
| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Snooze and X are saved to the Outlook reminder (Graph snoozeReminder / dismissReminder, occurrence id); reminders snoozed or dismissed in Outlook or on another device are read from reminderView every 60 s near a meeting and are not shown again. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar; push event 128 not wired (the realtime layer does not receive it) |
196
| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Outlook-only home keeps Graph `POST /me/events` with `isOnlineMeeting`. With Google home or extra write targets: Teams join link first, then inserts per target (Outlook with join in location; Google `events.insert`). Settings > Calendar chooses home + dual-write. Body builders unit tested; live Google create needs `TEAMS_GOOGLE_CLIENT_ID` |
197
| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Outlook: Graph `accept` / `tentativelyAccept` / `decline` (+ iCalUId fallback). Google: Calendar API attendee `responseStatus` patch with `sendUpdates`. Source shown on calendar blocks |
198
| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Outlook: Snooze and X go to Graph snoozeReminder / dismissReminder; reminderView every 60 s near a meeting. Google: snooze/dismiss stay local only. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar (Outlook + optional Google merge); push event 128 not wired |
199
| Google Calendar accounts | Partial | Settings > Calendar: Connect Google (OAuth Desktop + PKCE, env `TEAMS_GOOGLE_CLIENT_ID` / optional secret), list calendars, home calendar, extra write targets. Poll merges with Outlook by iCal UID / Teams join URL. Disconnect clears tokens. Manual smoke still needed against a real Google account |
199
200
| Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |
200
201
| Narrow windows in a call | Done | Controls that do not fit move into "..." (View, Reactions, Raise hand, People, Chat; mic, camera, share, "..." and Leave always stay). Below 960 px, or when a side panel would leave the call under 720 px, the chat list hides; still too narrow, the panel overlays the call. Layout guard checks 640x480, 1280x800, 1920x1080 |
201
202
| Give and take control | Missing | Protocol known (main-channel data channel, action codes 0-11); needs a second person and a security review |
@@ -193,9 +193,10 @@ Feature parity with the Microsoft Teams desktop client.193
| Calls in chat history | Done | Card per call in the chat on the caller's side: "Call ended" with duration and end time, red "Missed call" with Call back, "Meeting started" / "Meeting ended", live start with Join. Started card hides once the call ended. From Graph call events, cached chats refetch once. Missed incoming call not seen live yet |193
| Calls in chat history | Done | Card per call in the chat on the caller's side: "Call ended" with duration and end time, red "Missed call" with Call back, "Meeting started" / "Meeting ended", live start with Join. Started card hides once the call ended. From Graph call events, cached chats refetch once. Missed incoming call not seen live yet |194
| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |194
| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |195
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |195
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |196
| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Graph `POST /me/events` with `isOnlineMeeting` and `teamsForBusiness`, local wall time in the own mailbox time zone (series keep their time across DST, weekday from the local date). Body building unit tested; never run against a real calendar |196
| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Outlook-only home keeps Graph `POST /me/events` with `isOnlineMeeting`. With Google home or extra write targets: Teams join link first, then inserts per target (Outlook with join in location; Google `events.insert`). Settings > Calendar chooses home + dual-write. Body builders unit tested; live Google create needs `TEAMS_GOOGLE_CLIENT_ID` |197
| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Graph `accept`, `tentativelyAccept`, `decline`, falls back to the iCalUId lookup when the Teams id is not a Graph id. Not run against a real invitation |197
| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Outlook: Graph `accept` / `tentativelyAccept` / `decline` (+ iCalUId fallback). Google: Calendar API attendee `responseStatus` patch with `sendUpdates`. Source shown on calendar blocks |198
| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Snooze and X are saved to the Outlook reminder (Graph snoozeReminder / dismissReminder, occurrence id); reminders snoozed or dismissed in Outlook or on another device are read from reminderView every 60 s near a meeting and are not shown again. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar; push event 128 not wired (the realtime layer does not receive it) |198
| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Outlook: Snooze and X go to Graph snoozeReminder / dismissReminder; reminderView every 60 s near a meeting. Google: snooze/dismiss stay local only. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar (Outlook + optional Google merge); push event 128 not wired |199
| Google Calendar accounts | Partial | Settings > Calendar: Connect Google (OAuth Desktop + PKCE, env `TEAMS_GOOGLE_CLIENT_ID` / optional secret), list calendars, home calendar, extra write targets. Poll merges with Outlook by iCal UID / Teams join URL. Disconnect clears tokens. Manual smoke still needed against a real Google account |199
| Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |200
| Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |200
| Narrow windows in a call | Done | Controls that do not fit move into "..." (View, Reactions, Raise hand, People, Chat; mic, camera, share, "..." and Leave always stay). Below 960 px, or when a side panel would leave the call under 720 px, the chat list hides; still too narrow, the panel overlays the call. Layout guard checks 640x480, 1280x800, 1920x1080 |201
| Narrow windows in a call | Done | Controls that do not fit move into "..." (View, Reactions, Raise hand, People, Chat; mic, camera, share, "..." and Leave always stay). Below 960 px, or when a side panel would leave the call under 720 px, the chat list hides; still too narrow, the panel overlays the call. Layout guard checks 640x480, 1280x800, 1920x1080 |201
| Give and take control | Missing | Protocol known (main-channel data channel, action codes 0-11); needs a second person and a security review |202
| Give and take control | Missing | Protocol known (main-channel data channel, action codes 0-11); needs a second person and a security review |@@ -1,6 +1,8 @@
1
1
use chatsvc::{CalendarEvent, ResponseType};
2
2
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
3
3
4
use crate::week_grid::is_effective_all_day;
5
4
6
const JOIN_LEAD_MINUTES: i64 = 5;
5
7
const AGENDA_DAYS: i64 = 7;
6
8
const ALL_DAY_LABEL: &str = "All day";
@@ -73,7 +75,7 @@ fn detail_label(event: &CalendarEvent) -> String {
73
75
}
74
76
75
77
fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {
76
if event.all_day {
78
if is_effective_all_day(event, offset) {
77
79
return ALL_DAY_LABEL.to_owned();
78
80
}
79
81
format!(
@@ -90,6 +92,8 @@ fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {
90
92
}
91
93
92
94
fn agenda_day(event: &CalendarEvent, today: NaiveDate, offset: FixedOffset) -> NaiveDate {
95
// Flagged all-day (`date`) uses the UTC calendar date; midnight-span
96
// dateTime events use the local calendar day.
93
97
let start_day = if event.all_day {
94
98
event.start.date_naive()
95
99
} else {
@@ -110,7 +114,7 @@ fn agenda_row(event: &CalendarEvent, offset: FixedOffset) -> AgendaRow {
110
114
detail: detail_label(event),
111
115
response: event.response,
112
116
can_respond: event.response != ResponseType::Organizer && event.organizer_name.is_some(),
113
all_day: event.all_day,
117
all_day: is_effective_all_day(event, offset),
114
118
join_url: event.join_url.clone().filter(|_| event.online),
115
119
thread_id: event.thread_id.clone(),
116
120
start: event.start,
@@ -160,22 +164,30 @@ pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
160
164
minutes_from_now: i64,
161
165
length_minutes: i64,
162
166
organizer: &str,
163
response: ResponseType| CalendarEvent {
164
object_id: id.to_owned(),
165
subject: subject.to_owned(),
166
start: now + Duration::minutes(minutes_from_now),
167
end: now + Duration::minutes(minutes_from_now + length_minutes),
168
all_day: false,
169
cancelled: false,
170
online: true,
171
join_url: Some(demo_join_url(id)),
172
thread_id: None,
173
organizer_name: Some(organizer.to_owned()),
174
organizer_address: None,
175
ical_uid: None,
176
show_as: Default::default(),
177
dial_in: None,
178
response,
167
response: ResponseType| {
168
let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();
169
CalendarEvent {
170
object_id: id.to_owned(),
171
subject: subject.to_owned(),
172
start: now + Duration::minutes(minutes_from_now),
173
end: now + Duration::minutes(minutes_from_now + length_minutes),
174
all_day: false,
175
cancelled: false,
176
online: true,
177
join_url: Some(demo_join_url(id)),
178
thread_id: None,
179
organizer_name: Some(organizer.to_owned()),
180
organizer_address: None,
181
ical_uid: None,
182
show_as: Default::default(),
183
dial_in: None,
184
response,
185
source,
186
account_id,
187
calendar_id,
188
sources,
189
..Default::default()
190
}
179
191
};
180
192
vec![
181
193
event(
@@ -253,6 +265,7 @@ mod tests {
253
265
show_as: Default::default(),
254
266
dial_in: None,
255
267
response: ResponseType::Accepted,
268
..Default::default()
256
269
}
257
270
}
258
271
@@ -1,6 +1,8 @@1
use chatsvc::{CalendarEvent, ResponseType};1
use chatsvc::{CalendarEvent, ResponseType};2
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};2
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};3
3
4
use crate::week_grid::is_effective_all_day;5
4
const JOIN_LEAD_MINUTES: i64 = 5;6
const JOIN_LEAD_MINUTES: i64 = 5;5
const AGENDA_DAYS: i64 = 7;7
const AGENDA_DAYS: i64 = 7;6
const ALL_DAY_LABEL: &str = "All day";8
const ALL_DAY_LABEL: &str = "All day";@@ -73,7 +75,7 @@ fn detail_label(event: &CalendarEvent) -> String {73
}75
}74
76
75
fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {77
fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {76
if event.all_day {78
if is_effective_all_day(event, offset) {77
return ALL_DAY_LABEL.to_owned();79
return ALL_DAY_LABEL.to_owned();78
}80
}79
format!(81
format!(@@ -90,6 +92,8 @@ fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {90
}92
}91
93
92
fn agenda_day(event: &CalendarEvent, today: NaiveDate, offset: FixedOffset) -> NaiveDate {94
fn agenda_day(event: &CalendarEvent, today: NaiveDate, offset: FixedOffset) -> NaiveDate {95
// Flagged all-day (`date`) uses the UTC calendar date; midnight-span96
// dateTime events use the local calendar day.93
let start_day = if event.all_day {97
let start_day = if event.all_day {94
event.start.date_naive()98
event.start.date_naive()95
} else {99
} else {@@ -110,7 +114,7 @@ fn agenda_row(event: &CalendarEvent, offset: FixedOffset) -> AgendaRow {110
detail: detail_label(event),114
detail: detail_label(event),111
response: event.response,115
response: event.response,112
can_respond: event.response != ResponseType::Organizer && event.organizer_name.is_some(),116
can_respond: event.response != ResponseType::Organizer && event.organizer_name.is_some(),113
all_day: event.all_day,117
all_day: is_effective_all_day(event, offset),114
join_url: event.join_url.clone().filter(|_| event.online),118
join_url: event.join_url.clone().filter(|_| event.online),115
thread_id: event.thread_id.clone(),119
thread_id: event.thread_id.clone(),116
start: event.start,120
start: event.start,@@ -160,22 +164,30 @@ pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {160
minutes_from_now: i64,164
minutes_from_now: i64,161
length_minutes: i64,165
length_minutes: i64,162
organizer: &str,166
organizer: &str,163
response: ResponseType| CalendarEvent {167
response: ResponseType| {164
object_id: id.to_owned(),168
let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();165
subject: subject.to_owned(),169
CalendarEvent {166
start: now + Duration::minutes(minutes_from_now),170
object_id: id.to_owned(),167
end: now + Duration::minutes(minutes_from_now + length_minutes),171
subject: subject.to_owned(),168
all_day: false,172
start: now + Duration::minutes(minutes_from_now),169
cancelled: false,173
end: now + Duration::minutes(minutes_from_now + length_minutes),170
online: true,174
all_day: false,171
join_url: Some(demo_join_url(id)),175
cancelled: false,172
thread_id: None,176
online: true,173
organizer_name: Some(organizer.to_owned()),177
join_url: Some(demo_join_url(id)),174
organizer_address: None,178
thread_id: None,175
ical_uid: None,179
organizer_name: Some(organizer.to_owned()),176
show_as: Default::default(),180
organizer_address: None,177
dial_in: None,181
ical_uid: None,178
response,182
show_as: Default::default(),183
dial_in: None,184
response,185
source,186
account_id,187
calendar_id,188
sources,189
..Default::default()190
}179
};191
};180
vec![192
vec![181
event(193
event(@@ -253,6 +265,7 @@ mod tests {253
show_as: Default::default(),265
show_as: Default::default(),254
dial_in: None,266
dial_in: None,255
response: ResponseType::Accepted,267
response: ResponseType::Accepted,268
..Default::default()256
}269
}257
}270
}258
271
@@ -1,5 +1,7 @@
1
1
use chatsvc::{CalendarEvent, ResponseType, ShowAs};
2
use chrono::{DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, Utc, Weekday};
2
use chrono::{
3
DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,
4
};
3
5
4
6
pub const WORK_WEEK_DAYS: i64 = 5;
5
7
pub const MINUTES_PER_DAY: i64 = 24 * 60;
@@ -138,6 +140,25 @@ pub fn shown_in_calendar(event: &CalendarEvent) -> bool {
138
140
event.response != ResponseType::Declined
139
141
}
140
142
143
/// True all-day events, plus timed blocks that cover whole local days
144
/// (Google holidays/week markers as 00:00→00:00, or multi-day 00:00→23:59).
145
pub fn is_effective_all_day(event: &CalendarEvent, offset: FixedOffset) -> bool {
146
if event.all_day {
147
return true;
148
}
149
let start = event.start.with_timezone(&offset);
150
let end = event.end.with_timezone(&offset);
151
if start.time() != NaiveTime::MIN || end <= start {
152
return false;
153
}
154
if end.time() == NaiveTime::MIN {
155
return true;
156
}
157
// Multi-day blocks that run from midnight through end-of-day (e.g. 23:59).
158
end.date_naive() > start.date_naive()
159
&& end.time() >= NaiveTime::from_hms_opt(23, 59, 0).unwrap()
160
}
161
141
162
pub fn week_days(
142
163
events: &[CalendarEvent],
143
164
start: NaiveDate,
@@ -154,7 +175,7 @@ pub fn week_days(
154
175
if !shown_in_calendar(event) || event.end <= day_start || event.start >= day_end {
155
176
continue;
156
177
}
157
if event.all_day {
178
if is_effective_all_day(event, offset) {
158
179
all_day.push(index);
159
180
continue;
160
181
}
@@ -269,6 +290,7 @@ mod tests {
269
290
show_as: Default::default(),
270
291
dial_in: None,
271
292
response: ResponseType::Accepted,
293
..Default::default()
272
294
}
273
295
}
274
296
@@ -351,6 +373,32 @@ mod tests {
351
373
);
352
374
}
353
375
376
#[test]
377
fn midnight_to_midnight_timed_events_sit_in_the_all_day_row() {
378
// Google holidays / week markers often arrive as dateTime 00:00→00:00.
379
let holiday = event(0, 0, 24 * 60);
380
let meeting = event(9, 30, 60);
381
let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
382
assert!(is_effective_all_day(&holiday, utc()));
383
assert!(!is_effective_all_day(&meeting, utc()));
384
let days = week_days(&[holiday, meeting], monday, 1, utc());
385
assert_eq!(days[0].all_day, [0]);
386
assert_eq!(days[0].blocks.len(), 1);
387
assert_eq!(days[0].blocks[0].event_index, 1);
388
}
389
390
#[test]
391
fn multi_day_midnight_to_end_of_day_is_all_day() {
392
// e.g. KubeCon as 00:00 Mon → 23:59 Thu.
393
let conference = event(0, 0, 4 * 24 * 60 - 1);
394
assert!(is_effective_all_day(&conference, utc()));
395
let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
396
let days = week_days(&[conference], monday, 5, utc());
397
assert!(days.iter().all(|day| day.blocks.is_empty()));
398
assert_eq!(days[0].all_day, [0]);
399
assert_eq!(days[3].all_day, [0]);
400
}
401
354
402
#[test]
355
403
fn spans_start_and_step_like_teams() {
356
404
let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();
@@ -1,5 +1,7 @@1
use chatsvc::{CalendarEvent, ResponseType, ShowAs};1
use chatsvc::{CalendarEvent, ResponseType, ShowAs};2
use chrono::{DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, Utc, Weekday};2
use chrono::{3
DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,4
};3
5
4
pub const WORK_WEEK_DAYS: i64 = 5;6
pub const WORK_WEEK_DAYS: i64 = 5;5
pub const MINUTES_PER_DAY: i64 = 24 * 60;7
pub const MINUTES_PER_DAY: i64 = 24 * 60;@@ -138,6 +140,25 @@ pub fn shown_in_calendar(event: &CalendarEvent) -> bool {138
event.response != ResponseType::Declined140
event.response != ResponseType::Declined139
}141
}140
142
143
/// True all-day events, plus timed blocks that cover whole local days144
/// (Google holidays/week markers as 00:00→00:00, or multi-day 00:00→23:59).145
pub fn is_effective_all_day(event: &CalendarEvent, offset: FixedOffset) -> bool {146
if event.all_day {147
return true;148
}149
let start = event.start.with_timezone(&offset);150
let end = event.end.with_timezone(&offset);151
if start.time() != NaiveTime::MIN || end <= start {152
return false;153
}154
if end.time() == NaiveTime::MIN {155
return true;156
}157
// Multi-day blocks that run from midnight through end-of-day (e.g. 23:59).158
end.date_naive() > start.date_naive()159
&& end.time() >= NaiveTime::from_hms_opt(23, 59, 0).unwrap()160
}161
141
pub fn week_days(162
pub fn week_days(142
events: &[CalendarEvent],163
events: &[CalendarEvent],143
start: NaiveDate,164
start: NaiveDate,@@ -154,7 +175,7 @@ pub fn week_days(154
if !shown_in_calendar(event) || event.end <= day_start || event.start >= day_end {175
if !shown_in_calendar(event) || event.end <= day_start || event.start >= day_end {155
continue;176
continue;156
}177
}157
if event.all_day {178
if is_effective_all_day(event, offset) {158
all_day.push(index);179
all_day.push(index);159
continue;180
continue;160
}181
}@@ -269,6 +290,7 @@ mod tests {269
show_as: Default::default(),290
show_as: Default::default(),270
dial_in: None,291
dial_in: None,271
response: ResponseType::Accepted,292
response: ResponseType::Accepted,293
..Default::default()272
}294
}273
}295
}274
296
@@ -351,6 +373,32 @@ mod tests {351
);373
);352
}374
}353
375
376
#[test]377
fn midnight_to_midnight_timed_events_sit_in_the_all_day_row() {378
// Google holidays / week markers often arrive as dateTime 00:00→00:00.379
let holiday = event(0, 0, 24 * 60);380
let meeting = event(9, 30, 60);381
let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();382
assert!(is_effective_all_day(&holiday, utc()));383
assert!(!is_effective_all_day(&meeting, utc()));384
let days = week_days(&[holiday, meeting], monday, 1, utc());385
assert_eq!(days[0].all_day, [0]);386
assert_eq!(days[0].blocks.len(), 1);387
assert_eq!(days[0].blocks[0].event_index, 1);388
}389
390
#[test]391
fn multi_day_midnight_to_end_of_day_is_all_day() {392
// e.g. KubeCon as 00:00 Mon → 23:59 Thu.393
let conference = event(0, 0, 4 * 24 * 60 - 1);394
assert!(is_effective_all_day(&conference, utc()));395
let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();396
let days = week_days(&[conference], monday, 5, utc());397
assert!(days.iter().all(|day| day.blocks.is_empty()));398
assert_eq!(days[0].all_day, [0]);399
assert_eq!(days[3].all_day, [0]);400
}401
354
#[test]402
#[test]355
fn spans_start_and_step_like_teams() {403
fn spans_start_and_step_like_teams() {356
let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();404
let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();@@ -204,7 +204,11 @@ async fn supervise(
204
204
link,
205
205
live_retry,
206
206
));
207
tokio::spawn(calendar_loop(session.clone(), events.clone()));
207
tokio::spawn(calendar_loop(
208
session.clone(),
209
store.clone(),
210
events.clone(),
211
));
208
212
tokio::spawn(pins_loop(session, events.clone()));
209
213
tokio::spawn(presence_resubscribe_loop(engine.clone()));
210
214
refresh_loop(engine, events, nudges).await;
@@ -457,7 +461,7 @@ async fn handle_message_event(
457
461
}
458
462
}
459
463
460
async fn calendar_loop(session: Session, events: EventSender) {
464
async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender) {
461
465
let calendar = Calendar::new(&session);
462
466
let (nudge, mut nudges) = mpsc::unbounded_channel();
463
467
let _ = events.send(BackendEvent::CalendarNudge(nudge));
@@ -483,16 +487,33 @@ async fn calendar_loop(session: Session, events: EventSender) {
483
487
deferred_fetch = None;
484
488
last_fetch = Some(tokio::time::Instant::now());
485
489
let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
486
match calendar.calendar_view(start, end).await {
487
Ok(fetched) => {
488
if events.send(BackendEvent::Calendar(fetched)).is_err() {
489
return;
490
let mut accounts = store::load_calendar_accounts(&store);
491
let mut combined = Vec::new();
492
let mut outlook_failed = false;
493
if accounts.outlook_selected {
494
match calendar.calendar_view(start, end).await {
495
Ok(fetched) => combined.extend(fetched),
496
Err(error) => {
497
outlook_failed = true;
498
crate::diagnostics::record(format!(
499
"calls: outlook calendar not loaded: {}",
500
shorten(&error.to_string())
501
));
490
502
}
491
503
}
492
Err(error) => crate::diagnostics::record(format!(
493
"calls: calendar not loaded: {}",
494
shorten(&error.to_string())
495
)),
504
}
505
if let Ok(google_events) =
506
crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await
507
{
508
let _ = store::save_calendar_accounts(&store, &accounts);
509
combined.extend(google_events);
510
}
511
if combined.is_empty() && outlook_failed && !accounts.has_google() {
512
continue;
513
}
514
let merged = chatsvc::merge_calendar_events(combined);
515
if events.send(BackendEvent::Calendar(merged)).is_err() {
516
return;
496
517
}
497
518
}
498
519
}
@@ -204,7 +204,11 @@ async fn supervise(204
link,204
link,205
live_retry,205
live_retry,206
));206
));207
tokio::spawn(calendar_loop(session.clone(), events.clone()));207
tokio::spawn(calendar_loop(208
session.clone(),209
store.clone(),210
events.clone(),211
));208
tokio::spawn(pins_loop(session, events.clone()));212
tokio::spawn(pins_loop(session, events.clone()));209
tokio::spawn(presence_resubscribe_loop(engine.clone()));213
tokio::spawn(presence_resubscribe_loop(engine.clone()));210
refresh_loop(engine, events, nudges).await;214
refresh_loop(engine, events, nudges).await;@@ -457,7 +461,7 @@ async fn handle_message_event(457
}461
}458
}462
}459
463
460
async fn calendar_loop(session: Session, events: EventSender) {464
async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender) {461
let calendar = Calendar::new(&session);465
let calendar = Calendar::new(&session);462
let (nudge, mut nudges) = mpsc::unbounded_channel();466
let (nudge, mut nudges) = mpsc::unbounded_channel();463
let _ = events.send(BackendEvent::CalendarNudge(nudge));467
let _ = events.send(BackendEvent::CalendarNudge(nudge));@@ -483,16 +487,33 @@ async fn calendar_loop(session: Session, events: EventSender) {483
deferred_fetch = None;487
deferred_fetch = None;484
last_fetch = Some(tokio::time::Instant::now());488
last_fetch = Some(tokio::time::Instant::now());485
let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());489
let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());486
match calendar.calendar_view(start, end).await {490
let mut accounts = store::load_calendar_accounts(&store);487
Ok(fetched) => {491
let mut combined = Vec::new();488
if events.send(BackendEvent::Calendar(fetched)).is_err() {492
let mut outlook_failed = false;489
return;493
if accounts.outlook_selected {494
match calendar.calendar_view(start, end).await {495
Ok(fetched) => combined.extend(fetched),496
Err(error) => {497
outlook_failed = true;498
crate::diagnostics::record(format!(499
"calls: outlook calendar not loaded: {}",500
shorten(&error.to_string())501
));490
}502
}491
}503
}492
Err(error) => crate::diagnostics::record(format!(504
}493
"calls: calendar not loaded: {}",505
if let Ok(google_events) =494
shorten(&error.to_string())506
crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await495
)),507
{508
let _ = store::save_calendar_accounts(&store, &accounts);509
combined.extend(google_events);510
}511
if combined.is_empty() && outlook_failed && !accounts.has_google() {512
continue;513
}514
let merged = chatsvc::merge_calendar_events(combined);515
if events.send(BackendEvent::Calendar(merged)).is_err() {516
return;496
}517
}497
}518
}498
}519
}@@ -0,0 +1,207 @@
1
use chrono::Utc;
2
use gpui_kit::Context;
3
use store::{
4
CalendarAccounts, CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet,
5
load_calendar_accounts, save_calendar_accounts,
6
};
7
use uuid::Uuid;
8
9
use chatsvc::{
10
GoogleCalendar, GoogleOAuth, allocate_redirect_uri, client_id_from_env, exchange_code,
11
parse_calendar_list, wait_for_code,
12
};
13
14
use crate::app_state::AppState;
15
use crate::runtime;
16
17
impl AppState {
18
pub fn calendar_accounts(&self) -> CalendarAccounts {
19
load_calendar_accounts(&self.store)
20
}
21
22
pub fn disconnect_google_account(&mut self, account_id: &str, cx: &mut Context<Self>) {
23
let mut accounts = load_calendar_accounts(&self.store);
24
accounts.disconnect_google(account_id);
25
let _ = save_calendar_accounts(&self.store, &accounts);
26
self.refresh_calendar(cx);
27
self.load_calendar_week(cx);
28
cx.notify();
29
}
30
31
pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {
32
let mut accounts = load_calendar_accounts(&self.store);
33
accounts.home = home;
34
let _ = save_calendar_accounts(&self.store, &accounts);
35
cx.notify();
36
}
37
38
pub fn toggle_write_target(&mut self, target: CalendarRef, cx: &mut Context<Self>) {
39
let mut accounts = load_calendar_accounts(&self.store);
40
if let Some(index) = accounts
41
.write_targets
42
.iter()
43
.position(|existing| existing.key() == target.key())
44
{
45
accounts.write_targets.remove(index);
46
} else if accounts.home.key() != target.key() {
47
accounts.write_targets.push(target);
48
}
49
let _ = save_calendar_accounts(&self.store, &accounts);
50
cx.notify();
51
}
52
53
pub fn toggle_google_calendar_selected(
54
&mut self,
55
account_id: &str,
56
calendar_id: &str,
57
cx: &mut Context<Self>,
58
) {
59
let mut accounts = load_calendar_accounts(&self.store);
60
if let Some(calendar) = accounts.google_account_mut(account_id).and_then(|account| {
61
account
62
.calendars
63
.iter_mut()
64
.find(|calendar| calendar.id == calendar_id)
65
}) {
66
calendar.selected = !calendar.selected;
67
}
68
let _ = save_calendar_accounts(&self.store, &accounts);
69
self.refresh_calendar(cx);
70
self.load_calendar_week(cx);
71
cx.notify();
72
}
73
74
pub fn toggle_outlook_calendar_selected(&mut self, cx: &mut Context<Self>) {
75
let mut accounts = load_calendar_accounts(&self.store);
76
accounts.outlook_selected = !accounts.outlook_selected;
77
let _ = save_calendar_accounts(&self.store, &accounts);
78
self.refresh_calendar(cx);
79
self.load_calendar_week(cx);
80
cx.notify();
81
}
82
83
pub fn connect_google_calendar(&mut self, cx: &mut Context<Self>) {
84
let Some(oauth) = client_id_from_env() else {
85
self.raise_notice(
86
"Set TEAMS_GOOGLE_CLIENT_ID (and optional TEAMS_GOOGLE_CLIENT_SECRET) to connect Google Calendar."
87
.to_owned(),
88
None,
89
cx,
90
);
91
return;
92
};
93
let store = self.store.clone();
94
cx.spawn(async move |this, cx| {
95
let prepared = runtime::spawn({
96
let oauth = oauth.clone();
97
async move {
98
let (redirect_uri, listener) = allocate_redirect_uri()
99
.await
100
.map_err(|error| error.to_string())?;
101
let pending = oauth.begin(&redirect_uri);
102
let authorize_url = pending.authorize_url.clone();
103
Ok::<_, String>((authorize_url, pending, listener, oauth))
104
}
105
});
106
let (authorize_url, pending, listener, oauth) = match prepared.await {
107
Ok(Ok(value)) => value,
108
Ok(Err(error)) => {
109
this.update(cx, |state, cx| state.raise_notice(error, None, cx))
110
.ok();
111
return;
112
}
113
Err(_) => {
114
this.update(cx, |state, cx| {
115
state.raise_notice("Could not start Google sign-in.".to_owned(), None, cx)
116
})
117
.ok();
118
return;
119
}
120
};
121
this.update(cx, |_, cx| cx.open_url(&authorize_url)).ok();
122
let finished = runtime::spawn(async move {
123
finish_google_connect(oauth, pending, listener, store).await
124
});
125
match finished.await {
126
Ok(Ok(email)) => {
127
this.update(cx, |state, cx| {
128
state.raise_notice(
129
format!("Google Calendar connected ({email})."),
130
None,
131
cx,
132
);
133
state.refresh_calendar(cx);
134
cx.notify();
135
})
136
.ok();
137
}
138
Ok(Err(error)) => {
139
this.update(cx, |state, cx| state.raise_notice(error, None, cx))
140
.ok();
141
}
142
Err(_) => {
143
this.update(cx, |state, cx| {
144
state.raise_notice("Google sign-in was cancelled.".to_owned(), None, cx)
145
})
146
.ok();
147
}
148
}
149
})
150
.detach();
151
}
152
}
153
154
async fn finish_google_connect(
155
oauth: GoogleOAuth,
156
pending: chatsvc::AuthPending,
157
listener: tokio::net::TcpListener,
158
store: std::sync::Arc<store::Store>,
159
) -> Result<String, String> {
160
let code = wait_for_code(&pending, listener)
161
.await
162
.map_err(|error| error.to_string())?;
163
let bundle = exchange_code(&oauth, &pending, &code)
164
.await
165
.map_err(|error| error.to_string())?;
166
let client = GoogleCalendar::new(bundle.access_token.clone());
167
let list = client
168
.list_calendars()
169
.await
170
.map_err(|error| error.to_string())?;
171
let mut calendars = parse_calendar_list(&list)
172
.into_iter()
173
.map(|(id, summary, primary)| GoogleCalendarInfo {
174
id,
175
summary,
176
selected: true,
177
primary,
178
})
179
.collect::<Vec<_>>();
180
if calendars.is_empty() {
181
calendars.push(GoogleCalendarInfo {
182
id: "primary".into(),
183
summary: "Primary".into(),
184
selected: true,
185
primary: true,
186
});
187
}
188
let email = calendars
189
.iter()
190
.find(|calendar| calendar.primary)
191
.map(|calendar| calendar.summary.clone())
192
.unwrap_or_else(|| "Google".into());
193
let account = GoogleAccount {
194
id: Uuid::new_v4().to_string(),
195
email: email.clone(),
196
calendars,
197
tokens: GoogleTokenSet {
198
access_token: bundle.access_token,
199
refresh_token: bundle.refresh_token,
200
expires_at: Utc::now().timestamp() + bundle.expires_in.max(60),
201
},
202
};
203
let mut accounts = load_calendar_accounts(&store);
204
accounts.google_accounts.push(account);
205
save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
206
Ok(email)
207
}
@@ -0,0 +1,207 @@1
use chrono::Utc;2
use gpui_kit::Context;3
use store::{4
CalendarAccounts, CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet,5
load_calendar_accounts, save_calendar_accounts,6
};7
use uuid::Uuid;8
9
use chatsvc::{10
GoogleCalendar, GoogleOAuth, allocate_redirect_uri, client_id_from_env, exchange_code,11
parse_calendar_list, wait_for_code,12
};13
14
use crate::app_state::AppState;15
use crate::runtime;16
17
impl AppState {18
pub fn calendar_accounts(&self) -> CalendarAccounts {19
load_calendar_accounts(&self.store)20
}21
22
pub fn disconnect_google_account(&mut self, account_id: &str, cx: &mut Context<Self>) {23
let mut accounts = load_calendar_accounts(&self.store);24
accounts.disconnect_google(account_id);25
let _ = save_calendar_accounts(&self.store, &accounts);26
self.refresh_calendar(cx);27
self.load_calendar_week(cx);28
cx.notify();29
}30
31
pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {32
let mut accounts = load_calendar_accounts(&self.store);33
accounts.home = home;34
let _ = save_calendar_accounts(&self.store, &accounts);35
cx.notify();36
}37
38
pub fn toggle_write_target(&mut self, target: CalendarRef, cx: &mut Context<Self>) {39
let mut accounts = load_calendar_accounts(&self.store);40
if let Some(index) = accounts41
.write_targets42
.iter()43
.position(|existing| existing.key() == target.key())44
{45
accounts.write_targets.remove(index);46
} else if accounts.home.key() != target.key() {47
accounts.write_targets.push(target);48
}49
let _ = save_calendar_accounts(&self.store, &accounts);50
cx.notify();51
}52
53
pub fn toggle_google_calendar_selected(54
&mut self,55
account_id: &str,56
calendar_id: &str,57
cx: &mut Context<Self>,58
) {59
let mut accounts = load_calendar_accounts(&self.store);60
if let Some(calendar) = accounts.google_account_mut(account_id).and_then(|account| {61
account62
.calendars63
.iter_mut()64
.find(|calendar| calendar.id == calendar_id)65
}) {66
calendar.selected = !calendar.selected;67
}68
let _ = save_calendar_accounts(&self.store, &accounts);69
self.refresh_calendar(cx);70
self.load_calendar_week(cx);71
cx.notify();72
}73
74
pub fn toggle_outlook_calendar_selected(&mut self, cx: &mut Context<Self>) {75
let mut accounts = load_calendar_accounts(&self.store);76
accounts.outlook_selected = !accounts.outlook_selected;77
let _ = save_calendar_accounts(&self.store, &accounts);78
self.refresh_calendar(cx);79
self.load_calendar_week(cx);80
cx.notify();81
}82
83
pub fn connect_google_calendar(&mut self, cx: &mut Context<Self>) {84
let Some(oauth) = client_id_from_env() else {85
self.raise_notice(86
"Set TEAMS_GOOGLE_CLIENT_ID (and optional TEAMS_GOOGLE_CLIENT_SECRET) to connect Google Calendar."87
.to_owned(),88
None,89
cx,90
);91
return;92
};93
let store = self.store.clone();94
cx.spawn(async move |this, cx| {95
let prepared = runtime::spawn({96
let oauth = oauth.clone();97
async move {98
let (redirect_uri, listener) = allocate_redirect_uri()99
.await100
.map_err(|error| error.to_string())?;101
let pending = oauth.begin(&redirect_uri);102
let authorize_url = pending.authorize_url.clone();103
Ok::<_, String>((authorize_url, pending, listener, oauth))104
}105
});106
let (authorize_url, pending, listener, oauth) = match prepared.await {107
Ok(Ok(value)) => value,108
Ok(Err(error)) => {109
this.update(cx, |state, cx| state.raise_notice(error, None, cx))110
.ok();111
return;112
}113
Err(_) => {114
this.update(cx, |state, cx| {115
state.raise_notice("Could not start Google sign-in.".to_owned(), None, cx)116
})117
.ok();118
return;119
}120
};121
this.update(cx, |_, cx| cx.open_url(&authorize_url)).ok();122
let finished = runtime::spawn(async move {123
finish_google_connect(oauth, pending, listener, store).await124
});125
match finished.await {126
Ok(Ok(email)) => {127
this.update(cx, |state, cx| {128
state.raise_notice(129
format!("Google Calendar connected ({email})."),130
None,131
cx,132
);133
state.refresh_calendar(cx);134
cx.notify();135
})136
.ok();137
}138
Ok(Err(error)) => {139
this.update(cx, |state, cx| state.raise_notice(error, None, cx))140
.ok();141
}142
Err(_) => {143
this.update(cx, |state, cx| {144
state.raise_notice("Google sign-in was cancelled.".to_owned(), None, cx)145
})146
.ok();147
}148
}149
})150
.detach();151
}152
}153
154
async fn finish_google_connect(155
oauth: GoogleOAuth,156
pending: chatsvc::AuthPending,157
listener: tokio::net::TcpListener,158
store: std::sync::Arc<store::Store>,159
) -> Result<String, String> {160
let code = wait_for_code(&pending, listener)161
.await162
.map_err(|error| error.to_string())?;163
let bundle = exchange_code(&oauth, &pending, &code)164
.await165
.map_err(|error| error.to_string())?;166
let client = GoogleCalendar::new(bundle.access_token.clone());167
let list = client168
.list_calendars()169
.await170
.map_err(|error| error.to_string())?;171
let mut calendars = parse_calendar_list(&list)172
.into_iter()173
.map(|(id, summary, primary)| GoogleCalendarInfo {174
id,175
summary,176
selected: true,177
primary,178
})179
.collect::<Vec<_>>();180
if calendars.is_empty() {181
calendars.push(GoogleCalendarInfo {182
id: "primary".into(),183
summary: "Primary".into(),184
selected: true,185
primary: true,186
});187
}188
let email = calendars189
.iter()190
.find(|calendar| calendar.primary)191
.map(|calendar| calendar.summary.clone())192
.unwrap_or_else(|| "Google".into());193
let account = GoogleAccount {194
id: Uuid::new_v4().to_string(),195
email: email.clone(),196
calendars,197
tokens: GoogleTokenSet {198
access_token: bundle.access_token,199
refresh_token: bundle.refresh_token,200
expires_at: Utc::now().timestamp() + bundle.expires_in.max(60),201
},202
};203
let mut accounts = load_calendar_accounts(&store);204
accounts.google_accounts.push(account);205
save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;206
Ok(email)207
}@@ -17,6 +17,9 @@ pub(crate) fn demo_anchor() -> DateTime<Utc> {
17
17
18
18
impl AppState {
19
19
pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {
20
// Agenda / reminders poll — must not replace calendar_week.events.
21
// That window is only ~today+7d; overwriting wiped earlier days in the
22
// visible week/month and made entries "vanish" after delete or poll.
20
23
self.calendar_events = events;
21
24
self.calls_list.invalidate();
22
25
cx.emit(AppEvent::CallHistory);
@@ -29,11 +32,18 @@ impl AppState {
29
32
events.extend(self.demo_meetings.iter().cloned());
30
33
events.sort_by_key(|event| (event.start, event.end));
31
34
self.apply_calendar(events, cx);
35
if self.calendar_week.start.is_some() {
36
self.load_calendar_week(cx);
37
}
32
38
return;
33
39
}
34
40
if let Some(nudge) = &self.calendar_nudge {
35
41
let _ = nudge.send(());
36
42
}
43
// Visible grid SoT is load_calendar_week (full span + Google merge).
44
if self.calendar_week.start.is_some() {
45
self.load_calendar_week(cx);
46
}
37
47
}
38
48
39
49
pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {
@@ -17,6 +17,9 @@ pub(crate) fn demo_anchor() -> DateTime<Utc> {17
17
18
impl AppState {18
impl AppState {19
pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {19
pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {20
// Agenda / reminders poll — must not replace calendar_week.events.21
// That window is only ~today+7d; overwriting wiped earlier days in the22
// visible week/month and made entries "vanish" after delete or poll.20
self.calendar_events = events;23
self.calendar_events = events;21
self.calls_list.invalidate();24
self.calls_list.invalidate();22
cx.emit(AppEvent::CallHistory);25
cx.emit(AppEvent::CallHistory);@@ -29,11 +32,18 @@ impl AppState {29
events.extend(self.demo_meetings.iter().cloned());32
events.extend(self.demo_meetings.iter().cloned());30
events.sort_by_key(|event| (event.start, event.end));33
events.sort_by_key(|event| (event.start, event.end));31
self.apply_calendar(events, cx);34
self.apply_calendar(events, cx);35
if self.calendar_week.start.is_some() {36
self.load_calendar_week(cx);37
}32
return;38
return;33
}39
}34
if let Some(nudge) = &self.calendar_nudge {40
if let Some(nudge) = &self.calendar_nudge {35
let _ = nudge.send(());41
let _ = nudge.send(());36
}42
}43
// Visible grid SoT is load_calendar_week (full span + Google merge).44
if self.calendar_week.start.is_some() {45
self.load_calendar_week(cx);46
}37
}47
}38
48
39
pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {49
pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {@@ -163,16 +163,16 @@ impl CallLauncher {
163
163
.map_err(|error| error.to_string())
164
164
}
165
165
166
pub async fn create_meeting(
166
pub async fn resolve_new_event(
167
167
&self,
168
168
draft: MeetingDraft,
169
) -> Result<chatsvc::CreatedEvent, String> {
169
) -> Result<chatsvc::NewEvent, String> {
170
170
let session = self
171
171
.ready_engine()
172
172
.await
173
173
.ok_or_else(|| NOT_READY.to_owned())?
174
174
.session();
175
let graph = graph::Graph::new(session.clone());
175
let graph = graph::Graph::new(session);
176
176
let mut attendees = Vec::with_capacity(draft.people.len());
177
177
for invitee in &draft.people {
178
178
let looked_up = match invitee.mail {
@@ -181,7 +181,7 @@ impl CallLauncher {
181
181
};
182
182
attendees.push(attendee_for(invitee, looked_up)?);
183
183
}
184
let event = chatsvc::NewEvent {
184
Ok(chatsvc::NewEvent {
185
185
subject: draft.subject,
186
186
start: draft.start,
187
187
end: draft.end,
@@ -191,13 +191,41 @@ impl CallLauncher {
191
191
attendees,
192
192
repeat: draft.repeat,
193
193
details: draft.details,
194
};
194
})
195
}
196
197
pub async fn create_meeting(
198
&self,
199
draft: MeetingDraft,
200
) -> Result<chatsvc::CreatedEvent, String> {
201
let session = self
202
.ready_engine()
203
.await
204
.ok_or_else(|| NOT_READY.to_owned())?
205
.session();
206
let event = self.resolve_new_event(draft).await?;
195
207
chatsvc::Calendar::new(&session)
196
208
.create_event(&event)
197
209
.await
198
210
.map_err(|error| error.to_string())
199
211
}
200
212
213
pub async fn create_meeting_with_join(
214
&self,
215
event: chatsvc::NewEvent,
216
join_url: &str,
217
) -> Result<chatsvc::CreatedEvent, String> {
218
let session = self
219
.ready_engine()
220
.await
221
.ok_or_else(|| NOT_READY.to_owned())?
222
.session();
223
chatsvc::Calendar::new(&session)
224
.create_event_with_join(&event, join_url)
225
.await
226
.map_err(|error| error.to_string())
227
}
228
201
229
pub async fn time_zone_name(&self, mail: &str) -> Option<String> {
202
230
let session = self.engine()?.session();
203
231
graph::Graph::new(session)
@@ -225,6 +253,22 @@ impl CallLauncher {
225
253
.map_err(|error| error.to_string())
226
254
}
227
255
256
pub async fn delete_calendar_event(
257
&self,
258
event_id: &str,
259
ical_uid: Option<&str>,
260
) -> Result<(), String> {
261
let session = self
262
.ready_engine()
263
.await
264
.ok_or_else(|| NOT_READY.to_owned())?
265
.session();
266
chatsvc::Calendar::new(&session)
267
.delete_event(event_id, ical_uid)
268
.await
269
.map_err(|error| error.to_string())
270
}
271
228
272
pub async fn calendar_view(
229
273
&self,
230
274
start: chrono::DateTime<chrono::Utc>,
@@ -163,16 +163,16 @@ impl CallLauncher {163
.map_err(|error| error.to_string())163
.map_err(|error| error.to_string())164
}164
}165
165
166
pub async fn create_meeting(166
pub async fn resolve_new_event(167
&self,167
&self,168
draft: MeetingDraft,168
draft: MeetingDraft,169
) -> Result<chatsvc::CreatedEvent, String> {169
) -> Result<chatsvc::NewEvent, String> {170
let session = self170
let session = self171
.ready_engine()171
.ready_engine()172
.await172
.await173
.ok_or_else(|| NOT_READY.to_owned())?173
.ok_or_else(|| NOT_READY.to_owned())?174
.session();174
.session();175
let graph = graph::Graph::new(session.clone());175
let graph = graph::Graph::new(session);176
let mut attendees = Vec::with_capacity(draft.people.len());176
let mut attendees = Vec::with_capacity(draft.people.len());177
for invitee in &draft.people {177
for invitee in &draft.people {178
let looked_up = match invitee.mail {178
let looked_up = match invitee.mail {@@ -181,7 +181,7 @@ impl CallLauncher {181
};181
};182
attendees.push(attendee_for(invitee, looked_up)?);182
attendees.push(attendee_for(invitee, looked_up)?);183
}183
}184
let event = chatsvc::NewEvent {184
Ok(chatsvc::NewEvent {185
subject: draft.subject,185
subject: draft.subject,186
start: draft.start,186
start: draft.start,187
end: draft.end,187
end: draft.end,@@ -191,13 +191,41 @@ impl CallLauncher {191
attendees,191
attendees,192
repeat: draft.repeat,192
repeat: draft.repeat,193
details: draft.details,193
details: draft.details,194
};194
})195
}196
197
pub async fn create_meeting(198
&self,199
draft: MeetingDraft,200
) -> Result<chatsvc::CreatedEvent, String> {201
let session = self202
.ready_engine()203
.await204
.ok_or_else(|| NOT_READY.to_owned())?205
.session();206
let event = self.resolve_new_event(draft).await?;195
chatsvc::Calendar::new(&session)207
chatsvc::Calendar::new(&session)196
.create_event(&event)208
.create_event(&event)197
.await209
.await198
.map_err(|error| error.to_string())210
.map_err(|error| error.to_string())199
}211
}200
212
213
pub async fn create_meeting_with_join(214
&self,215
event: chatsvc::NewEvent,216
join_url: &str,217
) -> Result<chatsvc::CreatedEvent, String> {218
let session = self219
.ready_engine()220
.await221
.ok_or_else(|| NOT_READY.to_owned())?222
.session();223
chatsvc::Calendar::new(&session)224
.create_event_with_join(&event, join_url)225
.await226
.map_err(|error| error.to_string())227
}228
201
pub async fn time_zone_name(&self, mail: &str) -> Option<String> {229
pub async fn time_zone_name(&self, mail: &str) -> Option<String> {202
let session = self.engine()?.session();230
let session = self.engine()?.session();203
graph::Graph::new(session)231
graph::Graph::new(session)@@ -225,6 +253,22 @@ impl CallLauncher {225
.map_err(|error| error.to_string())253
.map_err(|error| error.to_string())226
}254
}227
255
256
pub async fn delete_calendar_event(257
&self,258
event_id: &str,259
ical_uid: Option<&str>,260
) -> Result<(), String> {261
let session = self262
.ready_engine()263
.await264
.ok_or_else(|| NOT_READY.to_owned())?265
.session();266
chatsvc::Calendar::new(&session)267
.delete_event(event_id, ical_uid)268
.await269
.map_err(|error| error.to_string())270
}271
228
pub async fn calendar_view(272
pub async fn calendar_view(229
&self,273
&self,230
start: chrono::DateTime<chrono::Utc>,274
start: chrono::DateTime<chrono::Utc>,@@ -0,0 +1,164 @@
1
use std::sync::Arc;
2
3
use chatsvc::{CreatedEvent, GoogleEventDraft, NewEvent};
4
use store::{CalendarAccounts, CalendarProvider, CalendarRef, Store};
5
6
use super::launcher::CallLauncher;
7
use super::schedule::MeetingDraft;
8
9
/// Whether create must mint a Teams join URL before per-target inserts.
10
pub fn needs_join_first(accounts: &CalendarAccounts) -> bool {
11
let targets = accounts.resolved_write_targets();
12
targets.len() > 1
13
|| targets
14
.iter()
15
.any(|target| target.provider == CalendarProvider::Google)
16
}
17
18
/// Write targets used for New meeting (home + extras, de-duplicated).
19
pub fn create_targets(accounts: &CalendarAccounts) -> Vec<CalendarRef> {
20
accounts.resolved_write_targets()
21
}
22
23
/// Format a partial-failure notice when the join link exists but a target failed.
24
pub fn partial_create_notice(join_url: &str, failed: &[String]) -> String {
25
format!(
26
"Meeting link ready, but calendar write failed for {}: {join_url}",
27
failed.join(", ")
28
)
29
}
30
31
pub async fn create_across_targets(
32
launcher: Arc<CallLauncher>,
33
draft: MeetingDraft,
34
mut accounts: CalendarAccounts,
35
store: Arc<Store>,
36
) -> Result<CreatedEvent, String> {
37
if !needs_join_first(&accounts) {
38
return launcher.create_meeting(draft).await;
39
}
40
let event = launcher.resolve_new_event(draft).await?;
41
let join_url = launcher.create_meet_now(&event.subject).await?;
42
let targets = create_targets(&accounts);
43
let mut failed = Vec::new();
44
let mut first_id = String::new();
45
for target in targets {
46
match write_target(launcher.as_ref(), &mut accounts, &target, &event, &join_url).await {
47
Ok(id) => {
48
if first_id.is_empty() {
49
first_id = id;
50
}
51
}
52
Err(error) => failed.push(format!("{} ({error})", target.key())),
53
}
54
}
55
let _ = store::save_calendar_accounts(&store, &accounts);
56
if !failed.is_empty() {
57
crate::diagnostics::record(partial_create_notice(&join_url, &failed));
58
if first_id.is_empty() {
59
return Err(partial_create_notice(&join_url, &failed));
60
}
61
}
62
Ok(CreatedEvent {
63
id: if first_id.is_empty() {
64
join_url.clone()
65
} else {
66
first_id
67
},
68
join_url: Some(join_url),
69
})
70
}
71
72
async fn write_target(
73
launcher: &CallLauncher,
74
accounts: &mut CalendarAccounts,
75
target: &CalendarRef,
76
event: &NewEvent,
77
join_url: &str,
78
) -> Result<String, String> {
79
match target.provider {
80
CalendarProvider::Outlook => launcher
81
.create_meeting_with_join(event.clone(), join_url)
82
.await
83
.map(|created| created.id),
84
CalendarProvider::Google => {
85
let calendar_id = if target.calendar_id.is_empty() {
86
"primary"
87
} else {
88
target.calendar_id.as_str()
89
};
90
let mut draft = GoogleEventDraft::from(event);
91
draft.join_url = Some(join_url.to_owned());
92
crate::google_calendar_sync::insert_google_event(
93
accounts,
94
&target.account_id,
95
calendar_id,
96
&draft,
97
)
98
.await?;
99
Ok(format!("google:{}:{}", target.account_id, calendar_id))
100
}
101
}
102
}
103
104
#[cfg(test)]
105
mod tests {
106
use store::{CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet};
107
108
use super::*;
109
110
fn google_home() -> CalendarAccounts {
111
CalendarAccounts {
112
home: CalendarRef::google("g1", "primary"),
113
write_targets: Vec::new(),
114
outlook_selected: true,
115
google_accounts: vec![GoogleAccount {
116
id: "g1".into(),
117
email: "joe@example.com".into(),
118
calendars: vec![GoogleCalendarInfo {
119
id: "primary".into(),
120
summary: "Joe".into(),
121
selected: true,
122
primary: true,
123
}],
124
tokens: GoogleTokenSet::default(),
125
}],
126
}
127
}
128
129
#[test]
130
fn outlook_only_home_keeps_one_step() {
131
let accounts = CalendarAccounts::default();
132
assert!(!needs_join_first(&accounts));
133
assert_eq!(create_targets(&accounts).len(), 1);
134
assert_eq!(
135
create_targets(&accounts)[0].provider,
136
CalendarProvider::Outlook
137
);
138
}
139
140
#[test]
141
fn google_home_needs_join_first() {
142
assert!(needs_join_first(&google_home()));
143
}
144
145
#[test]
146
fn outlook_home_with_google_extra_needs_join_first() {
147
let mut accounts = CalendarAccounts::default();
148
accounts
149
.write_targets
150
.push(CalendarRef::google("g1", "primary"));
151
assert!(needs_join_first(&accounts));
152
assert_eq!(create_targets(&accounts).len(), 2);
153
}
154
155
#[test]
156
fn partial_notice_keeps_join_url() {
157
let notice = partial_create_notice(
158
"https://teams.microsoft.com/l/meetup-join/x",
159
&["Google:primary".into()],
160
);
161
assert!(notice.contains("teams.microsoft.com"));
162
assert!(notice.contains("Google:primary"));
163
}
164
}
@@ -0,0 +1,164 @@1
use std::sync::Arc;2
3
use chatsvc::{CreatedEvent, GoogleEventDraft, NewEvent};4
use store::{CalendarAccounts, CalendarProvider, CalendarRef, Store};5
6
use super::launcher::CallLauncher;7
use super::schedule::MeetingDraft;8
9
/// Whether create must mint a Teams join URL before per-target inserts.10
pub fn needs_join_first(accounts: &CalendarAccounts) -> bool {11
let targets = accounts.resolved_write_targets();12
targets.len() > 113
|| targets14
.iter()15
.any(|target| target.provider == CalendarProvider::Google)16
}17
18
/// Write targets used for New meeting (home + extras, de-duplicated).19
pub fn create_targets(accounts: &CalendarAccounts) -> Vec<CalendarRef> {20
accounts.resolved_write_targets()21
}22
23
/// Format a partial-failure notice when the join link exists but a target failed.24
pub fn partial_create_notice(join_url: &str, failed: &[String]) -> String {25
format!(26
"Meeting link ready, but calendar write failed for {}: {join_url}",27
failed.join(", ")28
)29
}30
31
pub async fn create_across_targets(32
launcher: Arc<CallLauncher>,33
draft: MeetingDraft,34
mut accounts: CalendarAccounts,35
store: Arc<Store>,36
) -> Result<CreatedEvent, String> {37
if !needs_join_first(&accounts) {38
return launcher.create_meeting(draft).await;39
}40
let event = launcher.resolve_new_event(draft).await?;41
let join_url = launcher.create_meet_now(&event.subject).await?;42
let targets = create_targets(&accounts);43
let mut failed = Vec::new();44
let mut first_id = String::new();45
for target in targets {46
match write_target(launcher.as_ref(), &mut accounts, &target, &event, &join_url).await {47
Ok(id) => {48
if first_id.is_empty() {49
first_id = id;50
}51
}52
Err(error) => failed.push(format!("{} ({error})", target.key())),53
}54
}55
let _ = store::save_calendar_accounts(&store, &accounts);56
if !failed.is_empty() {57
crate::diagnostics::record(partial_create_notice(&join_url, &failed));58
if first_id.is_empty() {59
return Err(partial_create_notice(&join_url, &failed));60
}61
}62
Ok(CreatedEvent {63
id: if first_id.is_empty() {64
join_url.clone()65
} else {66
first_id67
},68
join_url: Some(join_url),69
})70
}71
72
async fn write_target(73
launcher: &CallLauncher,74
accounts: &mut CalendarAccounts,75
target: &CalendarRef,76
event: &NewEvent,77
join_url: &str,78
) -> Result<String, String> {79
match target.provider {80
CalendarProvider::Outlook => launcher81
.create_meeting_with_join(event.clone(), join_url)82
.await83
.map(|created| created.id),84
CalendarProvider::Google => {85
let calendar_id = if target.calendar_id.is_empty() {86
"primary"87
} else {88
target.calendar_id.as_str()89
};90
let mut draft = GoogleEventDraft::from(event);91
draft.join_url = Some(join_url.to_owned());92
crate::google_calendar_sync::insert_google_event(93
accounts,94
&target.account_id,95
calendar_id,96
&draft,97
)98
.await?;99
Ok(format!("google:{}:{}", target.account_id, calendar_id))100
}101
}102
}103
104
#[cfg(test)]105
mod tests {106
use store::{CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet};107
108
use super::*;109
110
fn google_home() -> CalendarAccounts {111
CalendarAccounts {112
home: CalendarRef::google("g1", "primary"),113
write_targets: Vec::new(),114
outlook_selected: true,115
google_accounts: vec![GoogleAccount {116
id: "g1".into(),117
email: "joe@example.com".into(),118
calendars: vec![GoogleCalendarInfo {119
id: "primary".into(),120
summary: "Joe".into(),121
selected: true,122
primary: true,123
}],124
tokens: GoogleTokenSet::default(),125
}],126
}127
}128
129
#[test]130
fn outlook_only_home_keeps_one_step() {131
let accounts = CalendarAccounts::default();132
assert!(!needs_join_first(&accounts));133
assert_eq!(create_targets(&accounts).len(), 1);134
assert_eq!(135
create_targets(&accounts)[0].provider,136
CalendarProvider::Outlook137
);138
}139
140
#[test]141
fn google_home_needs_join_first() {142
assert!(needs_join_first(&google_home()));143
}144
145
#[test]146
fn outlook_home_with_google_extra_needs_join_first() {147
let mut accounts = CalendarAccounts::default();148
accounts149
.write_targets150
.push(CalendarRef::google("g1", "primary"));151
assert!(needs_join_first(&accounts));152
assert_eq!(create_targets(&accounts).len(), 2);153
}154
155
#[test]156
fn partial_notice_keeps_join_url() {157
let notice = partial_create_notice(158
"https://teams.microsoft.com/l/meetup-join/x",159
&["Google:primary".into()],160
);161
assert!(notice.contains("teams.microsoft.com"));162
assert!(notice.contains("Google:primary"));163
}164
}@@ -1,6 +1,6 @@
1
1
use std::collections::HashMap;
2
2
3
use chatsvc::{CalendarEvent, Reminder};
3
use chatsvc::{CalendarEvent, CalendarSource, Reminder};
4
4
use chrono::{DateTime, Duration, Utc};
5
5
use gpui_kit::Context;
6
6
@@ -33,6 +33,9 @@ pub enum ReminderWrite {
33
33
}
34
34
35
35
fn watched(event: &CalendarEvent, now: DateTime<Utc>) -> bool {
36
if event.source != CalendarSource::Outlook {
37
return false;
38
}
36
39
let watch_from = event.start - Duration::minutes(LEAD_MINUTES + WATCH_BEFORE_LEAD_MINUTES);
37
40
let watch_until = event
38
41
.end
@@ -79,6 +82,11 @@ impl OutlookReminders {
79
82
}
80
83
81
84
pub fn allows(&self, event: &CalendarEvent, now: DateTime<Utc>) -> bool {
85
// Google (and later sources) use the local Soon/Started phase only —
86
// Outlook ReminderView must not suppress them when the id is absent.
87
if event.source != CalendarSource::Outlook {
88
return true;
89
}
82
90
let Some(known) = &self.known else {
83
91
return true;
84
92
};
@@ -192,6 +200,7 @@ mod tests {
192
200
show_as: Default::default(),
193
201
dial_in: None,
194
202
response: ResponseType::Accepted,
203
..Default::default()
195
204
}
196
205
}
197
206
@@ -243,6 +252,16 @@ mod tests {
243
252
assert!(outlook.allows(&event("b"), at(9, 40)));
244
253
}
245
254
255
#[test]
256
fn google_events_stay_allowed_when_outlook_reminder_view_is_loaded() {
257
let outlook = known(vec![reminder("outlook-1", at(9, 30))], at(9, 39));
258
let mut google = event("google-1");
259
google.source = CalendarSource::Google;
260
google.sources = vec![CalendarSource::Google];
261
assert!(outlook.allows(&google, at(9, 40)));
262
assert!(!outlook.allows(&event("missing-outlook"), at(9, 40)));
263
}
264
246
265
#[test]
247
266
fn a_reminder_snoozed_in_outlook_waits_for_its_fire_time() {
248
267
let outlook = known(vec![reminder("a", at(9, 43))], at(9, 39));
@@ -1,6 +1,6 @@1
use std::collections::HashMap;1
use std::collections::HashMap;2
2
3
use chatsvc::{CalendarEvent, Reminder};3
use chatsvc::{CalendarEvent, CalendarSource, Reminder};4
use chrono::{DateTime, Duration, Utc};4
use chrono::{DateTime, Duration, Utc};5
use gpui_kit::Context;5
use gpui_kit::Context;6
6
@@ -33,6 +33,9 @@ pub enum ReminderWrite {33
}33
}34
34
35
fn watched(event: &CalendarEvent, now: DateTime<Utc>) -> bool {35
fn watched(event: &CalendarEvent, now: DateTime<Utc>) -> bool {36
if event.source != CalendarSource::Outlook {37
return false;38
}36
let watch_from = event.start - Duration::minutes(LEAD_MINUTES + WATCH_BEFORE_LEAD_MINUTES);39
let watch_from = event.start - Duration::minutes(LEAD_MINUTES + WATCH_BEFORE_LEAD_MINUTES);37
let watch_until = event40
let watch_until = event38
.end41
.end@@ -79,6 +82,11 @@ impl OutlookReminders {79
}82
}80
83
81
pub fn allows(&self, event: &CalendarEvent, now: DateTime<Utc>) -> bool {84
pub fn allows(&self, event: &CalendarEvent, now: DateTime<Utc>) -> bool {85
// Google (and later sources) use the local Soon/Started phase only —86
// Outlook ReminderView must not suppress them when the id is absent.87
if event.source != CalendarSource::Outlook {88
return true;89
}82
let Some(known) = &self.known else {90
let Some(known) = &self.known else {83
return true;91
return true;84
};92
};@@ -192,6 +200,7 @@ mod tests {192
show_as: Default::default(),200
show_as: Default::default(),193
dial_in: None,201
dial_in: None,194
response: ResponseType::Accepted,202
response: ResponseType::Accepted,203
..Default::default()195
}204
}196
}205
}197
206
@@ -243,6 +252,16 @@ mod tests {243
assert!(outlook.allows(&event("b"), at(9, 40)));252
assert!(outlook.allows(&event("b"), at(9, 40)));244
}253
}245
254
255
#[test]256
fn google_events_stay_allowed_when_outlook_reminder_view_is_loaded() {257
let outlook = known(vec![reminder("outlook-1", at(9, 30))], at(9, 39));258
let mut google = event("google-1");259
google.source = CalendarSource::Google;260
google.sources = vec![CalendarSource::Google];261
assert!(outlook.allows(&google, at(9, 40)));262
assert!(!outlook.allows(&event("missing-outlook"), at(9, 40)));263
}264
246
#[test]265
#[test]247
fn a_reminder_snoozed_in_outlook_waits_for_its_fire_time() {266
fn a_reminder_snoozed_in_outlook_waits_for_its_fire_time() {248
let outlook = known(vec![reminder("a", at(9, 43))], at(9, 39));267
let outlook = known(vec![reminder("a", at(9, 43))], at(9, 39));@@ -273,27 +273,37 @@ impl MeetingToasts {
273
273
}
274
274
}
275
275
276
fn reminder_source_events(state: &AppState) -> Vec<CalendarEvent> {
277
let mut events = state.calendar_events.clone();
278
for event in &state.calendar_week.events {
279
if !events
280
.iter()
281
.any(|existing| existing.object_id == event.object_id)
282
{
283
events.push(event.clone());
284
}
285
}
286
events
287
}
288
276
289
impl AppState {
277
290
pub fn tick_meeting_reminders(&mut self, show: bool, cx: &mut Context<Self>) {
278
291
let now = Utc::now();
279
292
self.poll_outlook_reminders(now, cx);
280
293
let in_call = self.call.is_some();
281
294
let show = show && !in_call && !self.mode.read_only;
282
for thread_id in self
283
.meeting_toasts
284
.live_candidates(&self.calendar_events, now)
285
{
295
let events = reminder_source_events(self);
296
for thread_id in self.meeting_toasts.live_candidates(&events, now) {
286
297
self.fetch_live_meeting(&thread_id, cx);
287
298
}
288
let live_threads: HashSet<String> = self
289
.calendar_events
299
let live_threads: HashSet<String> = events
290
300
.iter()
291
301
.filter_map(|event| event.thread_id.clone())
292
302
.filter(|thread_id| self.running_meeting(thread_id).is_some())
293
303
.collect();
294
304
let update = self
295
305
.meeting_toasts
296
.update(&self.calendar_events, &live_threads, now, show);
306
.update(&events, &live_threads, now, show);
297
307
if (in_call && self.meeting_toasts.clear()) || update.changed {
298
308
cx.emit(AppEvent::MeetingReminder);
299
309
cx.notify();
@@ -322,7 +332,9 @@ impl AppState {
322
332
323
333
pub fn snooze_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
324
334
if let Some(toast) = self.meeting_toasts.snooze(id) {
325
self.write_outlook_reminder(toast.event_id, ReminderWrite::Snooze(toast.start));
335
if self.outlook_reminder_event(&toast.event_id) {
336
self.write_outlook_reminder(toast.event_id, ReminderWrite::Snooze(toast.start));
337
}
326
338
cx.emit(AppEvent::MeetingReminder);
327
339
cx.notify();
328
340
}
@@ -330,11 +342,21 @@ impl AppState {
330
342
331
343
pub fn dismiss_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
332
344
if let Some(toast) = self.meeting_toasts.dismiss(id) {
333
self.write_outlook_reminder(toast.event_id, ReminderWrite::Dismiss);
345
if self.outlook_reminder_event(&toast.event_id) {
346
self.write_outlook_reminder(toast.event_id, ReminderWrite::Dismiss);
347
}
334
348
cx.emit(AppEvent::MeetingReminder);
335
349
cx.notify();
336
350
}
337
351
}
352
353
fn outlook_reminder_event(&self, event_id: &str) -> bool {
354
self.calendar_events
355
.iter()
356
.chain(self.calendar_week.events.iter())
357
.find(|event| event.object_id == event_id)
358
.is_none_or(|event| event.source == chatsvc::CalendarSource::Outlook)
359
}
338
360
}
339
361
340
362
#[cfg(test)]
@@ -365,6 +387,7 @@ mod tests {
365
387
show_as: Default::default(),
366
388
dial_in: None,
367
389
response: ResponseType::Accepted,
390
..Default::default()
368
391
}
369
392
}
370
393
@@ -273,27 +273,37 @@ impl MeetingToasts {273
}273
}274
}274
}275
275
276
fn reminder_source_events(state: &AppState) -> Vec<CalendarEvent> {277
let mut events = state.calendar_events.clone();278
for event in &state.calendar_week.events {279
if !events280
.iter()281
.any(|existing| existing.object_id == event.object_id)282
{283
events.push(event.clone());284
}285
}286
events287
}288
276
impl AppState {289
impl AppState {277
pub fn tick_meeting_reminders(&mut self, show: bool, cx: &mut Context<Self>) {290
pub fn tick_meeting_reminders(&mut self, show: bool, cx: &mut Context<Self>) {278
let now = Utc::now();291
let now = Utc::now();279
self.poll_outlook_reminders(now, cx);292
self.poll_outlook_reminders(now, cx);280
let in_call = self.call.is_some();293
let in_call = self.call.is_some();281
let show = show && !in_call && !self.mode.read_only;294
let show = show && !in_call && !self.mode.read_only;282
for thread_id in self295
let events = reminder_source_events(self);283
.meeting_toasts296
for thread_id in self.meeting_toasts.live_candidates(&events, now) {284
.live_candidates(&self.calendar_events, now)285
{286
self.fetch_live_meeting(&thread_id, cx);297
self.fetch_live_meeting(&thread_id, cx);287
}298
}288
let live_threads: HashSet<String> = self299
let live_threads: HashSet<String> = events289
.calendar_events290
.iter()300
.iter()291
.filter_map(|event| event.thread_id.clone())301
.filter_map(|event| event.thread_id.clone())292
.filter(|thread_id| self.running_meeting(thread_id).is_some())302
.filter(|thread_id| self.running_meeting(thread_id).is_some())293
.collect();303
.collect();294
let update = self304
let update = self295
.meeting_toasts305
.meeting_toasts296
.update(&self.calendar_events, &live_threads, now, show);306
.update(&events, &live_threads, now, show);297
if (in_call && self.meeting_toasts.clear()) || update.changed {307
if (in_call && self.meeting_toasts.clear()) || update.changed {298
cx.emit(AppEvent::MeetingReminder);308
cx.emit(AppEvent::MeetingReminder);299
cx.notify();309
cx.notify();@@ -322,7 +332,9 @@ impl AppState {322
332
323
pub fn snooze_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {333
pub fn snooze_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {324
if let Some(toast) = self.meeting_toasts.snooze(id) {334
if let Some(toast) = self.meeting_toasts.snooze(id) {325
self.write_outlook_reminder(toast.event_id, ReminderWrite::Snooze(toast.start));335
if self.outlook_reminder_event(&toast.event_id) {336
self.write_outlook_reminder(toast.event_id, ReminderWrite::Snooze(toast.start));337
}326
cx.emit(AppEvent::MeetingReminder);338
cx.emit(AppEvent::MeetingReminder);327
cx.notify();339
cx.notify();328
}340
}@@ -330,11 +342,21 @@ impl AppState {330
342
331
pub fn dismiss_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {343
pub fn dismiss_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {332
if let Some(toast) = self.meeting_toasts.dismiss(id) {344
if let Some(toast) = self.meeting_toasts.dismiss(id) {333
self.write_outlook_reminder(toast.event_id, ReminderWrite::Dismiss);345
if self.outlook_reminder_event(&toast.event_id) {346
self.write_outlook_reminder(toast.event_id, ReminderWrite::Dismiss);347
}334
cx.emit(AppEvent::MeetingReminder);348
cx.emit(AppEvent::MeetingReminder);335
cx.notify();349
cx.notify();336
}350
}337
}351
}352
353
fn outlook_reminder_event(&self, event_id: &str) -> bool {354
self.calendar_events355
.iter()356
.chain(self.calendar_week.events.iter())357
.find(|event| event.object_id == event_id)358
.is_none_or(|event| event.source == chatsvc::CalendarSource::Outlook)359
}338
}360
}339
361
340
#[cfg(test)]362
#[cfg(test)]@@ -365,6 +387,7 @@ mod tests {365
show_as: Default::default(),387
show_as: Default::default(),366
dial_in: None,388
dial_in: None,367
response: ResponseType::Accepted,389
response: ResponseType::Accepted,390
..Default::default()368
}391
}369
}392
}370
393
@@ -12,6 +12,8 @@ const HALF_HOUR_MINUTES: i64 = 30;
12
12
const DEFAULT_LENGTH_MINUTES: i64 = 30;
13
13
const READ_ONLY_MESSAGE: &str = "Meetings cannot be scheduled in read-only mode.";
14
14
const RESPONSE_FAILED_NOTICE: &str = "Could not send your response";
15
const DELETE_FAILED_NOTICE: &str = "Could not delete the meeting";
16
const DELETE_READ_ONLY_NOTICE: &str = "Meetings cannot be deleted in read-only mode.";
15
17
16
18
#[derive(Debug, Clone, PartialEq, Eq)]
17
19
pub struct Invitee {
@@ -129,6 +131,7 @@ fn demo_event(draft: &MeetingDraft, serial: u64) -> CalendarEvent {
129
131
show_as: Default::default(),
130
132
dial_in: None,
131
133
response: ResponseType::Organizer,
134
..Default::default()
132
135
}
133
136
}
134
137
@@ -176,7 +179,11 @@ impl AppState {
176
179
let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));
177
180
return receiver;
178
181
};
179
let created = runtime::spawn(async move { launcher.create_meeting(draft).await });
182
let accounts = store::load_calendar_accounts(&self.store);
183
let store = self.store.clone();
184
let created = runtime::spawn(async move {
185
super::meeting_create::create_across_targets(launcher, draft, accounts, store).await
186
});
180
187
cx.spawn(async move |this, cx| {
181
188
let outcome = created
182
189
.await
@@ -208,6 +215,125 @@ impl AppState {
208
215
self.calls_list.invalidate();
209
216
}
210
217
218
fn remove_calendar_event(&mut self, event_id: &str) -> Option<CalendarEvent> {
219
let mut removed = None;
220
if let Some(index) = self
221
.calendar_week
222
.events
223
.iter()
224
.position(|event| event.object_id == event_id)
225
{
226
removed = Some(self.calendar_week.events.remove(index));
227
}
228
if let Some(index) = self
229
.calendar_events
230
.iter()
231
.position(|event| event.object_id == event_id)
232
{
233
let event = self.calendar_events.remove(index);
234
if removed.is_none() {
235
removed = Some(event);
236
}
237
}
238
self.calls_list.invalidate();
239
removed
240
}
241
242
fn restore_calendar_event(&mut self, event: CalendarEvent) {
243
if !self
244
.calendar_week
245
.events
246
.iter()
247
.any(|existing| existing.object_id == event.object_id)
248
{
249
self.calendar_week.events.push(event.clone());
250
self.calendar_week
251
.events
252
.sort_by_key(|item| (item.start, item.end));
253
}
254
if !self
255
.calendar_events
256
.iter()
257
.any(|existing| existing.object_id == event.object_id)
258
{
259
self.calendar_events.push(event);
260
self.calendar_events
261
.sort_by_key(|item| (item.start, item.end));
262
}
263
self.calls_list.invalidate();
264
}
265
266
pub fn delete_calendar_event(&mut self, event_key: &str, cx: &mut Context<Self>) {
267
if self.mode.read_only {
268
self.raise_notice(DELETE_READ_ONLY_NOTICE.to_owned(), None, cx);
269
return;
270
}
271
let Some(event) = self
272
.calendar_events
273
.iter()
274
.chain(&self.calendar_week.events)
275
.find(|event| event.object_id == event_key)
276
.cloned()
277
else {
278
return;
279
};
280
let snapshot = event.clone();
281
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
282
let source = event.source;
283
let account_id = event.account_id.clone();
284
let calendar_id = event.calendar_id.clone();
285
self.remove_calendar_event(&event_id);
286
cx.notify();
287
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
288
let Some(launcher) = launcher else {
289
return;
290
};
291
let send_updates = self.rsvp_send_response;
292
let store = self.store.clone();
293
let deleted = runtime::spawn({
294
let event_id = event_id.clone();
295
async move {
296
match source {
297
chatsvc::CalendarSource::Outlook => {
298
launcher
299
.delete_calendar_event(&event_id, ical_uid.as_deref())
300
.await
301
}
302
chatsvc::CalendarSource::Google => {
303
let mut accounts = store::load_calendar_accounts(&store);
304
let account =
305
account_id.ok_or_else(|| "Google account missing".to_owned())?;
306
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
307
let result = crate::google_calendar_sync::delete_google_event(
308
&mut accounts,
309
&account,
310
&calendar,
311
&event_id,
312
send_updates,
313
)
314
.await;
315
let _ = store::save_calendar_accounts(&store, &accounts);
316
result
317
}
318
}
319
}
320
});
321
cx.spawn(async move |this, cx| {
322
let ok = deleted.await.is_ok_and(|result| result.is_ok());
323
this.update(cx, |state, cx| {
324
if ok {
325
// refresh_calendar nudges agenda poll + reloads the week grid.
326
state.refresh_calendar(cx);
327
return;
328
}
329
state.restore_calendar_event(snapshot);
330
state.raise_notice(DELETE_FAILED_NOTICE.to_owned(), None, cx);
331
})
332
.ok();
333
})
334
.detach();
335
}
336
211
337
pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {
212
338
if self.mode.read_only {
213
339
self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
@@ -223,6 +349,9 @@ impl AppState {
223
349
};
224
350
let previous = event.response;
225
351
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
352
let source = event.source;
353
let account_id = event.account_id.clone();
354
let calendar_id = event.calendar_id.clone();
226
355
self.set_event_response(&event_id, response_for(reply));
227
356
cx.notify();
228
357
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
@@ -230,12 +359,34 @@ impl AppState {
230
359
return;
231
360
};
232
361
let send_response = self.rsvp_send_response;
362
let store = self.store.clone();
233
363
let answered = runtime::spawn({
234
364
let event_id = event_id.clone();
235
365
async move {
236
launcher
237
.respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
238
.await
366
match source {
367
chatsvc::CalendarSource::Outlook => {
368
launcher
369
.respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
370
.await
371
}
372
chatsvc::CalendarSource::Google => {
373
let mut accounts = store::load_calendar_accounts(&store);
374
let account =
375
account_id.ok_or_else(|| "Google account missing".to_owned())?;
376
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
377
let result = crate::google_calendar_sync::respond_google_event(
378
&mut accounts,
379
&account,
380
&calendar,
381
&event_id,
382
reply,
383
send_response,
384
)
385
.await;
386
let _ = store::save_calendar_accounts(&store, &accounts);
387
result
388
}
389
}
239
390
}
240
391
});
241
392
cx.spawn(async move |this, cx| {
@@ -12,6 +12,8 @@ const HALF_HOUR_MINUTES: i64 = 30;12
const DEFAULT_LENGTH_MINUTES: i64 = 30;12
const DEFAULT_LENGTH_MINUTES: i64 = 30;13
const READ_ONLY_MESSAGE: &str = "Meetings cannot be scheduled in read-only mode.";13
const READ_ONLY_MESSAGE: &str = "Meetings cannot be scheduled in read-only mode.";14
const RESPONSE_FAILED_NOTICE: &str = "Could not send your response";14
const RESPONSE_FAILED_NOTICE: &str = "Could not send your response";15
const DELETE_FAILED_NOTICE: &str = "Could not delete the meeting";16
const DELETE_READ_ONLY_NOTICE: &str = "Meetings cannot be deleted in read-only mode.";15
17
16
#[derive(Debug, Clone, PartialEq, Eq)]18
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct Invitee {19
pub struct Invitee {@@ -129,6 +131,7 @@ fn demo_event(draft: &MeetingDraft, serial: u64) -> CalendarEvent {129
show_as: Default::default(),131
show_as: Default::default(),130
dial_in: None,132
dial_in: None,131
response: ResponseType::Organizer,133
response: ResponseType::Organizer,134
..Default::default()132
}135
}133
}136
}134
137
@@ -176,7 +179,11 @@ impl AppState {176
let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));179
let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));177
return receiver;180
return receiver;178
};181
};179
let created = runtime::spawn(async move { launcher.create_meeting(draft).await });182
let accounts = store::load_calendar_accounts(&self.store);183
let store = self.store.clone();184
let created = runtime::spawn(async move {185
super::meeting_create::create_across_targets(launcher, draft, accounts, store).await186
});180
cx.spawn(async move |this, cx| {187
cx.spawn(async move |this, cx| {181
let outcome = created188
let outcome = created182
.await189
.await@@ -208,6 +215,125 @@ impl AppState {208
self.calls_list.invalidate();215
self.calls_list.invalidate();209
}216
}210
217
218
fn remove_calendar_event(&mut self, event_id: &str) -> Option<CalendarEvent> {219
let mut removed = None;220
if let Some(index) = self221
.calendar_week222
.events223
.iter()224
.position(|event| event.object_id == event_id)225
{226
removed = Some(self.calendar_week.events.remove(index));227
}228
if let Some(index) = self229
.calendar_events230
.iter()231
.position(|event| event.object_id == event_id)232
{233
let event = self.calendar_events.remove(index);234
if removed.is_none() {235
removed = Some(event);236
}237
}238
self.calls_list.invalidate();239
removed240
}241
242
fn restore_calendar_event(&mut self, event: CalendarEvent) {243
if !self244
.calendar_week245
.events246
.iter()247
.any(|existing| existing.object_id == event.object_id)248
{249
self.calendar_week.events.push(event.clone());250
self.calendar_week251
.events252
.sort_by_key(|item| (item.start, item.end));253
}254
if !self255
.calendar_events256
.iter()257
.any(|existing| existing.object_id == event.object_id)258
{259
self.calendar_events.push(event);260
self.calendar_events261
.sort_by_key(|item| (item.start, item.end));262
}263
self.calls_list.invalidate();264
}265
266
pub fn delete_calendar_event(&mut self, event_key: &str, cx: &mut Context<Self>) {267
if self.mode.read_only {268
self.raise_notice(DELETE_READ_ONLY_NOTICE.to_owned(), None, cx);269
return;270
}271
let Some(event) = self272
.calendar_events273
.iter()274
.chain(&self.calendar_week.events)275
.find(|event| event.object_id == event_key)276
.cloned()277
else {278
return;279
};280
let snapshot = event.clone();281
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());282
let source = event.source;283
let account_id = event.account_id.clone();284
let calendar_id = event.calendar_id.clone();285
self.remove_calendar_event(&event_id);286
cx.notify();287
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);288
let Some(launcher) = launcher else {289
return;290
};291
let send_updates = self.rsvp_send_response;292
let store = self.store.clone();293
let deleted = runtime::spawn({294
let event_id = event_id.clone();295
async move {296
match source {297
chatsvc::CalendarSource::Outlook => {298
launcher299
.delete_calendar_event(&event_id, ical_uid.as_deref())300
.await301
}302
chatsvc::CalendarSource::Google => {303
let mut accounts = store::load_calendar_accounts(&store);304
let account =305
account_id.ok_or_else(|| "Google account missing".to_owned())?;306
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());307
let result = crate::google_calendar_sync::delete_google_event(308
&mut accounts,309
&account,310
&calendar,311
&event_id,312
send_updates,313
)314
.await;315
let _ = store::save_calendar_accounts(&store, &accounts);316
result317
}318
}319
}320
});321
cx.spawn(async move |this, cx| {322
let ok = deleted.await.is_ok_and(|result| result.is_ok());323
this.update(cx, |state, cx| {324
if ok {325
// refresh_calendar nudges agenda poll + reloads the week grid.326
state.refresh_calendar(cx);327
return;328
}329
state.restore_calendar_event(snapshot);330
state.raise_notice(DELETE_FAILED_NOTICE.to_owned(), None, cx);331
})332
.ok();333
})334
.detach();335
}336
211
pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {337
pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {212
if self.mode.read_only {338
if self.mode.read_only {213
self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);339
self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);@@ -223,6 +349,9 @@ impl AppState {223
};349
};224
let previous = event.response;350
let previous = event.response;225
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());351
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());352
let source = event.source;353
let account_id = event.account_id.clone();354
let calendar_id = event.calendar_id.clone();226
self.set_event_response(&event_id, response_for(reply));355
self.set_event_response(&event_id, response_for(reply));227
cx.notify();356
cx.notify();228
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);357
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);@@ -230,12 +359,34 @@ impl AppState {230
return;359
return;231
};360
};232
let send_response = self.rsvp_send_response;361
let send_response = self.rsvp_send_response;362
let store = self.store.clone();233
let answered = runtime::spawn({363
let answered = runtime::spawn({234
let event_id = event_id.clone();364
let event_id = event_id.clone();235
async move {365
async move {236
launcher366
match source {237
.respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)367
chatsvc::CalendarSource::Outlook => {238
.await368
launcher369
.respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)370
.await371
}372
chatsvc::CalendarSource::Google => {373
let mut accounts = store::load_calendar_accounts(&store);374
let account =375
account_id.ok_or_else(|| "Google account missing".to_owned())?;376
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());377
let result = crate::google_calendar_sync::respond_google_event(378
&mut accounts,379
&account,380
&calendar,381
&event_id,382
reply,383
send_response,384
)385
.await;386
let _ = store::save_calendar_accounts(&store, &accounts);387
result388
}389
}239
}390
}240
});391
});241
cx.spawn(async move |this, cx| {392
cx.spawn(async move |this, cx| {@@ -73,7 +73,7 @@ impl AppState {
73
73
self.show_calendar_date(date, cx);
74
74
}
75
75
76
fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
76
pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
77
77
let start = self.calendar_start();
78
78
let offset = Local::now().offset().fix();
79
79
let (from, to) = week_range(start, self.calendar_week.span.days(), offset);
@@ -94,17 +94,48 @@ impl AppState {
94
94
let request = self.calendar_week.request;
95
95
self.calendar_week.loading = true;
96
96
cx.notify();
97
let receiver = crate::runtime::spawn(async move { launcher.calendar_view(from, to).await });
97
let store = self.store.clone();
98
let receiver = crate::runtime::spawn(async move {
99
let mut accounts = store::load_calendar_accounts(&store);
100
let mut combined = Vec::new();
101
let mut outlook_failed = false;
102
if accounts.outlook_selected {
103
match launcher.calendar_view(from, to).await {
104
Ok(events) => combined.extend(events),
105
Err(error) => {
106
outlook_failed = true;
107
crate::diagnostics::record(format!(
108
"calls: outlook calendar week not loaded: {error}"
109
));
110
}
111
}
112
}
113
match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {
114
Ok(events) => {
115
let _ = store::save_calendar_accounts(&store, &accounts);
116
combined.extend(events);
117
}
118
Err(error) => crate::diagnostics::record(format!(
119
"calls: google calendar week not loaded: {error}"
120
)),
121
}
122
if combined.is_empty() && outlook_failed && !accounts.has_google() {
123
return Err(CALENDAR_LOAD_FAILURE.to_owned());
124
}
125
Ok(chatsvc::merge_calendar_events(combined))
126
});
98
127
cx.spawn(async move |this, cx| {
99
let loaded = receiver.await.ok().and_then(Result::ok);
128
let loaded = receiver
129
.await
130
.unwrap_or_else(|_| Err(CALENDAR_LOAD_FAILURE.to_owned()));
100
131
this.update(cx, |state, cx| {
101
132
if state.calendar_week.request != request {
102
133
return;
103
134
}
104
135
state.calendar_week.loading = false;
105
136
match loaded {
106
Some(events) => state.calendar_week.events = events,
107
None => state.raise_notice(CALENDAR_LOAD_FAILURE.to_owned(), None, cx),
137
Ok(events) => state.calendar_week.events = events,
138
Err(notice) => state.raise_notice(notice, None, cx),
108
139
}
109
140
cx.notify();
110
141
})
@@ -213,6 +244,7 @@ fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
213
244
show_as: demo_show_as(subject, *response),
214
245
dial_in: None,
215
246
response: *response,
247
..Default::default()
216
248
}
217
249
})
218
250
.collect()
@@ -73,7 +73,7 @@ impl AppState {73
self.show_calendar_date(date, cx);73
self.show_calendar_date(date, cx);74
}74
}75
75
76
fn load_calendar_week(&mut self, cx: &mut Context<Self>) {76
pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {77
let start = self.calendar_start();77
let start = self.calendar_start();78
let offset = Local::now().offset().fix();78
let offset = Local::now().offset().fix();79
let (from, to) = week_range(start, self.calendar_week.span.days(), offset);79
let (from, to) = week_range(start, self.calendar_week.span.days(), offset);@@ -94,17 +94,48 @@ impl AppState {94
let request = self.calendar_week.request;94
let request = self.calendar_week.request;95
self.calendar_week.loading = true;95
self.calendar_week.loading = true;96
cx.notify();96
cx.notify();97
let receiver = crate::runtime::spawn(async move { launcher.calendar_view(from, to).await });97
let store = self.store.clone();98
let receiver = crate::runtime::spawn(async move {99
let mut accounts = store::load_calendar_accounts(&store);100
let mut combined = Vec::new();101
let mut outlook_failed = false;102
if accounts.outlook_selected {103
match launcher.calendar_view(from, to).await {104
Ok(events) => combined.extend(events),105
Err(error) => {106
outlook_failed = true;107
crate::diagnostics::record(format!(108
"calls: outlook calendar week not loaded: {error}"109
));110
}111
}112
}113
match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {114
Ok(events) => {115
let _ = store::save_calendar_accounts(&store, &accounts);116
combined.extend(events);117
}118
Err(error) => crate::diagnostics::record(format!(119
"calls: google calendar week not loaded: {error}"120
)),121
}122
if combined.is_empty() && outlook_failed && !accounts.has_google() {123
return Err(CALENDAR_LOAD_FAILURE.to_owned());124
}125
Ok(chatsvc::merge_calendar_events(combined))126
});98
cx.spawn(async move |this, cx| {127
cx.spawn(async move |this, cx| {99
let loaded = receiver.await.ok().and_then(Result::ok);128
let loaded = receiver129
.await130
.unwrap_or_else(|_| Err(CALENDAR_LOAD_FAILURE.to_owned()));100
this.update(cx, |state, cx| {131
this.update(cx, |state, cx| {101
if state.calendar_week.request != request {132
if state.calendar_week.request != request {102
return;133
return;103
}134
}104
state.calendar_week.loading = false;135
state.calendar_week.loading = false;105
match loaded {136
match loaded {106
Some(events) => state.calendar_week.events = events,137
Ok(events) => state.calendar_week.events = events,107
None => state.raise_notice(CALENDAR_LOAD_FAILURE.to_owned(), None, cx),138
Err(notice) => state.raise_notice(notice, None, cx),108
}139
}109
cx.notify();140
cx.notify();110
})141
})@@ -213,6 +244,7 @@ fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {213
show_as: demo_show_as(subject, *response),244
show_as: demo_show_as(subject, *response),214
dial_in: None,245
dial_in: None,215
response: *response,246
response: *response,247
..Default::default()216
}248
}217
})249
})218
.collect()250
.collect()@@ -0,0 +1,165 @@
1
use chrono::{DateTime, Utc};
2
use store::{CalendarAccounts, GoogleTokenSet};
3
4
use chatsvc::{
5
CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, client_id_from_env,
6
google_rsvp_status, refresh_access_token,
7
};
8
9
/// Refresh tokens when needed and load events from every selected Google calendar.
10
pub async fn fetch_google_events(
11
accounts: &mut CalendarAccounts,
12
start: DateTime<Utc>,
13
end: DateTime<Utc>,
14
) -> Result<Vec<CalendarEvent>, String> {
15
let Some(oauth) = client_id_from_env() else {
16
return Ok(Vec::new());
17
};
18
let mut all = Vec::new();
19
for index in 0..accounts.google_accounts.len() {
20
if !ensure_access_token(accounts, index, &oauth).await? {
21
continue;
22
}
23
let account = &accounts.google_accounts[index];
24
let access = account.tokens.access_token.clone();
25
let account_id = account.id.clone();
26
let calendars: Vec<_> = account
27
.calendars
28
.iter()
29
.filter(|calendar| calendar.selected)
30
.map(|calendar| calendar.id.clone())
31
.collect();
32
let calendars = if calendars.is_empty() {
33
vec!["primary".to_owned()]
34
} else {
35
calendars
36
};
37
let client = GoogleCalendar::new(access);
38
for calendar_id in calendars {
39
match client.events(&calendar_id, start, end).await {
40
Ok(mut events) => {
41
for event in &mut events {
42
event.account_id = Some(account_id.clone());
43
event.calendar_id = Some(calendar_id.clone());
44
}
45
all.extend(events);
46
}
47
Err(error) => crate::diagnostics::record(format!(
48
"calls: google calendar {calendar_id} not loaded: {error}"
49
)),
50
}
51
}
52
}
53
Ok(all)
54
}
55
56
pub async fn insert_google_event(
57
accounts: &mut CalendarAccounts,
58
account_id: &str,
59
calendar_id: &str,
60
draft: &GoogleEventDraft,
61
) -> Result<(), String> {
62
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
63
let index = accounts
64
.google_accounts
65
.iter()
66
.position(|account| account.id == account_id)
67
.ok_or_else(|| format!("Google account {account_id} missing"))?;
68
if !ensure_access_token(accounts, index, &oauth).await? {
69
return Err("Google access token missing".into());
70
}
71
let access = accounts.google_accounts[index].tokens.access_token.clone();
72
GoogleCalendar::new(access)
73
.insert_event(calendar_id, draft)
74
.await
75
.map(|_| ())
76
.map_err(|error| error.to_string())
77
}
78
79
pub async fn respond_google_event(
80
accounts: &mut CalendarAccounts,
81
account_id: &str,
82
calendar_id: &str,
83
event_id: &str,
84
reply: Reply,
85
send_updates: bool,
86
) -> Result<(), String> {
87
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
88
let index = accounts
89
.google_accounts
90
.iter()
91
.position(|account| account.id == account_id)
92
.ok_or_else(|| format!("Google account {account_id} missing"))?;
93
if !ensure_access_token(accounts, index, &oauth).await? {
94
return Err("Google access token missing".into());
95
}
96
let access = accounts.google_accounts[index].tokens.access_token.clone();
97
GoogleCalendar::new(access)
98
.respond(
99
calendar_id,
100
event_id,
101
google_rsvp_status(reply),
102
send_updates,
103
)
104
.await
105
.map_err(|error| error.to_string())
106
}
107
108
pub async fn delete_google_event(
109
accounts: &mut CalendarAccounts,
110
account_id: &str,
111
calendar_id: &str,
112
event_id: &str,
113
send_updates: bool,
114
) -> Result<(), String> {
115
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
116
let index = accounts
117
.google_accounts
118
.iter()
119
.position(|account| account.id == account_id)
120
.ok_or_else(|| format!("Google account {account_id} missing"))?;
121
if !ensure_access_token(accounts, index, &oauth).await? {
122
return Err("Google access token missing".into());
123
}
124
let access = accounts.google_accounts[index].tokens.access_token.clone();
125
GoogleCalendar::new(access)
126
.delete_event(calendar_id, event_id, send_updates)
127
.await
128
.map_err(|error| error.to_string())
129
}
130
131
async fn ensure_access_token(
132
accounts: &mut CalendarAccounts,
133
index: usize,
134
oauth: &GoogleOAuth,
135
) -> Result<bool, String> {
136
let now = Utc::now().timestamp();
137
let account = &mut accounts.google_accounts[index];
138
if account.tokens.refresh_token.is_empty() && account.tokens.access_token.is_empty() {
139
return Ok(false);
140
}
141
if account.tokens.expires_at <= now + 60 && !account.tokens.refresh_token.is_empty() {
142
match refresh_access_token(oauth, &account.tokens.refresh_token).await {
143
Ok(bundle) => {
144
account.tokens = GoogleTokenSet {
145
access_token: bundle.access_token,
146
refresh_token: if bundle.refresh_token.is_empty() {
147
account.tokens.refresh_token.clone()
148
} else {
149
bundle.refresh_token
150
},
151
expires_at: now + bundle.expires_in.max(60),
152
};
153
}
154
Err(error) => {
155
crate::diagnostics::record(format!("calls: google token refresh failed: {error}"));
156
return Ok(false);
157
}
158
}
159
}
160
Ok(!account.tokens.access_token.is_empty())
161
}
162
163
fn missing_client_id() -> String {
164
"Set TEAMS_GOOGLE_CLIENT_ID to connect Google Calendar".into()
165
}
@@ -0,0 +1,165 @@1
use chrono::{DateTime, Utc};2
use store::{CalendarAccounts, GoogleTokenSet};3
4
use chatsvc::{5
CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, client_id_from_env,6
google_rsvp_status, refresh_access_token,7
};8
9
/// Refresh tokens when needed and load events from every selected Google calendar.10
pub async fn fetch_google_events(11
accounts: &mut CalendarAccounts,12
start: DateTime<Utc>,13
end: DateTime<Utc>,14
) -> Result<Vec<CalendarEvent>, String> {15
let Some(oauth) = client_id_from_env() else {16
return Ok(Vec::new());17
};18
let mut all = Vec::new();19
for index in 0..accounts.google_accounts.len() {20
if !ensure_access_token(accounts, index, &oauth).await? {21
continue;22
}23
let account = &accounts.google_accounts[index];24
let access = account.tokens.access_token.clone();25
let account_id = account.id.clone();26
let calendars: Vec<_> = account27
.calendars28
.iter()29
.filter(|calendar| calendar.selected)30
.map(|calendar| calendar.id.clone())31
.collect();32
let calendars = if calendars.is_empty() {33
vec!["primary".to_owned()]34
} else {35
calendars36
};37
let client = GoogleCalendar::new(access);38
for calendar_id in calendars {39
match client.events(&calendar_id, start, end).await {40
Ok(mut events) => {41
for event in &mut events {42
event.account_id = Some(account_id.clone());43
event.calendar_id = Some(calendar_id.clone());44
}45
all.extend(events);46
}47
Err(error) => crate::diagnostics::record(format!(48
"calls: google calendar {calendar_id} not loaded: {error}"49
)),50
}51
}52
}53
Ok(all)54
}55
56
pub async fn insert_google_event(57
accounts: &mut CalendarAccounts,58
account_id: &str,59
calendar_id: &str,60
draft: &GoogleEventDraft,61
) -> Result<(), String> {62
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;63
let index = accounts64
.google_accounts65
.iter()66
.position(|account| account.id == account_id)67
.ok_or_else(|| format!("Google account {account_id} missing"))?;68
if !ensure_access_token(accounts, index, &oauth).await? {69
return Err("Google access token missing".into());70
}71
let access = accounts.google_accounts[index].tokens.access_token.clone();72
GoogleCalendar::new(access)73
.insert_event(calendar_id, draft)74
.await75
.map(|_| ())76
.map_err(|error| error.to_string())77
}78
79
pub async fn respond_google_event(80
accounts: &mut CalendarAccounts,81
account_id: &str,82
calendar_id: &str,83
event_id: &str,84
reply: Reply,85
send_updates: bool,86
) -> Result<(), String> {87
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;88
let index = accounts89
.google_accounts90
.iter()91
.position(|account| account.id == account_id)92
.ok_or_else(|| format!("Google account {account_id} missing"))?;93
if !ensure_access_token(accounts, index, &oauth).await? {94
return Err("Google access token missing".into());95
}96
let access = accounts.google_accounts[index].tokens.access_token.clone();97
GoogleCalendar::new(access)98
.respond(99
calendar_id,100
event_id,101
google_rsvp_status(reply),102
send_updates,103
)104
.await105
.map_err(|error| error.to_string())106
}107
108
pub async fn delete_google_event(109
accounts: &mut CalendarAccounts,110
account_id: &str,111
calendar_id: &str,112
event_id: &str,113
send_updates: bool,114
) -> Result<(), String> {115
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;116
let index = accounts117
.google_accounts118
.iter()119
.position(|account| account.id == account_id)120
.ok_or_else(|| format!("Google account {account_id} missing"))?;121
if !ensure_access_token(accounts, index, &oauth).await? {122
return Err("Google access token missing".into());123
}124
let access = accounts.google_accounts[index].tokens.access_token.clone();125
GoogleCalendar::new(access)126
.delete_event(calendar_id, event_id, send_updates)127
.await128
.map_err(|error| error.to_string())129
}130
131
async fn ensure_access_token(132
accounts: &mut CalendarAccounts,133
index: usize,134
oauth: &GoogleOAuth,135
) -> Result<bool, String> {136
let now = Utc::now().timestamp();137
let account = &mut accounts.google_accounts[index];138
if account.tokens.refresh_token.is_empty() && account.tokens.access_token.is_empty() {139
return Ok(false);140
}141
if account.tokens.expires_at <= now + 60 && !account.tokens.refresh_token.is_empty() {142
match refresh_access_token(oauth, &account.tokens.refresh_token).await {143
Ok(bundle) => {144
account.tokens = GoogleTokenSet {145
access_token: bundle.access_token,146
refresh_token: if bundle.refresh_token.is_empty() {147
account.tokens.refresh_token.clone()148
} else {149
bundle.refresh_token150
},151
expires_at: now + bundle.expires_in.max(60),152
};153
}154
Err(error) => {155
crate::diagnostics::record(format!("calls: google token refresh failed: {error}"));156
return Ok(false);157
}158
}159
}160
Ok(!account.tokens.access_token.is_empty())161
}162
163
fn missing_client_id() -> String {164
"Set TEAMS_GOOGLE_CLIENT_ID to connect Google Calendar".into()165
}@@ -5,6 +5,7 @@ pub mod agents;
5
5
pub mod app_state;
6
6
pub mod backend;
7
7
pub mod banner_image;
8
pub mod calendar_accounts_actions;
8
9
pub mod call;
9
10
pub mod call_rows;
10
11
pub mod card_actions;
@@ -28,6 +29,7 @@ pub mod emoji;
28
29
pub mod find_in_chat;
29
30
pub mod forward_selection;
30
31
pub mod gifs;
32
pub mod google_calendar_sync;
31
33
pub mod image_view_gallery;
32
34
pub mod importance;
33
35
pub mod local_previews;
@@ -5,6 +5,7 @@ pub mod agents;5
pub mod app_state;5
pub mod app_state;6
pub mod backend;6
pub mod backend;7
pub mod banner_image;7
pub mod banner_image;8
pub mod calendar_accounts_actions;8
pub mod call;9
pub mod call;9
pub mod call_rows;10
pub mod call_rows;10
pub mod card_actions;11
pub mod card_actions;@@ -28,6 +29,7 @@ pub mod emoji;28
pub mod find_in_chat;29
pub mod find_in_chat;29
pub mod forward_selection;30
pub mod forward_selection;30
pub mod gifs;31
pub mod gifs;32
pub mod google_calendar_sync;31
pub mod image_view_gallery;33
pub mod image_view_gallery;32
pub mod importance;34
pub mod importance;33
pub mod local_previews;35
pub mod local_previews;@@ -9,6 +9,7 @@ pub enum SettingsSection {
9
9
Appearance,
10
10
Chats,
11
11
Calls,
12
Calendar,
12
13
Devices,
13
14
Agents,
14
15
Mcp,
@@ -9,6 +9,7 @@ pub enum SettingsSection {9
Appearance,9
Appearance,10
Chats,10
Chats,11
Calls,11
Calls,12
Calendar,12
Devices,13
Devices,13
Agents,14
Agents,14
Mcp,15
Mcp,@@ -0,0 +1,180 @@
1
use gpui_kit::component::v_flex;
2
use gpui_kit::*;
3
use store::{CalendarProvider, CalendarRef};
4
5
use super::rows::{caption, control_row, text_button, toggle_row};
6
use crate::app_state::AppState;
7
use crate::theme;
8
9
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
10
let accounts = app.read(cx).calendar_accounts();
11
let mut body = v_flex()
12
.w_full()
13
.child(caption("GOOGLE"))
14
.child(connect_row(app, accounts.has_google()));
15
for account in &accounts.google_accounts {
16
body = body.child(account_block(app, account, &accounts));
17
}
18
body = body
19
.child(caption("HOME CALENDAR"))
20
.child(home_choices(app, &accounts))
21
.child(caption("ALSO WRITE TO"));
22
if accounts.home.provider != CalendarProvider::Outlook {
23
let write_app = app.clone();
24
let target = CalendarRef::outlook();
25
let selected = accounts
26
.write_targets
27
.iter()
28
.any(|existing| existing.key() == target.key());
29
body = body.child(
30
toggle_row(
31
"settings-write-outlook",
32
"Outlook (Microsoft mailbox)",
33
"Dual-write when home is Google",
34
theme::text_muted(),
35
selected,
36
)
37
.on_click(move |_, _, cx| {
38
write_app.update(cx, |state, cx| {
39
state.toggle_write_target(target.clone(), cx)
40
})
41
}),
42
);
43
} else if accounts.google_accounts.is_empty() {
44
body = body.child(control_row(
45
"No extra write targets",
46
"Connect Google, then enable dual-write on a calendar above.",
47
div(),
48
));
49
}
50
body
51
}
52
53
fn connect_row(app: &Entity<AppState>, connected: bool) -> Div {
54
let app = app.clone();
55
if connected {
56
control_row(
57
"Google Calendar",
58
"Connected accounts appear below. Disconnect removes tokens from this device.",
59
div(),
60
)
61
} else {
62
control_row(
63
"Google Calendar",
64
"Requires TEAMS_GOOGLE_CLIENT_ID. Opens a browser for sign-in.",
65
text_button("settings-google-connect", "Connect Google").on_click(move |_, _, cx| {
66
app.update(cx, |state, cx| state.connect_google_calendar(cx))
67
}),
68
)
69
}
70
}
71
72
fn account_block(
73
app: &Entity<AppState>,
74
account: &store::GoogleAccount,
75
accounts: &store::CalendarAccounts,
76
) -> Div {
77
let disconnect_app = app.clone();
78
let account_id = account.id.clone();
79
let mut block = v_flex().w_full().child(control_row(
80
account.email.clone(),
81
"Google account",
82
text_button(
83
format!("settings-google-disconnect-{}", account.id),
84
"Disconnect",
85
)
86
.on_click(move |_, _, cx| {
87
disconnect_app.update(cx, |state, cx| {
88
state.disconnect_google_account(&account_id, cx)
89
})
90
}),
91
));
92
for calendar in &account.calendars {
93
let toggle_app = app.clone();
94
let account_id = account.id.clone();
95
let calendar_id = calendar.id.clone();
96
let write_ref = CalendarRef::google(&account.id, &calendar.id);
97
let is_home = accounts.home.key() == write_ref.key();
98
let is_write = accounts
99
.write_targets
100
.iter()
101
.any(|target| target.key() == write_ref.key());
102
block = block.child(
103
toggle_row(
104
format!("settings-google-cal-{}", calendar.id),
105
calendar.summary.clone(),
106
if calendar.primary {
107
"Primary calendar"
108
} else {
109
"Show in calendar grid"
110
},
111
theme::text_muted(),
112
calendar.selected,
113
)
114
.on_click(move |_, _, cx| {
115
toggle_app.update(cx, |state, cx| {
116
state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)
117
})
118
}),
119
);
120
if !is_home {
121
let write_app = app.clone();
122
let target = write_ref;
123
block = block.child(
124
toggle_row(
125
format!("settings-google-write-{}", calendar.id),
126
format!("Also write new meetings to {}", calendar.summary),
127
"",
128
theme::text_muted(),
129
is_write,
130
)
131
.on_click(move |_, _, cx| {
132
write_app.update(cx, |state, cx| {
133
state.toggle_write_target(target.clone(), cx)
134
})
135
}),
136
);
137
}
138
}
139
block
140
}
141
142
fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {
143
let mut choices = v_flex().w_full();
144
let outlook_app = app.clone();
145
let outlook_home = accounts.home.provider == CalendarProvider::Outlook;
146
choices = choices.child(
147
toggle_row(
148
"settings-home-outlook",
149
"Outlook (Microsoft mailbox)",
150
"Default when no Google home is chosen",
151
theme::text_muted(),
152
outlook_home,
153
)
154
.on_click(move |_, _, cx| {
155
outlook_app.update(cx, |state, cx| {
156
state.set_home_calendar(CalendarRef::outlook(), cx)
157
})
158
}),
159
);
160
for account in &accounts.google_accounts {
161
for calendar in &account.calendars {
162
let home_app = app.clone();
163
let target = CalendarRef::google(&account.id, &calendar.id);
164
let selected = accounts.home.key() == target.key();
165
choices = choices.child(
166
toggle_row(
167
format!("settings-home-google-{}", calendar.id),
168
format!("Google · {}", calendar.summary),
169
account.email.clone(),
170
theme::text_muted(),
171
selected,
172
)
173
.on_click(move |_, _, cx| {
174
home_app.update(cx, |state, cx| state.set_home_calendar(target.clone(), cx))
175
}),
176
);
177
}
178
}
179
choices
180
}
@@ -0,0 +1,180 @@1
use gpui_kit::component::v_flex;2
use gpui_kit::*;3
use store::{CalendarProvider, CalendarRef};4
5
use super::rows::{caption, control_row, text_button, toggle_row};6
use crate::app_state::AppState;7
use crate::theme;8
9
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {10
let accounts = app.read(cx).calendar_accounts();11
let mut body = v_flex()12
.w_full()13
.child(caption("GOOGLE"))14
.child(connect_row(app, accounts.has_google()));15
for account in &accounts.google_accounts {16
body = body.child(account_block(app, account, &accounts));17
}18
body = body19
.child(caption("HOME CALENDAR"))20
.child(home_choices(app, &accounts))21
.child(caption("ALSO WRITE TO"));22
if accounts.home.provider != CalendarProvider::Outlook {23
let write_app = app.clone();24
let target = CalendarRef::outlook();25
let selected = accounts26
.write_targets27
.iter()28
.any(|existing| existing.key() == target.key());29
body = body.child(30
toggle_row(31
"settings-write-outlook",32
"Outlook (Microsoft mailbox)",33
"Dual-write when home is Google",34
theme::text_muted(),35
selected,36
)37
.on_click(move |_, _, cx| {38
write_app.update(cx, |state, cx| {39
state.toggle_write_target(target.clone(), cx)40
})41
}),42
);43
} else if accounts.google_accounts.is_empty() {44
body = body.child(control_row(45
"No extra write targets",46
"Connect Google, then enable dual-write on a calendar above.",47
div(),48
));49
}50
body51
}52
53
fn connect_row(app: &Entity<AppState>, connected: bool) -> Div {54
let app = app.clone();55
if connected {56
control_row(57
"Google Calendar",58
"Connected accounts appear below. Disconnect removes tokens from this device.",59
div(),60
)61
} else {62
control_row(63
"Google Calendar",64
"Requires TEAMS_GOOGLE_CLIENT_ID. Opens a browser for sign-in.",65
text_button("settings-google-connect", "Connect Google").on_click(move |_, _, cx| {66
app.update(cx, |state, cx| state.connect_google_calendar(cx))67
}),68
)69
}70
}71
72
fn account_block(73
app: &Entity<AppState>,74
account: &store::GoogleAccount,75
accounts: &store::CalendarAccounts,76
) -> Div {77
let disconnect_app = app.clone();78
let account_id = account.id.clone();79
let mut block = v_flex().w_full().child(control_row(80
account.email.clone(),81
"Google account",82
text_button(83
format!("settings-google-disconnect-{}", account.id),84
"Disconnect",85
)86
.on_click(move |_, _, cx| {87
disconnect_app.update(cx, |state, cx| {88
state.disconnect_google_account(&account_id, cx)89
})90
}),91
));92
for calendar in &account.calendars {93
let toggle_app = app.clone();94
let account_id = account.id.clone();95
let calendar_id = calendar.id.clone();96
let write_ref = CalendarRef::google(&account.id, &calendar.id);97
let is_home = accounts.home.key() == write_ref.key();98
let is_write = accounts99
.write_targets100
.iter()101
.any(|target| target.key() == write_ref.key());102
block = block.child(103
toggle_row(104
format!("settings-google-cal-{}", calendar.id),105
calendar.summary.clone(),106
if calendar.primary {107
"Primary calendar"108
} else {109
"Show in calendar grid"110
},111
theme::text_muted(),112
calendar.selected,113
)114
.on_click(move |_, _, cx| {115
toggle_app.update(cx, |state, cx| {116
state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)117
})118
}),119
);120
if !is_home {121
let write_app = app.clone();122
let target = write_ref;123
block = block.child(124
toggle_row(125
format!("settings-google-write-{}", calendar.id),126
format!("Also write new meetings to {}", calendar.summary),127
"",128
theme::text_muted(),129
is_write,130
)131
.on_click(move |_, _, cx| {132
write_app.update(cx, |state, cx| {133
state.toggle_write_target(target.clone(), cx)134
})135
}),136
);137
}138
}139
block140
}141
142
fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {143
let mut choices = v_flex().w_full();144
let outlook_app = app.clone();145
let outlook_home = accounts.home.provider == CalendarProvider::Outlook;146
choices = choices.child(147
toggle_row(148
"settings-home-outlook",149
"Outlook (Microsoft mailbox)",150
"Default when no Google home is chosen",151
theme::text_muted(),152
outlook_home,153
)154
.on_click(move |_, _, cx| {155
outlook_app.update(cx, |state, cx| {156
state.set_home_calendar(CalendarRef::outlook(), cx)157
})158
}),159
);160
for account in &accounts.google_accounts {161
for calendar in &account.calendars {162
let home_app = app.clone();163
let target = CalendarRef::google(&account.id, &calendar.id);164
let selected = accounts.home.key() == target.key();165
choices = choices.child(166
toggle_row(167
format!("settings-home-google-{}", calendar.id),168
format!("Google · {}", calendar.summary),169
account.email.clone(),170
theme::text_muted(),171
selected,172
)173
.on_click(move |_, _, cx| {174
home_app.update(cx, |state, cx| state.set_home_calendar(target.clone(), cx))175
}),176
);177
}178
}179
choices180
}@@ -9,7 +9,7 @@ use super::devices::DevicesView;
9
9
use super::mcp::McpView;
10
10
use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};
11
11
use super::rows::ROW_INSET;
12
use super::{about, appearance, calls, chats, general, notifications};
12
use super::{about, appearance, calendar, calls, chats, general, notifications};
13
13
use crate::agents::AgentsSettings;
14
14
use crate::app_state::AppState;
15
15
use crate::notify::NotificationCenter;
@@ -186,6 +186,7 @@ impl SettingsDialog {
186
186
SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),
187
187
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
188
188
SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),
189
SettingsSection::Calendar => calendar::render(&self.app, cx).into_any_element(),
189
190
SettingsSection::Devices => self
190
191
.devices
191
192
.clone()
@@ -9,7 +9,7 @@ use super::devices::DevicesView;9
use super::mcp::McpView;9
use super::mcp::McpView;10
use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};10
use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};11
use super::rows::ROW_INSET;11
use super::rows::ROW_INSET;12
use super::{about, appearance, calls, chats, general, notifications};12
use super::{about, appearance, calendar, calls, chats, general, notifications};13
use crate::agents::AgentsSettings;13
use crate::agents::AgentsSettings;14
use crate::app_state::AppState;14
use crate::app_state::AppState;15
use crate::notify::NotificationCenter;15
use crate::notify::NotificationCenter;@@ -186,6 +186,7 @@ impl SettingsDialog {186
SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),186
SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),187
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),187
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),188
SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),188
SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),189
SettingsSection::Calendar => calendar::render(&self.app, cx).into_any_element(),189
SettingsSection::Devices => self190
SettingsSection::Devices => self190
.devices191
.devices191
.clone()192
.clone()@@ -1,6 +1,7 @@
1
1
mod about;
2
2
mod account;
3
3
mod appearance;
4
mod calendar;
4
5
mod calls;
5
6
mod chats;
6
7
mod devices;
@@ -1,6 +1,7 @@1
mod about;1
mod about;2
mod account;2
mod account;3
mod appearance;3
mod appearance;4
mod calendar;4
mod calls;5
mod calls;5
mod chats;6
mod chats;6
mod devices;7
mod devices;@@ -0,0 +1,212 @@
1
use chatsvc::{CalendarEvent, ResponseType, join_info_text};
2
use chrono::{Local, Offset};
3
use gpui_kit::assets::IconName;
4
use gpui_kit::component::Sizable as _;
5
use gpui_kit::component::button::{Button, ButtonVariants as _};
6
use gpui_kit::component::dialog::{Dialog, DialogFooter};
7
use gpui_kit::component::menu::DropdownMenu as _;
8
use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
9
use gpui_kit::*;
10
11
use super::rsvp_menu::rsvp_menu;
12
use crate::app_state::AppState;
13
use crate::call::week_grid::is_effective_all_day;
14
use crate::i18n::tr;
15
use crate::theme;
16
17
const DIALOG_WIDTH: f32 = 440.;
18
const FIELD_GAP: f32 = 12.;
19
const LABEL_SIZE: f32 = 12.;
20
const COPY_JOIN_INFO: &str = "Copy join info";
21
22
fn when_label(event: &CalendarEvent) -> String {
23
let offset = Local::now().offset().fix();
24
if is_effective_all_day(event, offset) {
25
let start = event.start.with_timezone(&offset).date_naive();
26
let end = event.end.with_timezone(&offset).date_naive();
27
if end > start + chrono::Duration::days(1) {
28
return format!(
29
"All day · {} – {}",
30
start.format("%a, %b %-d"),
31
(end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")
32
);
33
}
34
return format!("All day · {}", start.format("%a, %b %-d, %Y"));
35
}
36
let start = event.start.with_timezone(&offset);
37
let end = event.end.with_timezone(&offset);
38
if start.date_naive() == end.date_naive() {
39
format!(
40
"{} · {} – {}",
41
start.format("%a, %b %-d, %Y"),
42
start.format(app_base::format::clock_format()),
43
end.format(app_base::format::clock_format())
44
)
45
} else {
46
format!(
47
"{} {} – {} {}",
48
start.format("%a, %b %-d"),
49
start.format(app_base::format::clock_format()),
50
end.format("%a, %b %-d, %Y"),
51
end.format(app_base::format::clock_format())
52
)
53
}
54
}
55
56
fn source_label(event: &CalendarEvent) -> String {
57
let mut sources = event.sources.clone();
58
if sources.is_empty() {
59
sources.push(event.source);
60
}
61
sources.sort_by_key(|source| source.label());
62
sources.dedup();
63
sources
64
.iter()
65
.map(|source| source.label())
66
.collect::<Vec<_>>()
67
.join(" + ")
68
}
69
70
fn detail_row(label: &str, value: impl Into<SharedString>) -> Div {
71
v_flex()
72
.gap(px(2.))
73
.child(
74
div()
75
.text_size(px(LABEL_SIZE))
76
.text_color(theme::text_muted())
77
.child(label.to_owned()),
78
)
79
.child(
80
div()
81
.text_size(px(14.))
82
.text_color(theme::text())
83
.child(value.into()),
84
)
85
}
86
87
pub fn open_calendar_event(
88
state: Entity<AppState>,
89
event: CalendarEvent,
90
window: &mut Window,
91
cx: &mut App,
92
) {
93
let send_response = state.read(cx).rsvp_send_response;
94
// Show Join whenever a Teams link exists — not only inside the join window.
95
let can_join = event.online && !event.cancelled && event.join_url.is_some();
96
let subject = if event.cancelled {
97
format!("Canceled: {}", event.subject)
98
} else if event.subject.is_empty() {
99
"(No title)".to_owned()
100
} else {
101
event.subject.clone()
102
};
103
let when = when_label(&event);
104
let source = source_label(&event);
105
let organizer = event
106
.organizer_name
107
.clone()
108
.or_else(|| event.organizer_address.clone());
109
let join_url = event.join_url.clone();
110
let dial_in = event.dial_in.clone();
111
let thread_id = event.thread_id.clone();
112
let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();
113
let response = event.response;
114
let event_key = event.object_id.clone();
115
let meeting_title = event.subject.clone();
116
let online = event.online;
117
118
window.open_dialog(cx, move |dialog: Dialog, _, _| {
119
let delete_state = state.clone();
120
let delete_key = event_key.clone();
121
let mut footer = DialogFooter::new()
122
.child(
123
Button::new("calendar-event-delete")
124
.danger()
125
.label(tr("common.delete"))
126
.on_click(move |_, window, cx| {
127
delete_state
128
.update(cx, |state, cx| state.delete_calendar_event(&delete_key, cx));
129
window.close_dialog(cx);
130
}),
131
)
132
.child(
133
Button::new("calendar-event-close")
134
.label(tr("common.close"))
135
.on_click(|_, window, cx| window.close_dialog(cx)),
136
);
137
if can_rsvp {
138
let menu_state = state.clone();
139
let menu_key = event_key.clone();
140
footer = footer.child(
141
Button::new("calendar-event-rsvp")
142
.label("RSVP")
143
.dropdown_menu(move |menu, _, _| {
144
rsvp_menu(menu, &menu_state, &menu_key, response, send_response)
145
}),
146
);
147
}
148
if thread_id.is_some() {
149
let chat_state = state.clone();
150
let chat_thread = thread_id.clone();
151
footer = footer.child(
152
Button::new("calendar-event-chat")
153
.label(tr("common.chat"))
154
.on_click(move |_, window, cx| {
155
chat_state.update(cx, |state, cx| {
156
state.open_meeting_chat(chat_thread.as_deref(), cx)
157
});
158
window.close_dialog(cx);
159
}),
160
);
161
}
162
if can_join {
163
let join_state = state.clone();
164
let url = join_url.clone();
165
let title = meeting_title.clone();
166
footer = footer.child(
167
Button::new("calendar-event-join")
168
.primary()
169
.label(tr("common.join"))
170
.on_click(move |_, window, cx| {
171
join_state.update(cx, |state, cx| {
172
state.join_calendar_meeting(url.as_deref(), &title, cx)
173
});
174
window.close_dialog(cx);
175
}),
176
);
177
}
178
179
let mut body = v_flex()
180
.gap(px(FIELD_GAP))
181
.child(detail_row("When", when.clone()))
182
.child(detail_row("Calendar", source.clone()));
183
if let Some(name) = organizer.clone() {
184
body = body.child(detail_row("Organizer", name));
185
}
186
if let Some(url) = join_url.clone().filter(|_| online) {
187
let info = join_info_text(&url, dial_in.as_ref());
188
body = body.child(
189
v_flex()
190
.gap(px(6.))
191
.child(detail_row("Join link", url))
192
.child(
193
h_flex().child(
194
Button::new("calendar-event-copy-join")
195
.small()
196
.label(COPY_JOIN_INFO)
197
.icon(IconName::Copy)
198
.on_click(move |_, _, cx| {
199
cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
200
}),
201
),
202
),
203
);
204
}
205
206
dialog
207
.title(subject.clone())
208
.w(px(DIALOG_WIDTH))
209
.child(body)
210
.footer(footer)
211
});
212
}
@@ -0,0 +1,212 @@1
use chatsvc::{CalendarEvent, ResponseType, join_info_text};2
use chrono::{Local, Offset};3
use gpui_kit::assets::IconName;4
use gpui_kit::component::Sizable as _;5
use gpui_kit::component::button::{Button, ButtonVariants as _};6
use gpui_kit::component::dialog::{Dialog, DialogFooter};7
use gpui_kit::component::menu::DropdownMenu as _;8
use gpui_kit::component::{WindowExt as _, h_flex, v_flex};9
use gpui_kit::*;10
11
use super::rsvp_menu::rsvp_menu;12
use crate::app_state::AppState;13
use crate::call::week_grid::is_effective_all_day;14
use crate::i18n::tr;15
use crate::theme;16
17
const DIALOG_WIDTH: f32 = 440.;18
const FIELD_GAP: f32 = 12.;19
const LABEL_SIZE: f32 = 12.;20
const COPY_JOIN_INFO: &str = "Copy join info";21
22
fn when_label(event: &CalendarEvent) -> String {23
let offset = Local::now().offset().fix();24
if is_effective_all_day(event, offset) {25
let start = event.start.with_timezone(&offset).date_naive();26
let end = event.end.with_timezone(&offset).date_naive();27
if end > start + chrono::Duration::days(1) {28
return format!(29
"All day · {} – {}",30
start.format("%a, %b %-d"),31
(end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")32
);33
}34
return format!("All day · {}", start.format("%a, %b %-d, %Y"));35
}36
let start = event.start.with_timezone(&offset);37
let end = event.end.with_timezone(&offset);38
if start.date_naive() == end.date_naive() {39
format!(40
"{} · {} – {}",41
start.format("%a, %b %-d, %Y"),42
start.format(app_base::format::clock_format()),43
end.format(app_base::format::clock_format())44
)45
} else {46
format!(47
"{} {} – {} {}",48
start.format("%a, %b %-d"),49
start.format(app_base::format::clock_format()),50
end.format("%a, %b %-d, %Y"),51
end.format(app_base::format::clock_format())52
)53
}54
}55
56
fn source_label(event: &CalendarEvent) -> String {57
let mut sources = event.sources.clone();58
if sources.is_empty() {59
sources.push(event.source);60
}61
sources.sort_by_key(|source| source.label());62
sources.dedup();63
sources64
.iter()65
.map(|source| source.label())66
.collect::<Vec<_>>()67
.join(" + ")68
}69
70
fn detail_row(label: &str, value: impl Into<SharedString>) -> Div {71
v_flex()72
.gap(px(2.))73
.child(74
div()75
.text_size(px(LABEL_SIZE))76
.text_color(theme::text_muted())77
.child(label.to_owned()),78
)79
.child(80
div()81
.text_size(px(14.))82
.text_color(theme::text())83
.child(value.into()),84
)85
}86
87
pub fn open_calendar_event(88
state: Entity<AppState>,89
event: CalendarEvent,90
window: &mut Window,91
cx: &mut App,92
) {93
let send_response = state.read(cx).rsvp_send_response;94
// Show Join whenever a Teams link exists — not only inside the join window.95
let can_join = event.online && !event.cancelled && event.join_url.is_some();96
let subject = if event.cancelled {97
format!("Canceled: {}", event.subject)98
} else if event.subject.is_empty() {99
"(No title)".to_owned()100
} else {101
event.subject.clone()102
};103
let when = when_label(&event);104
let source = source_label(&event);105
let organizer = event106
.organizer_name107
.clone()108
.or_else(|| event.organizer_address.clone());109
let join_url = event.join_url.clone();110
let dial_in = event.dial_in.clone();111
let thread_id = event.thread_id.clone();112
let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();113
let response = event.response;114
let event_key = event.object_id.clone();115
let meeting_title = event.subject.clone();116
let online = event.online;117
118
window.open_dialog(cx, move |dialog: Dialog, _, _| {119
let delete_state = state.clone();120
let delete_key = event_key.clone();121
let mut footer = DialogFooter::new()122
.child(123
Button::new("calendar-event-delete")124
.danger()125
.label(tr("common.delete"))126
.on_click(move |_, window, cx| {127
delete_state128
.update(cx, |state, cx| state.delete_calendar_event(&delete_key, cx));129
window.close_dialog(cx);130
}),131
)132
.child(133
Button::new("calendar-event-close")134
.label(tr("common.close"))135
.on_click(|_, window, cx| window.close_dialog(cx)),136
);137
if can_rsvp {138
let menu_state = state.clone();139
let menu_key = event_key.clone();140
footer = footer.child(141
Button::new("calendar-event-rsvp")142
.label("RSVP")143
.dropdown_menu(move |menu, _, _| {144
rsvp_menu(menu, &menu_state, &menu_key, response, send_response)145
}),146
);147
}148
if thread_id.is_some() {149
let chat_state = state.clone();150
let chat_thread = thread_id.clone();151
footer = footer.child(152
Button::new("calendar-event-chat")153
.label(tr("common.chat"))154
.on_click(move |_, window, cx| {155
chat_state.update(cx, |state, cx| {156
state.open_meeting_chat(chat_thread.as_deref(), cx)157
});158
window.close_dialog(cx);159
}),160
);161
}162
if can_join {163
let join_state = state.clone();164
let url = join_url.clone();165
let title = meeting_title.clone();166
footer = footer.child(167
Button::new("calendar-event-join")168
.primary()169
.label(tr("common.join"))170
.on_click(move |_, window, cx| {171
join_state.update(cx, |state, cx| {172
state.join_calendar_meeting(url.as_deref(), &title, cx)173
});174
window.close_dialog(cx);175
}),176
);177
}178
179
let mut body = v_flex()180
.gap(px(FIELD_GAP))181
.child(detail_row("When", when.clone()))182
.child(detail_row("Calendar", source.clone()));183
if let Some(name) = organizer.clone() {184
body = body.child(detail_row("Organizer", name));185
}186
if let Some(url) = join_url.clone().filter(|_| online) {187
let info = join_info_text(&url, dial_in.as_ref());188
body = body.child(189
v_flex()190
.gap(px(6.))191
.child(detail_row("Join link", url))192
.child(193
h_flex().child(194
Button::new("calendar-event-copy-join")195
.small()196
.label(COPY_JOIN_INFO)197
.icon(IconName::Copy)198
.on_click(move |_, _, cx| {199
cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))200
}),201
),202
),203
);204
}205
206
dialog207
.title(subject.clone())208
.w(px(DIALOG_WIDTH))209
.child(body)210
.footer(footer)211
});212
}@@ -6,7 +6,7 @@ use gpui_kit::prelude::FluentBuilder as _;
6
6
use gpui_kit::*;
7
7
8
8
use crate::app_state::AppState;
9
use crate::call::week_grid::{WeekDay, month_shown};
9
use crate::call::week_grid::{WeekDay, is_effective_all_day, month_shown};
10
10
use crate::theme;
11
11
12
12
pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";
@@ -35,7 +35,8 @@ fn more_label(hidden: usize) -> String {
35
35
}
36
36
37
37
fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
38
let time = (!event.all_day).then(|| {
38
let all_day = is_effective_all_day(event, offset);
39
let time = (!all_day).then(|| {
39
40
event
40
41
.start
41
42
.with_timezone(&offset)
@@ -50,17 +51,28 @@ fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
50
51
.gap(px(6.))
51
52
.items_center()
52
53
.rounded(px(4.))
53
.bg(theme::accent().opacity(if event.all_day { 0.28 } else { 0.14 }))
54
.bg(theme::accent().opacity(if all_day { 0.28 } else { 0.14 }))
54
55
.text_size(px(11.5))
55
56
.text_color(theme::text())
56
57
.children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))
57
.child(
58
div()
59
.flex_1()
60
.min_w_0()
61
.truncate()
62
.child(event.subject.clone()),
63
)
58
.child(div().flex_1().min_w_0().truncate().child({
59
let mut sources = event.sources.clone();
60
if sources.is_empty() {
61
sources.push(event.source);
62
}
63
sources.sort_by_key(|source| source.label());
64
sources.dedup();
65
if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {
66
event.subject.clone()
67
} else {
68
let names = sources
69
.iter()
70
.map(|source| source.label())
71
.collect::<Vec<_>>()
72
.join("+");
73
format!("{} · {names}", event.subject)
74
}
75
}))
64
76
}
65
77
66
78
fn day_cell(
@@ -6,7 +6,7 @@ use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::*;6
use gpui_kit::*;7
7
8
use crate::app_state::AppState;8
use crate::app_state::AppState;9
use crate::call::week_grid::{WeekDay, month_shown};9
use crate::call::week_grid::{WeekDay, is_effective_all_day, month_shown};10
use crate::theme;10
use crate::theme;11
11
12
pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";12
pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";@@ -35,7 +35,8 @@ fn more_label(hidden: usize) -> String {35
}35
}36
36
37
fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {37
fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {38
let time = (!event.all_day).then(|| {38
let all_day = is_effective_all_day(event, offset);39
let time = (!all_day).then(|| {39
event40
event40
.start41
.start41
.with_timezone(&offset)42
.with_timezone(&offset)@@ -50,17 +51,28 @@ fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {50
.gap(px(6.))51
.gap(px(6.))51
.items_center()52
.items_center()52
.rounded(px(4.))53
.rounded(px(4.))53
.bg(theme::accent().opacity(if event.all_day { 0.28 } else { 0.14 }))54
.bg(theme::accent().opacity(if all_day { 0.28 } else { 0.14 }))54
.text_size(px(11.5))55
.text_size(px(11.5))55
.text_color(theme::text())56
.text_color(theme::text())56
.children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))57
.children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))57
.child(58
.child(div().flex_1().min_w_0().truncate().child({58
div()59
let mut sources = event.sources.clone();59
.flex_1()60
if sources.is_empty() {60
.min_w_0()61
sources.push(event.source);61
.truncate()62
}62
.child(event.subject.clone()),63
sources.sort_by_key(|source| source.label());63
)64
sources.dedup();65
if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {66
event.subject.clone()67
} else {68
let names = sources69
.iter()70
.map(|source| source.label())71
.collect::<Vec<_>>()72
.join("+");73
format!("{} · {names}", event.subject)74
}75
}))64
}76
}65
77
66
fn day_cell(78
fn day_cell(@@ -0,0 +1,137 @@
1
use gpui_kit::assets::IconName;
2
use gpui_kit::component::{h_flex, v_flex};
3
use gpui_kit::prelude::FluentBuilder as _;
4
use gpui_kit::*;
5
use store::CalendarAccounts;
6
7
use crate::app_state::AppState;
8
use crate::theme;
9
use crate::views::widgets::icon;
10
11
pub const PICKER_WIDTH: f32 = 220.;
12
const ROW_HEIGHT: f32 = 28.;
13
14
/// Teams-like calendar list: Outlook + each connected Google calendar with show toggles.
15
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
16
let accounts = app.read(cx).calendar_accounts();
17
let mut column = v_flex()
18
.debug_selector(|| "shell/islands/calendar/picker".into())
19
.w(px(PICKER_WIDTH))
20
.flex_none()
21
.h_full()
22
.border_r_1()
23
.border_color(theme::border())
24
.bg(theme::surface())
25
.px(px(12.))
26
.py(px(12.))
27
.gap(px(4.))
28
.child(
29
div()
30
.text_size(px(11.))
31
.font_weight(FontWeight::SEMIBOLD)
32
.text_color(theme::text_muted())
33
.mb(px(6.))
34
.child("CALENDARS"),
35
)
36
.child(outlook_row(app, &accounts));
37
for account in &accounts.google_accounts {
38
column = column.child(
39
div()
40
.mt(px(8.))
41
.mb(px(2.))
42
.text_size(px(11.))
43
.font_weight(FontWeight::SEMIBOLD)
44
.text_color(theme::text_muted())
45
.truncate()
46
.child(account.email.clone()),
47
);
48
for calendar in &account.calendars {
49
let toggle_app = app.clone();
50
let account_id = account.id.clone();
51
let calendar_id = calendar.id.clone();
52
let color = if calendar.primary {
53
theme::accent()
54
} else {
55
theme::text_soft()
56
};
57
column = column.child(toggle_row(
58
format!("calendar-picker-{}", calendar.id),
59
calendar.summary.clone(),
60
calendar.selected,
61
color,
62
move |cx| {
63
toggle_app.update(cx, |state, cx| {
64
state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)
65
});
66
},
67
));
68
}
69
}
70
if !accounts.has_google() {
71
column = column.child(
72
div()
73
.mt(px(8.))
74
.text_size(px(12.))
75
.text_color(theme::text_muted())
76
.child("Connect Google in Settings › Calendar"),
77
);
78
}
79
column
80
}
81
82
fn outlook_row(app: &Entity<AppState>, accounts: &CalendarAccounts) -> Stateful<Div> {
83
let app = app.clone();
84
toggle_row(
85
"calendar-picker-outlook",
86
"Outlook",
87
accounts.outlook_selected,
88
theme::accent(),
89
move |cx| {
90
app.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx));
91
},
92
)
93
}
94
95
fn toggle_row(
96
id: impl Into<ElementId>,
97
label: impl Into<SharedString>,
98
on: bool,
99
swatch: Hsla,
100
on_click: impl Fn(&mut App) + 'static,
101
) -> Stateful<Div> {
102
h_flex()
103
.id(id)
104
.h(px(ROW_HEIGHT))
105
.flex_none()
106
.w_full()
107
.items_center()
108
.gap(px(8.))
109
.rounded(px(6.))
110
.px(px(4.))
111
.cursor_pointer()
112
.hover(|row| row.bg(theme::popup_hover()))
113
.on_click(move |_, _, cx| on_click(cx))
114
.child(
115
div()
116
.size(px(14.))
117
.flex_none()
118
.rounded(px(3.))
119
.bg(if on { swatch } else { theme::border() })
120
.when(on, |box_| {
121
box_.flex().items_center().justify_center().child(icon(
122
IconName::Check,
123
10.,
124
theme::text(),
125
))
126
}),
127
)
128
.child(
129
div()
130
.flex_1()
131
.min_w_0()
132
.truncate()
133
.text_size(px(13.))
134
.text_color(theme::text())
135
.child(label.into()),
136
)
137
}
@@ -0,0 +1,137 @@1
use gpui_kit::assets::IconName;2
use gpui_kit::component::{h_flex, v_flex};3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;5
use store::CalendarAccounts;6
7
use crate::app_state::AppState;8
use crate::theme;9
use crate::views::widgets::icon;10
11
pub const PICKER_WIDTH: f32 = 220.;12
const ROW_HEIGHT: f32 = 28.;13
14
/// Teams-like calendar list: Outlook + each connected Google calendar with show toggles.15
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {16
let accounts = app.read(cx).calendar_accounts();17
let mut column = v_flex()18
.debug_selector(|| "shell/islands/calendar/picker".into())19
.w(px(PICKER_WIDTH))20
.flex_none()21
.h_full()22
.border_r_1()23
.border_color(theme::border())24
.bg(theme::surface())25
.px(px(12.))26
.py(px(12.))27
.gap(px(4.))28
.child(29
div()30
.text_size(px(11.))31
.font_weight(FontWeight::SEMIBOLD)32
.text_color(theme::text_muted())33
.mb(px(6.))34
.child("CALENDARS"),35
)36
.child(outlook_row(app, &accounts));37
for account in &accounts.google_accounts {38
column = column.child(39
div()40
.mt(px(8.))41
.mb(px(2.))42
.text_size(px(11.))43
.font_weight(FontWeight::SEMIBOLD)44
.text_color(theme::text_muted())45
.truncate()46
.child(account.email.clone()),47
);48
for calendar in &account.calendars {49
let toggle_app = app.clone();50
let account_id = account.id.clone();51
let calendar_id = calendar.id.clone();52
let color = if calendar.primary {53
theme::accent()54
} else {55
theme::text_soft()56
};57
column = column.child(toggle_row(58
format!("calendar-picker-{}", calendar.id),59
calendar.summary.clone(),60
calendar.selected,61
color,62
move |cx| {63
toggle_app.update(cx, |state, cx| {64
state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)65
});66
},67
));68
}69
}70
if !accounts.has_google() {71
column = column.child(72
div()73
.mt(px(8.))74
.text_size(px(12.))75
.text_color(theme::text_muted())76
.child("Connect Google in Settings › Calendar"),77
);78
}79
column80
}81
82
fn outlook_row(app: &Entity<AppState>, accounts: &CalendarAccounts) -> Stateful<Div> {83
let app = app.clone();84
toggle_row(85
"calendar-picker-outlook",86
"Outlook",87
accounts.outlook_selected,88
theme::accent(),89
move |cx| {90
app.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx));91
},92
)93
}94
95
fn toggle_row(96
id: impl Into<ElementId>,97
label: impl Into<SharedString>,98
on: bool,99
swatch: Hsla,100
on_click: impl Fn(&mut App) + 'static,101
) -> Stateful<Div> {102
h_flex()103
.id(id)104
.h(px(ROW_HEIGHT))105
.flex_none()106
.w_full()107
.items_center()108
.gap(px(8.))109
.rounded(px(6.))110
.px(px(4.))111
.cursor_pointer()112
.hover(|row| row.bg(theme::popup_hover()))113
.on_click(move |_, _, cx| on_click(cx))114
.child(115
div()116
.size(px(14.))117
.flex_none()118
.rounded(px(3.))119
.bg(if on { swatch } else { theme::border() })120
.when(on, |box_| {121
box_.flex().items_center().justify_center().child(icon(122
IconName::Check,123
10.,124
theme::text(),125
))126
}),127
)128
.child(129
div()130
.flex_1()131
.min_w_0()132
.truncate()133
.text_size(px(13.))134
.text_color(theme::text())135
.child(label.into()),136
)137
}@@ -12,7 +12,9 @@ use gpui_kit::prelude::FluentBuilder as _;
12
12
use gpui_kit::*;
13
13
14
14
use super::calendar_date_picker::date_picker_button;
15
use super::calendar_event_dialog::open_calendar_event;
15
16
use super::calendar_month::month_grid;
17
use super::calendar_picker;
16
18
use super::join_dialog::open_join_with_id;
17
19
use super::meeting_proposal_card::meeting_proposal_cards;
18
20
use super::new_meeting_dialog::open_new_meeting;
@@ -23,10 +25,10 @@ use crate::call::calendar_now::{
23
25
DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
24
26
now_scroll_offset_y, offset_differs, shows_hour_grid,
25
27
};
26
use crate::call::join_available;
27
28
use crate::call::week_grid::{
28
29
CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
29
30
};
31
use crate::i18n::tr;
30
32
use crate::theme;
31
33
32
34
const HOUR_HEIGHT: f32 = 120.;
@@ -352,7 +354,12 @@ impl CalendarView {
352
354
}))
353
355
}
354
356
355
fn all_day_row(&self, days: &[WeekDay], events: &[CalendarEvent]) -> Option<Div> {
357
fn all_day_row(
358
&self,
359
days: &[WeekDay],
360
events: &[CalendarEvent],
361
send_response: bool,
362
) -> Option<Div> {
356
363
if days.iter().all(|day| day.all_day.is_empty()) {
357
364
return None;
358
365
}
@@ -371,16 +378,36 @@ impl CalendarView {
371
378
.border_l_1()
372
379
.border_color(theme::border())
373
380
.children(day.all_day.iter().map(|&index| {
381
let event = events[index].clone();
382
let open_state = self.state.clone();
383
let (menu_state, menu_event) = (self.state.clone(), event.clone());
384
// Day-qualified id: multi-day all-day chips share object_id.
374
385
div()
386
.id(SharedString::from(format!(
387
"calendar-all-day-{}-{}",
388
event.object_id, day.date
389
)))
375
390
.h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))
376
391
.px(px(6.))
377
392
.flex()
378
393
.items_center()
379
394
.rounded(px(4.))
380
.bg(event_fill(event_look(&events[index])))
395
.bg(event_fill(event_look(&event)))
381
396
.text_size(px(12.))
382
397
.truncate()
383
.child(event_title(&events[index]))
398
.cursor_pointer()
399
.child(event_title(&event))
400
.on_click(move |_, window, cx| {
401
open_calendar_event(
402
open_state.clone(),
403
event.clone(),
404
window,
405
cx,
406
);
407
})
408
.context_menu(move |menu, _, _| {
409
event_menu(menu, &menu_state, &menu_event, send_response)
410
})
384
411
}))
385
412
})),
386
413
)
@@ -390,7 +417,7 @@ impl CalendarView {
390
417
&self,
391
418
block: &WeekBlock,
392
419
event: &CalendarEvent,
393
now: DateTime<Utc>,
420
day: NaiveDate,
394
421
send_response: bool,
395
422
) -> impl IntoElement {
396
423
let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;
@@ -401,11 +428,10 @@ impl CalendarView {
401
428
let compact = height < 36.;
402
429
let small = height < SMALL_TITLE_HEIGHT;
403
430
let look = event_look(event);
404
let can_join = event.online
405
&& !event.cancelled
406
&& event.join_url.is_some()
407
&& join_available(event.start, event.end, now);
408
let (open_state, thread_id) = (self.state.clone(), event.thread_id.clone());
431
// Join on the block whenever a Teams link exists (same as detail dialog).
432
let can_join = event.online && !event.cancelled && event.join_url.is_some();
433
let open_state = self.state.clone();
434
let open_event = event.clone();
409
435
let (menu_state, menu_event) = (self.state.clone(), event.clone());
410
436
let (join_state, join_url, subject) = (
411
437
self.state.clone(),
@@ -416,10 +442,11 @@ impl CalendarView {
416
442
EventLook::Busy => (theme::text(), theme::text_soft()),
417
443
EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),
418
444
};
445
// Day-qualified id: overnight / multi-day spans reuse object_id per column.
419
446
div()
420
447
.id(SharedString::from(format!(
421
"calendar-event-{}",
422
event.object_id
448
"calendar-event-{}-{}",
449
event.object_id, day
423
450
)))
424
451
.absolute()
425
452
.top(px(top))
@@ -471,12 +498,12 @@ impl CalendarView {
471
498
block.child(
472
499
div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(
473
500
Button::new(SharedString::from(format!(
474
"calendar-join-{}",
475
event.object_id
501
"calendar-join-{}-{}",
502
event.object_id, day
476
503
)))
477
504
.xsmall()
478
505
.primary()
479
.label("Join")
506
.label(tr("common.join"))
480
507
.on_click(move |_, _, cx| {
481
508
cx.stop_propagation();
482
509
join_state.update(cx, |state, cx| {
@@ -491,10 +518,8 @@ impl CalendarView {
491
518
)
492
519
}),
493
520
)
494
.on_click(move |_, _, cx| {
495
open_state.update(cx, |state, cx| {
496
state.open_meeting_chat(thread_id.as_deref(), cx)
497
});
521
.on_click(move |_, window, cx| {
522
open_calendar_event(open_state.clone(), open_event.clone(), window, cx);
498
523
})
499
524
.context_menu(move |menu, _, _| {
500
525
event_menu(menu, &menu_state, &menu_event, send_response)
@@ -571,7 +596,7 @@ impl CalendarView {
571
596
self.event_block(
572
597
block,
573
598
&events[block.event_index],
574
now,
599
day.date,
575
600
send_response,
576
601
)
577
602
}))
@@ -680,11 +705,34 @@ fn status_bar(look: EventLook) -> Option<Div> {
680
705
}
681
706
682
707
fn event_title(event: &CalendarEvent) -> String {
683
if event.cancelled {
708
let subject = if event.cancelled {
684
709
format!("{CANCELED_PREFIX}{}", event.subject)
685
710
} else {
686
711
event.subject.clone()
712
};
713
let label = source_label(event);
714
if label.is_empty() {
715
subject
716
} else {
717
format!("{subject} · {label}")
718
}
719
}
720
721
fn source_label(event: &CalendarEvent) -> String {
722
let mut sources = event.sources.clone();
723
if sources.is_empty() {
724
sources.push(event.source);
725
}
726
sources.sort_by_key(|source| source.label());
727
sources.dedup();
728
if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {
729
return String::new();
687
730
}
731
sources
732
.iter()
733
.map(|source| source.label())
734
.collect::<Vec<_>>()
735
.join("+")
688
736
}
689
737
690
738
impl Render for CalendarView {
@@ -700,7 +748,8 @@ impl Render for CalendarView {
700
748
let days = week_days(&events, start, span.days(), offset);
701
749
let today = Local::now().date_naive();
702
750
let now = Utc::now();
703
v_flex()
751
let show_picker = !compact;
752
h_flex()
704
753
.debug_selector(|| "shell/islands/calendar".into())
705
754
.flex_1()
706
755
.w_full()
@@ -709,24 +758,33 @@ impl Render for CalendarView {
709
758
.rounded(px(10.))
710
759
.bg(theme::surface())
711
760
.overflow_hidden()
712
.child(self.header(start, span, compact))
713
.children(meeting_proposal_cards(cx))
714
.map(|calendar| {
715
if span == CalendarSpan::Month {
716
calendar.child(month_grid(
717
&self.state,
718
start,
719
&days,
720
&events,
721
today,
722
offset,
723
))
724
} else {
725
calendar
726
.child(self.day_headers(&days, today))
727
.children(self.all_day_row(&days, &events))
728
.child(self.grid(&days, &events, today, now, send_response, cx))
729
}
761
.when(show_picker, |row| {
762
row.child(calendar_picker::render(&self.state, cx))
730
763
})
764
.child(
765
v_flex()
766
.flex_1()
767
.min_w_0()
768
.h_full()
769
.child(self.header(start, span, compact))
770
.children(meeting_proposal_cards(cx))
771
.map(|calendar| {
772
if span == CalendarSpan::Month {
773
calendar.child(month_grid(
774
&self.state,
775
start,
776
&days,
777
&events,
778
today,
779
offset,
780
))
781
} else {
782
calendar
783
.child(self.day_headers(&days, today))
784
.children(self.all_day_row(&days, &events, send_response))
785
.child(self.grid(&days, &events, today, now, send_response, cx))
786
}
787
}),
788
)
731
789
}
732
790
}
@@ -12,7 +12,9 @@ use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::*;12
use gpui_kit::*;13
13
14
use super::calendar_date_picker::date_picker_button;14
use super::calendar_date_picker::date_picker_button;15
use super::calendar_event_dialog::open_calendar_event;15
use super::calendar_month::month_grid;16
use super::calendar_month::month_grid;17
use super::calendar_picker;16
use super::join_dialog::open_join_with_id;18
use super::join_dialog::open_join_with_id;17
use super::meeting_proposal_card::meeting_proposal_cards;19
use super::meeting_proposal_card::meeting_proposal_cards;18
use super::new_meeting_dialog::open_new_meeting;20
use super::new_meeting_dialog::open_new_meeting;@@ -23,10 +25,10 @@ use crate::call::calendar_now::{23
DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,25
DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,24
now_scroll_offset_y, offset_differs, shows_hour_grid,26
now_scroll_offset_y, offset_differs, shows_hour_grid,25
};27
};26
use crate::call::join_available;27
use crate::call::week_grid::{28
use crate::call::week_grid::{28
CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,29
CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,29
};30
};31
use crate::i18n::tr;30
use crate::theme;32
use crate::theme;31
33
32
const HOUR_HEIGHT: f32 = 120.;34
const HOUR_HEIGHT: f32 = 120.;@@ -352,7 +354,12 @@ impl CalendarView {352
}))354
}))353
}355
}354
356
355
fn all_day_row(&self, days: &[WeekDay], events: &[CalendarEvent]) -> Option<Div> {357
fn all_day_row(358
&self,359
days: &[WeekDay],360
events: &[CalendarEvent],361
send_response: bool,362
) -> Option<Div> {356
if days.iter().all(|day| day.all_day.is_empty()) {363
if days.iter().all(|day| day.all_day.is_empty()) {357
return None;364
return None;358
}365
}@@ -371,16 +378,36 @@ impl CalendarView {371
.border_l_1()378
.border_l_1()372
.border_color(theme::border())379
.border_color(theme::border())373
.children(day.all_day.iter().map(|&index| {380
.children(day.all_day.iter().map(|&index| {381
let event = events[index].clone();382
let open_state = self.state.clone();383
let (menu_state, menu_event) = (self.state.clone(), event.clone());384
// Day-qualified id: multi-day all-day chips share object_id.374
div()385
div()386
.id(SharedString::from(format!(387
"calendar-all-day-{}-{}",388
event.object_id, day.date389
)))375
.h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))390
.h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))376
.px(px(6.))391
.px(px(6.))377
.flex()392
.flex()378
.items_center()393
.items_center()379
.rounded(px(4.))394
.rounded(px(4.))380
.bg(event_fill(event_look(&events[index])))395
.bg(event_fill(event_look(&event)))381
.text_size(px(12.))396
.text_size(px(12.))382
.truncate()397
.truncate()383
.child(event_title(&events[index]))398
.cursor_pointer()399
.child(event_title(&event))400
.on_click(move |_, window, cx| {401
open_calendar_event(402
open_state.clone(),403
event.clone(),404
window,405
cx,406
);407
})408
.context_menu(move |menu, _, _| {409
event_menu(menu, &menu_state, &menu_event, send_response)410
})384
}))411
}))385
})),412
})),386
)413
)@@ -390,7 +417,7 @@ impl CalendarView {390
&self,417
&self,391
block: &WeekBlock,418
block: &WeekBlock,392
event: &CalendarEvent,419
event: &CalendarEvent,393
now: DateTime<Utc>,420
day: NaiveDate,394
send_response: bool,421
send_response: bool,395
) -> impl IntoElement {422
) -> impl IntoElement {396
let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;423
let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;@@ -401,11 +428,10 @@ impl CalendarView {401
let compact = height < 36.;428
let compact = height < 36.;402
let small = height < SMALL_TITLE_HEIGHT;429
let small = height < SMALL_TITLE_HEIGHT;403
let look = event_look(event);430
let look = event_look(event);404
let can_join = event.online431
// Join on the block whenever a Teams link exists (same as detail dialog).405
&& !event.cancelled432
let can_join = event.online && !event.cancelled && event.join_url.is_some();406
&& event.join_url.is_some()433
let open_state = self.state.clone();407
&& join_available(event.start, event.end, now);434
let open_event = event.clone();408
let (open_state, thread_id) = (self.state.clone(), event.thread_id.clone());409
let (menu_state, menu_event) = (self.state.clone(), event.clone());435
let (menu_state, menu_event) = (self.state.clone(), event.clone());410
let (join_state, join_url, subject) = (436
let (join_state, join_url, subject) = (411
self.state.clone(),437
self.state.clone(),@@ -416,10 +442,11 @@ impl CalendarView {416
EventLook::Busy => (theme::text(), theme::text_soft()),442
EventLook::Busy => (theme::text(), theme::text_soft()),417
EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),443
EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),418
};444
};445
// Day-qualified id: overnight / multi-day spans reuse object_id per column.419
div()446
div()420
.id(SharedString::from(format!(447
.id(SharedString::from(format!(421
"calendar-event-{}",448
"calendar-event-{}-{}",422
event.object_id449
event.object_id, day423
)))450
)))424
.absolute()451
.absolute()425
.top(px(top))452
.top(px(top))@@ -471,12 +498,12 @@ impl CalendarView {471
block.child(498
block.child(472
div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(499
div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(473
Button::new(SharedString::from(format!(500
Button::new(SharedString::from(format!(474
"calendar-join-{}",501
"calendar-join-{}-{}",475
event.object_id502
event.object_id, day476
)))503
)))477
.xsmall()504
.xsmall()478
.primary()505
.primary()479
.label("Join")506
.label(tr("common.join"))480
.on_click(move |_, _, cx| {507
.on_click(move |_, _, cx| {481
cx.stop_propagation();508
cx.stop_propagation();482
join_state.update(cx, |state, cx| {509
join_state.update(cx, |state, cx| {@@ -491,10 +518,8 @@ impl CalendarView {491
)518
)492
}),519
}),493
)520
)494
.on_click(move |_, _, cx| {521
.on_click(move |_, window, cx| {495
open_state.update(cx, |state, cx| {522
open_calendar_event(open_state.clone(), open_event.clone(), window, cx);496
state.open_meeting_chat(thread_id.as_deref(), cx)497
});498
})523
})499
.context_menu(move |menu, _, _| {524
.context_menu(move |menu, _, _| {500
event_menu(menu, &menu_state, &menu_event, send_response)525
event_menu(menu, &menu_state, &menu_event, send_response)@@ -571,7 +596,7 @@ impl CalendarView {571
self.event_block(596
self.event_block(572
block,597
block,573
&events[block.event_index],598
&events[block.event_index],574
now,599
day.date,575
send_response,600
send_response,576
)601
)577
}))602
}))@@ -680,11 +705,34 @@ fn status_bar(look: EventLook) -> Option<Div> {680
}705
}681
706
682
fn event_title(event: &CalendarEvent) -> String {707
fn event_title(event: &CalendarEvent) -> String {683
if event.cancelled {708
let subject = if event.cancelled {684
format!("{CANCELED_PREFIX}{}", event.subject)709
format!("{CANCELED_PREFIX}{}", event.subject)685
} else {710
} else {686
event.subject.clone()711
event.subject.clone()712
};713
let label = source_label(event);714
if label.is_empty() {715
subject716
} else {717
format!("{subject} · {label}")718
}719
}720
721
fn source_label(event: &CalendarEvent) -> String {722
let mut sources = event.sources.clone();723
if sources.is_empty() {724
sources.push(event.source);725
}726
sources.sort_by_key(|source| source.label());727
sources.dedup();728
if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {729
return String::new();687
}730
}731
sources732
.iter()733
.map(|source| source.label())734
.collect::<Vec<_>>()735
.join("+")688
}736
}689
737
690
impl Render for CalendarView {738
impl Render for CalendarView {@@ -700,7 +748,8 @@ impl Render for CalendarView {700
let days = week_days(&events, start, span.days(), offset);748
let days = week_days(&events, start, span.days(), offset);701
let today = Local::now().date_naive();749
let today = Local::now().date_naive();702
let now = Utc::now();750
let now = Utc::now();703
v_flex()751
let show_picker = !compact;752
h_flex()704
.debug_selector(|| "shell/islands/calendar".into())753
.debug_selector(|| "shell/islands/calendar".into())705
.flex_1()754
.flex_1()706
.w_full()755
.w_full()@@ -709,24 +758,33 @@ impl Render for CalendarView {709
.rounded(px(10.))758
.rounded(px(10.))710
.bg(theme::surface())759
.bg(theme::surface())711
.overflow_hidden()760
.overflow_hidden()712
.child(self.header(start, span, compact))761
.when(show_picker, |row| {713
.children(meeting_proposal_cards(cx))762
row.child(calendar_picker::render(&self.state, cx))714
.map(|calendar| {715
if span == CalendarSpan::Month {716
calendar.child(month_grid(717
&self.state,718
start,719
&days,720
&events,721
today,722
offset,723
))724
} else {725
calendar726
.child(self.day_headers(&days, today))727
.children(self.all_day_row(&days, &events))728
.child(self.grid(&days, &events, today, now, send_response, cx))729
}730
})763
})764
.child(765
v_flex()766
.flex_1()767
.min_w_0()768
.h_full()769
.child(self.header(start, span, compact))770
.children(meeting_proposal_cards(cx))771
.map(|calendar| {772
if span == CalendarSpan::Month {773
calendar.child(month_grid(774
&self.state,775
start,776
&days,777
&events,778
today,779
offset,780
))781
} else {782
calendar783
.child(self.day_headers(&days, today))784
.children(self.all_day_row(&days, &events, send_response))785
.child(self.grid(&days, &events, today, now, send_response, cx))786
}787
}),788
)731
}789
}732
}790
}@@ -7,7 +7,9 @@ pub mod attachment_tray;
7
7
pub mod attachments;
8
8
pub mod avatar;
9
9
pub mod calendar_date_picker;
10
pub mod calendar_event_dialog;
10
11
pub mod calendar_month;
12
pub mod calendar_picker;
11
13
pub mod calendar_view;
12
14
pub mod call_card;
13
15
pub mod call_control_fold;
@@ -7,7 +7,9 @@ pub mod attachment_tray;7
pub mod attachments;7
pub mod attachments;8
pub mod avatar;8
pub mod avatar;9
pub mod calendar_date_picker;9
pub mod calendar_date_picker;10
pub mod calendar_event_dialog;10
pub mod calendar_month;11
pub mod calendar_month;12
pub mod calendar_picker;11
pub mod calendar_view;13
pub mod calendar_view;12
pub mod call_card;14
pub mod call_card;13
pub mod call_control_fold;15
pub mod call_control_fold;@@ -10,14 +10,17 @@ base64.workspace = true
10
10
chrono.workspace = true
11
11
futures-util.workspace = true
12
12
percent-encoding.workspace = true
13
rand = "0.9"
14
reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }
13
15
serde.workspace = true
14
16
serde_json.workspace = true
15
17
session.workspace = true
18
sha2 = "0.10"
16
19
thiserror.workspace = true
17
20
tokio.workspace = true
18
21
tokio-tungstenite = { workspace = true, features = ["rustls-tls-native-roots"] }
22
url.workspace = true
19
23
uuid.workspace = true
20
24
21
25
[dev-dependencies]
22
26
tokio = { workspace = true }
23
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
@@ -10,14 +10,17 @@ base64.workspace = true10
chrono.workspace = true10
chrono.workspace = true11
futures-util.workspace = true11
futures-util.workspace = true12
percent-encoding.workspace = true12
percent-encoding.workspace = true13
rand = "0.9"14
reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }13
serde.workspace = true15
serde.workspace = true14
serde_json.workspace = true16
serde_json.workspace = true15
session.workspace = true17
session.workspace = true18
sha2 = "0.10"16
thiserror.workspace = true19
thiserror.workspace = true17
tokio.workspace = true20
tokio.workspace = true18
tokio-tungstenite = { workspace = true, features = ["rustls-tls-native-roots"] }21
tokio-tungstenite = { workspace = true, features = ["rustls-tls-native-roots"] }22
url.workspace = true19
uuid.workspace = true23
uuid.workspace = true20
24
21
[dev-dependencies]25
[dev-dependencies]22
tokio = { workspace = true }26
tokio = { workspace = true }23
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }@@ -13,7 +13,8 @@ pub use availability::{BusyTime, PersonSchedule, parse_schedules};
13
13
14
14
pub use reminders::{Reminder, parse_reminders};
15
15
pub use schedule::{
16
Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, parse_created_event,
16
Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, new_event_body_with_join,
17
parse_created_event,
17
18
};
18
19
19
20
const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";
@@ -39,6 +40,22 @@ pub enum ShowAs {
39
40
WorkingElsewhere,
40
41
}
41
42
43
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44
pub enum CalendarSource {
45
#[default]
46
Outlook,
47
Google,
48
}
49
50
impl CalendarSource {
51
pub fn label(self) -> &'static str {
52
match self {
53
CalendarSource::Outlook => "Outlook",
54
CalendarSource::Google => "Google",
55
}
56
}
57
}
58
42
59
#[derive(Debug, Clone, PartialEq, Eq)]
43
60
pub struct CalendarEvent {
44
61
pub object_id: String,
@@ -56,6 +73,54 @@ pub struct CalendarEvent {
56
73
pub response: ResponseType,
57
74
pub show_as: ShowAs,
58
75
pub dial_in: Option<DialIn>,
76
pub source: CalendarSource,
77
pub account_id: Option<String>,
78
pub calendar_id: Option<String>,
79
/// When a merge collapsed duplicates, every contributing source.
80
pub sources: Vec<CalendarSource>,
81
}
82
83
impl CalendarEvent {
84
pub fn outlook_defaults() -> (
85
CalendarSource,
86
Option<String>,
87
Option<String>,
88
Vec<CalendarSource>,
89
) {
90
(
91
CalendarSource::Outlook,
92
None,
93
None,
94
vec![CalendarSource::Outlook],
95
)
96
}
97
}
98
99
impl Default for CalendarEvent {
100
fn default() -> Self {
101
let (source, account_id, calendar_id, sources) = Self::outlook_defaults();
102
CalendarEvent {
103
object_id: String::new(),
104
subject: String::new(),
105
start: DateTime::<Utc>::UNIX_EPOCH,
106
end: DateTime::<Utc>::UNIX_EPOCH,
107
all_day: false,
108
cancelled: false,
109
online: false,
110
join_url: None,
111
thread_id: None,
112
organizer_name: None,
113
organizer_address: None,
114
ical_uid: None,
115
response: ResponseType::default(),
116
show_as: ShowAs::default(),
117
dial_in: None,
118
source,
119
account_id,
120
calendar_id,
121
sources,
122
}
123
}
59
124
}
60
125
61
126
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -259,6 +324,7 @@ fn show_as(entry: &Value) -> ShowAs {
259
324
260
325
fn parse_event(entry: &Value) -> Option<CalendarEvent> {
261
326
let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));
327
let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();
262
328
Some(CalendarEvent {
263
329
object_id: text(entry, "objectId").or_else(|| text(entry, "id"))?,
264
330
subject: text(entry, "subject").unwrap_or_default(),
@@ -275,6 +341,10 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {
275
341
response: response_type(entry),
276
342
show_as: show_as(entry),
277
343
dial_in: dial_in(entry),
344
source,
345
account_id,
346
calendar_id,
347
sources,
278
348
})
279
349
}
280
350
@@ -13,7 +13,8 @@ pub use availability::{BusyTime, PersonSchedule, parse_schedules};13
13
14
pub use reminders::{Reminder, parse_reminders};14
pub use reminders::{Reminder, parse_reminders};15
pub use schedule::{15
pub use schedule::{16
Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, parse_created_event,16
Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, new_event_body_with_join,17
parse_created_event,17
};18
};18
19
19
const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";20
const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";@@ -39,6 +40,22 @@ pub enum ShowAs {39
WorkingElsewhere,40
WorkingElsewhere,40
}41
}41
42
43
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]44
pub enum CalendarSource {45
#[default]46
Outlook,47
Google,48
}49
50
impl CalendarSource {51
pub fn label(self) -> &'static str {52
match self {53
CalendarSource::Outlook => "Outlook",54
CalendarSource::Google => "Google",55
}56
}57
}58
42
#[derive(Debug, Clone, PartialEq, Eq)]59
#[derive(Debug, Clone, PartialEq, Eq)]43
pub struct CalendarEvent {60
pub struct CalendarEvent {44
pub object_id: String,61
pub object_id: String,@@ -56,6 +73,54 @@ pub struct CalendarEvent {56
pub response: ResponseType,73
pub response: ResponseType,57
pub show_as: ShowAs,74
pub show_as: ShowAs,58
pub dial_in: Option<DialIn>,75
pub dial_in: Option<DialIn>,76
pub source: CalendarSource,77
pub account_id: Option<String>,78
pub calendar_id: Option<String>,79
/// When a merge collapsed duplicates, every contributing source.80
pub sources: Vec<CalendarSource>,81
}82
83
impl CalendarEvent {84
pub fn outlook_defaults() -> (85
CalendarSource,86
Option<String>,87
Option<String>,88
Vec<CalendarSource>,89
) {90
(91
CalendarSource::Outlook,92
None,93
None,94
vec![CalendarSource::Outlook],95
)96
}97
}98
99
impl Default for CalendarEvent {100
fn default() -> Self {101
let (source, account_id, calendar_id, sources) = Self::outlook_defaults();102
CalendarEvent {103
object_id: String::new(),104
subject: String::new(),105
start: DateTime::<Utc>::UNIX_EPOCH,106
end: DateTime::<Utc>::UNIX_EPOCH,107
all_day: false,108
cancelled: false,109
online: false,110
join_url: None,111
thread_id: None,112
organizer_name: None,113
organizer_address: None,114
ical_uid: None,115
response: ResponseType::default(),116
show_as: ShowAs::default(),117
dial_in: None,118
source,119
account_id,120
calendar_id,121
sources,122
}123
}59
}124
}60
125
61
#[derive(Debug, Clone, PartialEq, Eq)]126
#[derive(Debug, Clone, PartialEq, Eq)]@@ -259,6 +324,7 @@ fn show_as(entry: &Value) -> ShowAs {259
324
260
fn parse_event(entry: &Value) -> Option<CalendarEvent> {325
fn parse_event(entry: &Value) -> Option<CalendarEvent> {261
let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));326
let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));327
let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();262
Some(CalendarEvent {328
Some(CalendarEvent {263
object_id: text(entry, "objectId").or_else(|| text(entry, "id"))?,329
object_id: text(entry, "objectId").or_else(|| text(entry, "id"))?,264
subject: text(entry, "subject").unwrap_or_default(),330
subject: text(entry, "subject").unwrap_or_default(),@@ -275,6 +341,10 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {275
response: response_type(entry),341
response: response_type(entry),276
show_as: show_as(entry),342
show_as: show_as(entry),277
dial_in: dial_in(entry),343
dial_in: dial_in(entry),344
source,345
account_id,346
calendar_id,347
sources,278
})348
})279
}349
}280
350
@@ -157,6 +157,31 @@ pub fn new_event_body(event: &NewEvent) -> Value {
157
157
body
158
158
}
159
159
160
/// Outlook insert when the Teams join URL already exists (multi-target create).
161
pub fn new_event_body_with_join(event: &NewEvent, join_url: &str) -> Value {
162
let mut details = event.details.clone();
163
if !details.is_empty() {
164
details.push_str("\n\n");
165
}
166
details.push_str(join_url);
167
let mut body = json!({
168
"subject": event.subject,
169
"start": graph_time(event, event.local_start, event.start),
170
"end": graph_time(event, event.local_end, event.end),
171
"attendees": event.attendees.iter().map(|attendee| json!({
172
"type": "required",
173
"emailAddress": {"address": attendee.address, "name": attendee.name},
174
})).collect::<Vec<_>>(),
175
"location": {"displayName": join_url},
176
"body": {"contentType": "text", "content": details},
177
"isOnlineMeeting": false,
178
});
179
if let Some(recurrence) = recurrence(event.repeat, event.local_start) {
180
body["recurrence"] = recurrence;
181
}
182
body
183
}
184
160
185
pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> {
161
186
Some(CreatedEvent {
162
187
id: body.get("id")?.as_str()?.to_owned(),
@@ -171,8 +196,12 @@ fn events_url() -> String {
171
196
format!("{GRAPH}/v1.0/me/events")
172
197
}
173
198
199
fn event_item_url(event_id: &str) -> String {
200
format!("{}/{}", events_url(), encode(event_id))
201
}
202
174
203
fn reply_url(event_id: &str, reply: Reply) -> String {
175
format!("{}/{}/{}", events_url(), encode(event_id), reply.action())
204
format!("{}/{}", event_item_url(event_id), reply.action())
176
205
}
177
206
178
207
fn lookup_url(ical_uid: &str) -> String {
@@ -189,8 +218,27 @@ fn api_error(answer: session::ApiResponse, url: &str) -> Error {
189
218
190
219
impl<T: CardTransport> Calendar<T> {
191
220
pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {
221
self.create_event_body(event, new_event_body(event)).await
222
}
223
224
pub async fn create_event_with_join(
225
&self,
226
event: &NewEvent,
227
join_url: &str,
228
) -> Result<CreatedEvent> {
229
let mut created = self
230
.create_event_body(event, new_event_body_with_join(event, join_url))
231
.await?;
232
if created.join_url.is_none() {
233
created.join_url = Some(join_url.to_owned());
234
}
235
Ok(created)
236
}
237
238
async fn create_event_body(&self, event: &NewEvent, body: Value) -> Result<CreatedEvent> {
239
let _ = event;
192
240
let url = events_url();
193
let request = Request::with_body(Method::Post, &url, new_event_body(event));
241
let request = Request::with_body(Method::Post, &url, body);
194
242
let answer = self
195
243
.transport
196
244
.send(request, Scope::graph(CALENDARS_SCOPE))
@@ -223,6 +271,31 @@ impl<T: CardTransport> Calendar<T> {
223
271
Err(api_error(retried, &reply_url(&graph_id, reply)))
224
272
}
225
273
274
pub async fn delete_event(&self, event_id: &str, ical_uid: Option<&str>) -> Result<()> {
275
let answer = self.send_delete(event_id).await?;
276
if answer.is_success() {
277
return Ok(());
278
}
279
let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else {
280
return Err(api_error(answer, &event_item_url(event_id)));
281
};
282
let graph_id = self.graph_event_id(ical_uid).await?;
283
let retried = self.send_delete(&graph_id).await?;
284
if retried.is_success() {
285
return Ok(());
286
}
287
Err(api_error(retried, &event_item_url(&graph_id)))
288
}
289
290
async fn send_delete(&self, event_id: &str) -> Result<session::ApiResponse> {
291
self.transport
292
.send(
293
Request::delete(event_item_url(event_id)),
294
Scope::graph(CALENDARS_SCOPE),
295
)
296
.await
297
}
298
226
299
async fn send_reply(
227
300
&self,
228
301
event_id: &str,
@@ -332,6 +405,25 @@ mod tests {
332
405
}
333
406
}
334
407
408
#[test]
409
fn join_first_body_puts_link_in_location_without_online_meeting() {
410
let body = new_event_body_with_join(
411
&event(Repeat::Never),
412
"https://teams.microsoft.com/l/meetup-join/x",
413
);
414
assert_eq!(body["isOnlineMeeting"], false);
415
assert_eq!(
416
body["location"]["displayName"],
417
"https://teams.microsoft.com/l/meetup-join/x"
418
);
419
assert!(
420
body["body"]["content"]
421
.as_str()
422
.unwrap()
423
.contains("teams.microsoft.com")
424
);
425
}
426
335
427
#[test]
336
428
fn the_body_asks_for_a_teams_meeting_with_utc_times() {
337
429
let body = new_event_body(&event(Repeat::Never));
@@ -479,6 +571,18 @@ mod tests {
479
571
);
480
572
}
481
573
574
#[tokio::test]
575
async fn delete_event_sends_graph_delete() {
576
let calendar = Calendar::with_transport(Scripted::new(vec![(204, Value::Null)]), "emea");
577
calendar.delete_event("AAMk=", None).await.unwrap();
578
let sent = calendar.transport.sent.lock().unwrap();
579
assert_eq!(sent[0].0, Method::Delete);
580
assert_eq!(
581
sent[0].1,
582
"https://graph.microsoft.com/v1.0/me/events/AAMk%3D"
583
);
584
}
585
482
586
#[tokio::test]
483
587
async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() {
484
588
let calendar = Calendar::with_transport(
@@ -157,6 +157,31 @@ pub fn new_event_body(event: &NewEvent) -> Value {157
body157
body158
}158
}159
159
160
/// Outlook insert when the Teams join URL already exists (multi-target create).161
pub fn new_event_body_with_join(event: &NewEvent, join_url: &str) -> Value {162
let mut details = event.details.clone();163
if !details.is_empty() {164
details.push_str("\n\n");165
}166
details.push_str(join_url);167
let mut body = json!({168
"subject": event.subject,169
"start": graph_time(event, event.local_start, event.start),170
"end": graph_time(event, event.local_end, event.end),171
"attendees": event.attendees.iter().map(|attendee| json!({172
"type": "required",173
"emailAddress": {"address": attendee.address, "name": attendee.name},174
})).collect::<Vec<_>>(),175
"location": {"displayName": join_url},176
"body": {"contentType": "text", "content": details},177
"isOnlineMeeting": false,178
});179
if let Some(recurrence) = recurrence(event.repeat, event.local_start) {180
body["recurrence"] = recurrence;181
}182
body183
}184
160
pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> {185
pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> {161
Some(CreatedEvent {186
Some(CreatedEvent {162
id: body.get("id")?.as_str()?.to_owned(),187
id: body.get("id")?.as_str()?.to_owned(),@@ -171,8 +196,12 @@ fn events_url() -> String {171
format!("{GRAPH}/v1.0/me/events")196
format!("{GRAPH}/v1.0/me/events")172
}197
}173
198
199
fn event_item_url(event_id: &str) -> String {200
format!("{}/{}", events_url(), encode(event_id))201
}202
174
fn reply_url(event_id: &str, reply: Reply) -> String {203
fn reply_url(event_id: &str, reply: Reply) -> String {175
format!("{}/{}/{}", events_url(), encode(event_id), reply.action())204
format!("{}/{}", event_item_url(event_id), reply.action())176
}205
}177
206
178
fn lookup_url(ical_uid: &str) -> String {207
fn lookup_url(ical_uid: &str) -> String {@@ -189,8 +218,27 @@ fn api_error(answer: session::ApiResponse, url: &str) -> Error {189
218
190
impl<T: CardTransport> Calendar<T> {219
impl<T: CardTransport> Calendar<T> {191
pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {220
pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {221
self.create_event_body(event, new_event_body(event)).await222
}223
224
pub async fn create_event_with_join(225
&self,226
event: &NewEvent,227
join_url: &str,228
) -> Result<CreatedEvent> {229
let mut created = self230
.create_event_body(event, new_event_body_with_join(event, join_url))231
.await?;232
if created.join_url.is_none() {233
created.join_url = Some(join_url.to_owned());234
}235
Ok(created)236
}237
238
async fn create_event_body(&self, event: &NewEvent, body: Value) -> Result<CreatedEvent> {239
let _ = event;192
let url = events_url();240
let url = events_url();193
let request = Request::with_body(Method::Post, &url, new_event_body(event));241
let request = Request::with_body(Method::Post, &url, body);194
let answer = self242
let answer = self195
.transport243
.transport196
.send(request, Scope::graph(CALENDARS_SCOPE))244
.send(request, Scope::graph(CALENDARS_SCOPE))@@ -223,6 +271,31 @@ impl<T: CardTransport> Calendar<T> {223
Err(api_error(retried, &reply_url(&graph_id, reply)))271
Err(api_error(retried, &reply_url(&graph_id, reply)))224
}272
}225
273
274
pub async fn delete_event(&self, event_id: &str, ical_uid: Option<&str>) -> Result<()> {275
let answer = self.send_delete(event_id).await?;276
if answer.is_success() {277
return Ok(());278
}279
let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else {280
return Err(api_error(answer, &event_item_url(event_id)));281
};282
let graph_id = self.graph_event_id(ical_uid).await?;283
let retried = self.send_delete(&graph_id).await?;284
if retried.is_success() {285
return Ok(());286
}287
Err(api_error(retried, &event_item_url(&graph_id)))288
}289
290
async fn send_delete(&self, event_id: &str) -> Result<session::ApiResponse> {291
self.transport292
.send(293
Request::delete(event_item_url(event_id)),294
Scope::graph(CALENDARS_SCOPE),295
)296
.await297
}298
226
async fn send_reply(299
async fn send_reply(227
&self,300
&self,228
event_id: &str,301
event_id: &str,@@ -332,6 +405,25 @@ mod tests {332
}405
}333
}406
}334
407
408
#[test]409
fn join_first_body_puts_link_in_location_without_online_meeting() {410
let body = new_event_body_with_join(411
&event(Repeat::Never),412
"https://teams.microsoft.com/l/meetup-join/x",413
);414
assert_eq!(body["isOnlineMeeting"], false);415
assert_eq!(416
body["location"]["displayName"],417
"https://teams.microsoft.com/l/meetup-join/x"418
);419
assert!(420
body["body"]["content"]421
.as_str()422
.unwrap()423
.contains("teams.microsoft.com")424
);425
}426
335
#[test]427
#[test]336
fn the_body_asks_for_a_teams_meeting_with_utc_times() {428
fn the_body_asks_for_a_teams_meeting_with_utc_times() {337
let body = new_event_body(&event(Repeat::Never));429
let body = new_event_body(&event(Repeat::Never));@@ -479,6 +571,18 @@ mod tests {479
);571
);480
}572
}481
573
574
#[tokio::test]575
async fn delete_event_sends_graph_delete() {576
let calendar = Calendar::with_transport(Scripted::new(vec![(204, Value::Null)]), "emea");577
calendar.delete_event("AAMk=", None).await.unwrap();578
let sent = calendar.transport.sent.lock().unwrap();579
assert_eq!(sent[0].0, Method::Delete);580
assert_eq!(581
sent[0].1,582
"https://graph.microsoft.com/v1.0/me/events/AAMk%3D"583
);584
}585
482
#[tokio::test]586
#[tokio::test]483
async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() {587
async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() {484
let calendar = Calendar::with_transport(588
let calendar = Calendar::with_transport(@@ -0,0 +1,114 @@
1
use std::net::SocketAddr;
2
use std::time::Duration;
3
4
use tokio::io::{AsyncReadExt, AsyncWriteExt};
5
use tokio::net::TcpListener;
6
7
use crate::error::{Error, Result};
8
9
use super::oauth::AuthPending;
10
11
/// Bind a free loopback port and return `http://127.0.0.1:<port>/`.
12
pub async fn allocate_redirect_uri() -> Result<(String, TcpListener)> {
13
let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))
14
.await
15
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
16
let port = listener
17
.local_addr()
18
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?
19
.port();
20
Ok((format!("http://127.0.0.1:{port}/"), listener))
21
}
22
23
/// Wait for the browser redirect, validate `state`, return the authorization code.
24
pub async fn wait_for_code(pending: &AuthPending, listener: TcpListener) -> Result<String> {
25
let accept = tokio::time::timeout(Duration::from_secs(180), listener.accept());
26
let (mut stream, _) = accept
27
.await
28
.map_err(|_| Error::UnexpectedAnswer("Google sign-in timed out".into()))?
29
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
30
let mut buffer = vec![0_u8; 4096];
31
let read = stream
32
.read(&mut buffer)
33
.await
34
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
35
let request = String::from_utf8_lossy(&buffer[..read]);
36
let line = request.lines().next().unwrap_or_default();
37
let path = line
38
.strip_prefix("GET ")
39
.and_then(|rest| rest.split_whitespace().next())
40
.unwrap_or("/");
41
let query = path.split('?').nth(1).unwrap_or("");
42
let mut code = None;
43
let mut state = None;
44
for pair in query.split('&') {
45
let mut parts = pair.splitn(2, '=');
46
match (parts.next(), parts.next()) {
47
(Some("code"), Some(value)) => code = Some(urlencoding_decode(value)),
48
(Some("state"), Some(value)) => state = Some(urlencoding_decode(value)),
49
_ => {}
50
}
51
}
52
let body = if state.as_deref() == Some(pending.state.as_str()) && code.is_some() {
53
"You can close this window and return to Rusty Teams."
54
} else {
55
"Sign-in failed. You can close this window."
56
};
57
let response = format!(
58
"HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
59
body.len()
60
);
61
let _ = stream.write_all(response.as_bytes()).await;
62
let _ = stream.shutdown().await;
63
if state.as_deref() != Some(pending.state.as_str()) {
64
return Err(Error::UnexpectedAnswer(
65
"Google OAuth state mismatch".into(),
66
));
67
}
68
code.ok_or_else(|| Error::UnexpectedAnswer("Google OAuth code missing".into()))
69
}
70
71
fn urlencoding_decode(value: &str) -> String {
72
percent_encoding::percent_decode_str(value)
73
.decode_utf8_lossy()
74
.into_owned()
75
}
76
77
#[cfg(test)]
78
mod tests {
79
use super::*;
80
use crate::google_calendar::oauth::GoogleOAuth;
81
82
#[tokio::test]
83
async fn allocate_redirect_is_loopback() {
84
let (uri, listener) = allocate_redirect_uri().await.unwrap();
85
assert!(uri.starts_with("http://127.0.0.1:"));
86
assert!(uri.ends_with('/'));
87
drop(listener);
88
}
89
90
#[tokio::test]
91
async fn wait_for_code_reads_query() {
92
let oauth = GoogleOAuth {
93
client_id: "cid".into(),
94
client_secret: String::new(),
95
};
96
let (uri, listener) = allocate_redirect_uri().await.unwrap();
97
let pending = oauth.begin(&uri);
98
let port = listener.local_addr().unwrap().port();
99
let state = pending.state.clone();
100
let code_value = "the-code";
101
tokio::spawn(async move {
102
tokio::time::sleep(Duration::from_millis(50)).await;
103
let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))
104
.await
105
.unwrap();
106
let request = format!(
107
"GET /?code={code_value}&state={state} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"
108
);
109
stream.write_all(request.as_bytes()).await.unwrap();
110
});
111
let code = wait_for_code(&pending, listener).await.unwrap();
112
assert_eq!(code, code_value);
113
}
114
}
@@ -0,0 +1,114 @@1
use std::net::SocketAddr;2
use std::time::Duration;3
4
use tokio::io::{AsyncReadExt, AsyncWriteExt};5
use tokio::net::TcpListener;6
7
use crate::error::{Error, Result};8
9
use super::oauth::AuthPending;10
11
/// Bind a free loopback port and return `http://127.0.0.1:<port>/`.12
pub async fn allocate_redirect_uri() -> Result<(String, TcpListener)> {13
let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))14
.await15
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;16
let port = listener17
.local_addr()18
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?19
.port();20
Ok((format!("http://127.0.0.1:{port}/"), listener))21
}22
23
/// Wait for the browser redirect, validate `state`, return the authorization code.24
pub async fn wait_for_code(pending: &AuthPending, listener: TcpListener) -> Result<String> {25
let accept = tokio::time::timeout(Duration::from_secs(180), listener.accept());26
let (mut stream, _) = accept27
.await28
.map_err(|_| Error::UnexpectedAnswer("Google sign-in timed out".into()))?29
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;30
let mut buffer = vec![0_u8; 4096];31
let read = stream32
.read(&mut buffer)33
.await34
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;35
let request = String::from_utf8_lossy(&buffer[..read]);36
let line = request.lines().next().unwrap_or_default();37
let path = line38
.strip_prefix("GET ")39
.and_then(|rest| rest.split_whitespace().next())40
.unwrap_or("/");41
let query = path.split('?').nth(1).unwrap_or("");42
let mut code = None;43
let mut state = None;44
for pair in query.split('&') {45
let mut parts = pair.splitn(2, '=');46
match (parts.next(), parts.next()) {47
(Some("code"), Some(value)) => code = Some(urlencoding_decode(value)),48
(Some("state"), Some(value)) => state = Some(urlencoding_decode(value)),49
_ => {}50
}51
}52
let body = if state.as_deref() == Some(pending.state.as_str()) && code.is_some() {53
"You can close this window and return to Rusty Teams."54
} else {55
"Sign-in failed. You can close this window."56
};57
let response = format!(58
"HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",59
body.len()60
);61
let _ = stream.write_all(response.as_bytes()).await;62
let _ = stream.shutdown().await;63
if state.as_deref() != Some(pending.state.as_str()) {64
return Err(Error::UnexpectedAnswer(65
"Google OAuth state mismatch".into(),66
));67
}68
code.ok_or_else(|| Error::UnexpectedAnswer("Google OAuth code missing".into()))69
}70
71
fn urlencoding_decode(value: &str) -> String {72
percent_encoding::percent_decode_str(value)73
.decode_utf8_lossy()74
.into_owned()75
}76
77
#[cfg(test)]78
mod tests {79
use super::*;80
use crate::google_calendar::oauth::GoogleOAuth;81
82
#[tokio::test]83
async fn allocate_redirect_is_loopback() {84
let (uri, listener) = allocate_redirect_uri().await.unwrap();85
assert!(uri.starts_with("http://127.0.0.1:"));86
assert!(uri.ends_with('/'));87
drop(listener);88
}89
90
#[tokio::test]91
async fn wait_for_code_reads_query() {92
let oauth = GoogleOAuth {93
client_id: "cid".into(),94
client_secret: String::new(),95
};96
let (uri, listener) = allocate_redirect_uri().await.unwrap();97
let pending = oauth.begin(&uri);98
let port = listener.local_addr().unwrap().port();99
let state = pending.state.clone();100
let code_value = "the-code";101
tokio::spawn(async move {102
tokio::time::sleep(Duration::from_millis(50)).await;103
let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))104
.await105
.unwrap();106
let request = format!(107
"GET /?code={code_value}&state={state} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"108
);109
stream.write_all(request.as_bytes()).await.unwrap();110
});111
let code = wait_for_code(&pending, listener).await.unwrap();112
assert_eq!(code, code_value);113
}114
}@@ -0,0 +1,133 @@
1
use crate::calendar::{CalendarEvent, CalendarSource};
2
3
/// Collapse duplicate meetings that share an iCal UID or the same Teams join URL.
4
pub fn merge_calendar_events(events: Vec<CalendarEvent>) -> Vec<CalendarEvent> {
5
let mut merged: Vec<CalendarEvent> = Vec::new();
6
for event in events {
7
if let Some(existing) = merged
8
.iter_mut()
9
.find(|candidate| same_meeting(candidate, &event))
10
{
11
if !existing.sources.contains(&event.source) {
12
existing.sources.push(event.source);
13
}
14
if existing.join_url.is_none() {
15
existing.join_url = event.join_url.clone();
16
existing.online = existing.online || event.online;
17
}
18
if existing.thread_id.is_none() {
19
existing.thread_id = event.thread_id.clone();
20
}
21
// Prefer Outlook object id when both sides contribute.
22
if existing.source == CalendarSource::Google && event.source == CalendarSource::Outlook
23
{
24
existing.object_id = event.object_id.clone();
25
existing.source = CalendarSource::Outlook;
26
existing.account_id = event.account_id.clone();
27
existing.calendar_id = event.calendar_id.clone();
28
existing.response = event.response;
29
existing.show_as = event.show_as;
30
}
31
continue;
32
}
33
merged.push(event);
34
}
35
merged.sort_by_key(|event| (event.start, event.end));
36
merged
37
}
38
39
fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
40
if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
41
if !a.is_empty() && a == b {
42
return true;
43
}
44
}
45
match (
46
left.join_url.as_deref().map(normalize_join_url),
47
right.join_url.as_deref().map(normalize_join_url),
48
) {
49
(Some(a), Some(b)) if !a.is_empty() && a == b => true,
50
_ => false,
51
}
52
}
53
54
pub fn normalize_join_url(url: &str) -> String {
55
let trimmed = url.trim().trim_end_matches('/');
56
let without_query = trimmed.split('?').next().unwrap_or(trimmed);
57
without_query.to_ascii_lowercase()
58
}
59
60
#[cfg(test)]
61
mod tests {
62
use chrono::TimeZone;
63
64
use super::*;
65
66
fn event(
67
id: &str,
68
source: CalendarSource,
69
ical: Option<&str>,
70
join: Option<&str>,
71
) -> CalendarEvent {
72
CalendarEvent {
73
object_id: id.into(),
74
subject: "Sync".into(),
75
start: chrono::Utc
76
.with_ymd_and_hms(2026, 11, 11, 10, 0, 0)
77
.unwrap(),
78
end: chrono::Utc
79
.with_ymd_and_hms(2026, 11, 11, 10, 30, 0)
80
.unwrap(),
81
ical_uid: ical.map(str::to_owned),
82
join_url: join.map(str::to_owned),
83
online: join.is_some(),
84
source,
85
sources: vec![source],
86
..Default::default()
87
}
88
}
89
90
#[test]
91
fn merges_on_ical_uid_and_keeps_both_sources() {
92
let merged = merge_calendar_events(vec![
93
event("o1", CalendarSource::Outlook, Some("uid"), None),
94
event(
95
"g1",
96
CalendarSource::Google,
97
Some("uid"),
98
Some("https://teams.microsoft.com/l/meetup-join/x"),
99
),
100
]);
101
assert_eq!(merged.len(), 1);
102
assert_eq!(merged[0].sources.len(), 2);
103
assert_eq!(merged[0].object_id, "o1");
104
assert!(merged[0].join_url.is_some());
105
}
106
107
#[test]
108
fn merges_on_normalized_join_url() {
109
let merged = merge_calendar_events(vec![
110
event(
111
"o1",
112
CalendarSource::Outlook,
113
None,
114
Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),
115
),
116
event(
117
"g1",
118
CalendarSource::Google,
119
None,
120
Some("https://teams.microsoft.com/l/meetup-join/x/"),
121
),
122
]);
123
assert_eq!(merged.len(), 1);
124
}
125
126
#[test]
127
fn does_not_merge_on_title_and_time_alone() {
128
let a = event("a", CalendarSource::Outlook, Some("a"), None);
129
let mut b = event("b", CalendarSource::Google, Some("b"), None);
130
b.subject = a.subject.clone();
131
assert_eq!(merge_calendar_events(vec![a, b]).len(), 2);
132
}
133
}
@@ -0,0 +1,133 @@1
use crate::calendar::{CalendarEvent, CalendarSource};2
3
/// Collapse duplicate meetings that share an iCal UID or the same Teams join URL.4
pub fn merge_calendar_events(events: Vec<CalendarEvent>) -> Vec<CalendarEvent> {5
let mut merged: Vec<CalendarEvent> = Vec::new();6
for event in events {7
if let Some(existing) = merged8
.iter_mut()9
.find(|candidate| same_meeting(candidate, &event))10
{11
if !existing.sources.contains(&event.source) {12
existing.sources.push(event.source);13
}14
if existing.join_url.is_none() {15
existing.join_url = event.join_url.clone();16
existing.online = existing.online || event.online;17
}18
if existing.thread_id.is_none() {19
existing.thread_id = event.thread_id.clone();20
}21
// Prefer Outlook object id when both sides contribute.22
if existing.source == CalendarSource::Google && event.source == CalendarSource::Outlook23
{24
existing.object_id = event.object_id.clone();25
existing.source = CalendarSource::Outlook;26
existing.account_id = event.account_id.clone();27
existing.calendar_id = event.calendar_id.clone();28
existing.response = event.response;29
existing.show_as = event.show_as;30
}31
continue;32
}33
merged.push(event);34
}35
merged.sort_by_key(|event| (event.start, event.end));36
merged37
}38
39
fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {40
if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {41
if !a.is_empty() && a == b {42
return true;43
}44
}45
match (46
left.join_url.as_deref().map(normalize_join_url),47
right.join_url.as_deref().map(normalize_join_url),48
) {49
(Some(a), Some(b)) if !a.is_empty() && a == b => true,50
_ => false,51
}52
}53
54
pub fn normalize_join_url(url: &str) -> String {55
let trimmed = url.trim().trim_end_matches('/');56
let without_query = trimmed.split('?').next().unwrap_or(trimmed);57
without_query.to_ascii_lowercase()58
}59
60
#[cfg(test)]61
mod tests {62
use chrono::TimeZone;63
64
use super::*;65
66
fn event(67
id: &str,68
source: CalendarSource,69
ical: Option<&str>,70
join: Option<&str>,71
) -> CalendarEvent {72
CalendarEvent {73
object_id: id.into(),74
subject: "Sync".into(),75
start: chrono::Utc76
.with_ymd_and_hms(2026, 11, 11, 10, 0, 0)77
.unwrap(),78
end: chrono::Utc79
.with_ymd_and_hms(2026, 11, 11, 10, 30, 0)80
.unwrap(),81
ical_uid: ical.map(str::to_owned),82
join_url: join.map(str::to_owned),83
online: join.is_some(),84
source,85
sources: vec![source],86
..Default::default()87
}88
}89
90
#[test]91
fn merges_on_ical_uid_and_keeps_both_sources() {92
let merged = merge_calendar_events(vec![93
event("o1", CalendarSource::Outlook, Some("uid"), None),94
event(95
"g1",96
CalendarSource::Google,97
Some("uid"),98
Some("https://teams.microsoft.com/l/meetup-join/x"),99
),100
]);101
assert_eq!(merged.len(), 1);102
assert_eq!(merged[0].sources.len(), 2);103
assert_eq!(merged[0].object_id, "o1");104
assert!(merged[0].join_url.is_some());105
}106
107
#[test]108
fn merges_on_normalized_join_url() {109
let merged = merge_calendar_events(vec![110
event(111
"o1",112
CalendarSource::Outlook,113
None,114
Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),115
),116
event(117
"g1",118
CalendarSource::Google,119
None,120
Some("https://teams.microsoft.com/l/meetup-join/x/"),121
),122
]);123
assert_eq!(merged.len(), 1);124
}125
126
#[test]127
fn does_not_merge_on_title_and_time_alone() {128
let a = event("a", CalendarSource::Outlook, Some("a"), None);129
let mut b = event("b", CalendarSource::Google, Some("b"), None);130
b.subject = a.subject.clone();131
assert_eq!(merge_calendar_events(vec![a, b]).len(), 2);132
}133
}@@ -0,0 +1,177 @@
1
//! Google Calendar OAuth + REST client for rusty-teams calendar accounts.
2
3
mod loopback;
4
mod merge;
5
mod oauth;
6
mod parse;
7
mod write;
8
9
pub use loopback::{allocate_redirect_uri, wait_for_code};
10
pub use merge::{merge_calendar_events, normalize_join_url};
11
pub use oauth::{
12
AuthPending, GoogleOAuth, TokenBundle, client_id_from_env, exchange_code, refresh_access_token,
13
};
14
pub use parse::{parse_calendar_list, parse_google_events};
15
pub use write::{
16
GoogleEventDraft, google_event_body, google_rsvp_query, google_rsvp_status, rrule_for_repeat,
17
};
18
19
use chrono::{DateTime, Utc};
20
use reqwest::Client;
21
use serde_json::Value;
22
23
use crate::calendar::CalendarEvent;
24
use crate::error::{Error, Result};
25
26
const CALENDAR_API: &str = "https://www.googleapis.com/calendar/v3";
27
28
pub struct GoogleCalendar {
29
client: Client,
30
access_token: String,
31
}
32
33
impl GoogleCalendar {
34
pub fn new(access_token: impl Into<String>) -> Self {
35
GoogleCalendar {
36
client: Client::new(),
37
access_token: access_token.into(),
38
}
39
}
40
41
pub async fn list_calendars(&self) -> Result<Value> {
42
self.get(&format!("{CALENDAR_API}/users/me/calendarList"))
43
.await
44
}
45
46
pub async fn events(
47
&self,
48
calendar_id: &str,
49
start: DateTime<Utc>,
50
end: DateTime<Utc>,
51
) -> Result<Vec<CalendarEvent>> {
52
let encoded =
53
percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
54
let url = format!(
55
"{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&timeMin={}&timeMax={}",
56
start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
57
end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
58
);
59
let body = self.get(&url).await?;
60
Ok(parse_google_events(&body, None, Some(calendar_id)))
61
}
62
63
pub async fn insert_event(&self, calendar_id: &str, draft: &GoogleEventDraft) -> Result<Value> {
64
let encoded =
65
percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
66
let url = format!("{CALENDAR_API}/calendars/{encoded}/events?sendUpdates=all");
67
self.post(&url, google_event_body(draft)).await
68
}
69
70
pub async fn respond(
71
&self,
72
calendar_id: &str,
73
event_id: &str,
74
status: &str,
75
send_updates: bool,
76
) -> Result<()> {
77
let encoded_cal =
78
percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
79
let encoded_event =
80
percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);
81
let url = format!(
82
"{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",
83
google_rsvp_query(send_updates)
84
);
85
// Patch attendee self via conferenceData-free body: use attendees[].responseStatus
86
// by first getting the event is heavy; Google allows PATCH with only attendees when
87
// "self" is present. Simpler path: PATCH with a single attendees entry marked self.
88
let body = serde_json::json!({
89
"attendees": [{ "self": true, "responseStatus": status }]
90
});
91
self.patch(&url, body).await?;
92
Ok(())
93
}
94
95
pub async fn delete_event(
96
&self,
97
calendar_id: &str,
98
event_id: &str,
99
send_updates: bool,
100
) -> Result<()> {
101
let encoded_cal =
102
percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
103
let encoded_event =
104
percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);
105
let url = format!(
106
"{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",
107
google_rsvp_query(send_updates)
108
);
109
self.delete(&url).await
110
}
111
112
async fn get(&self, url: &str) -> Result<Value> {
113
let response = self
114
.client
115
.get(url)
116
.bearer_auth(&self.access_token)
117
.send()
118
.await
119
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
120
Self::json_result(url, response).await
121
}
122
123
async fn post(&self, url: &str, body: Value) -> Result<Value> {
124
let response = self
125
.client
126
.post(url)
127
.bearer_auth(&self.access_token)
128
.json(&body)
129
.send()
130
.await
131
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
132
Self::json_result(url, response).await
133
}
134
135
async fn patch(&self, url: &str, body: Value) -> Result<Value> {
136
let response = self
137
.client
138
.patch(url)
139
.bearer_auth(&self.access_token)
140
.json(&body)
141
.send()
142
.await
143
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
144
Self::json_result(url, response).await
145
}
146
147
async fn delete(&self, url: &str) -> Result<()> {
148
let response = self
149
.client
150
.delete(url)
151
.bearer_auth(&self.access_token)
152
.send()
153
.await
154
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
155
let status = response.status().as_u16();
156
if (200..300).contains(&status) {
157
return Ok(());
158
}
159
let body = response
160
.json::<Value>()
161
.await
162
.unwrap_or_else(|_| Value::Null);
163
Err(Error::Session(session::Error::api(status, url, body)))
164
}
165
166
async fn json_result(url: &str, response: reqwest::Response) -> Result<Value> {
167
let status = response.status().as_u16();
168
let body = response
169
.json::<Value>()
170
.await
171
.unwrap_or_else(|_| Value::Null);
172
if !(200..300).contains(&status) {
173
return Err(Error::Session(session::Error::api(status, url, body)));
174
}
175
Ok(body)
176
}
177
}
@@ -0,0 +1,177 @@1
//! Google Calendar OAuth + REST client for rusty-teams calendar accounts.2
3
mod loopback;4
mod merge;5
mod oauth;6
mod parse;7
mod write;8
9
pub use loopback::{allocate_redirect_uri, wait_for_code};10
pub use merge::{merge_calendar_events, normalize_join_url};11
pub use oauth::{12
AuthPending, GoogleOAuth, TokenBundle, client_id_from_env, exchange_code, refresh_access_token,13
};14
pub use parse::{parse_calendar_list, parse_google_events};15
pub use write::{16
GoogleEventDraft, google_event_body, google_rsvp_query, google_rsvp_status, rrule_for_repeat,17
};18
19
use chrono::{DateTime, Utc};20
use reqwest::Client;21
use serde_json::Value;22
23
use crate::calendar::CalendarEvent;24
use crate::error::{Error, Result};25
26
const CALENDAR_API: &str = "https://www.googleapis.com/calendar/v3";27
28
pub struct GoogleCalendar {29
client: Client,30
access_token: String,31
}32
33
impl GoogleCalendar {34
pub fn new(access_token: impl Into<String>) -> Self {35
GoogleCalendar {36
client: Client::new(),37
access_token: access_token.into(),38
}39
}40
41
pub async fn list_calendars(&self) -> Result<Value> {42
self.get(&format!("{CALENDAR_API}/users/me/calendarList"))43
.await44
}45
46
pub async fn events(47
&self,48
calendar_id: &str,49
start: DateTime<Utc>,50
end: DateTime<Utc>,51
) -> Result<Vec<CalendarEvent>> {52
let encoded =53
percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);54
let url = format!(55
"{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&timeMin={}&timeMax={}",56
start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),57
end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),58
);59
let body = self.get(&url).await?;60
Ok(parse_google_events(&body, None, Some(calendar_id)))61
}62
63
pub async fn insert_event(&self, calendar_id: &str, draft: &GoogleEventDraft) -> Result<Value> {64
let encoded =65
percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);66
let url = format!("{CALENDAR_API}/calendars/{encoded}/events?sendUpdates=all");67
self.post(&url, google_event_body(draft)).await68
}69
70
pub async fn respond(71
&self,72
calendar_id: &str,73
event_id: &str,74
status: &str,75
send_updates: bool,76
) -> Result<()> {77
let encoded_cal =78
percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);79
let encoded_event =80
percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);81
let url = format!(82
"{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",83
google_rsvp_query(send_updates)84
);85
// Patch attendee self via conferenceData-free body: use attendees[].responseStatus86
// by first getting the event is heavy; Google allows PATCH with only attendees when87
// "self" is present. Simpler path: PATCH with a single attendees entry marked self.88
let body = serde_json::json!({89
"attendees": [{ "self": true, "responseStatus": status }]90
});91
self.patch(&url, body).await?;92
Ok(())93
}94
95
pub async fn delete_event(96
&self,97
calendar_id: &str,98
event_id: &str,99
send_updates: bool,100
) -> Result<()> {101
let encoded_cal =102
percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);103
let encoded_event =104
percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);105
let url = format!(106
"{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",107
google_rsvp_query(send_updates)108
);109
self.delete(&url).await110
}111
112
async fn get(&self, url: &str) -> Result<Value> {113
let response = self114
.client115
.get(url)116
.bearer_auth(&self.access_token)117
.send()118
.await119
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;120
Self::json_result(url, response).await121
}122
123
async fn post(&self, url: &str, body: Value) -> Result<Value> {124
let response = self125
.client126
.post(url)127
.bearer_auth(&self.access_token)128
.json(&body)129
.send()130
.await131
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;132
Self::json_result(url, response).await133
}134
135
async fn patch(&self, url: &str, body: Value) -> Result<Value> {136
let response = self137
.client138
.patch(url)139
.bearer_auth(&self.access_token)140
.json(&body)141
.send()142
.await143
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;144
Self::json_result(url, response).await145
}146
147
async fn delete(&self, url: &str) -> Result<()> {148
let response = self149
.client150
.delete(url)151
.bearer_auth(&self.access_token)152
.send()153
.await154
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;155
let status = response.status().as_u16();156
if (200..300).contains(&status) {157
return Ok(());158
}159
let body = response160
.json::<Value>()161
.await162
.unwrap_or_else(|_| Value::Null);163
Err(Error::Session(session::Error::api(status, url, body)))164
}165
166
async fn json_result(url: &str, response: reqwest::Response) -> Result<Value> {167
let status = response.status().as_u16();168
let body = response169
.json::<Value>()170
.await171
.unwrap_or_else(|_| Value::Null);172
if !(200..300).contains(&status) {173
return Err(Error::Session(session::Error::api(status, url, body)));174
}175
Ok(body)176
}177
}@@ -0,0 +1,185 @@
1
use base64::Engine as _;
2
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
3
use rand::RngCore;
4
use serde::Deserialize;
5
use sha2::{Digest, Sha256};
6
7
use crate::error::{Error, Result};
8
9
pub const GOOGLE_CLIENT_ID_ENV: &str = "TEAMS_GOOGLE_CLIENT_ID";
10
pub const GOOGLE_CLIENT_SECRET_ENV: &str = "TEAMS_GOOGLE_CLIENT_SECRET";
11
const AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
12
const TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
13
const SCOPES: &str =
14
"https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email";
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub struct GoogleOAuth {
18
pub client_id: String,
19
pub client_secret: String,
20
}
21
22
#[derive(Debug, Clone, PartialEq, Eq)]
23
pub struct AuthPending {
24
pub authorize_url: String,
25
pub redirect_uri: String,
26
pub state: String,
27
pub code_verifier: String,
28
}
29
30
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
31
pub struct TokenBundle {
32
pub access_token: String,
33
#[serde(default)]
34
pub refresh_token: String,
35
#[serde(default)]
36
pub expires_in: i64,
37
#[serde(default)]
38
pub token_type: String,
39
}
40
41
pub fn client_id_from_env() -> Option<GoogleOAuth> {
42
let client_id = std::env::var(GOOGLE_CLIENT_ID_ENV).ok()?;
43
if client_id.trim().is_empty() {
44
return None;
45
}
46
let client_secret = std::env::var(GOOGLE_CLIENT_SECRET_ENV).unwrap_or_default();
47
Some(GoogleOAuth {
48
client_id,
49
client_secret,
50
})
51
}
52
53
impl GoogleOAuth {
54
pub fn begin(&self, redirect_uri: &str) -> AuthPending {
55
let state = random_url_token(16);
56
let code_verifier = random_url_token(32);
57
let challenge = code_challenge(&code_verifier);
58
let mut url = url::Url::parse(AUTH_URL).expect("auth url");
59
{
60
let mut query = url.query_pairs_mut();
61
query.append_pair("client_id", &self.client_id);
62
query.append_pair("redirect_uri", redirect_uri);
63
query.append_pair("response_type", "code");
64
query.append_pair("scope", SCOPES);
65
query.append_pair("access_type", "offline");
66
query.append_pair("prompt", "consent");
67
query.append_pair("state", &state);
68
query.append_pair("code_challenge", &challenge);
69
query.append_pair("code_challenge_method", "S256");
70
}
71
AuthPending {
72
authorize_url: url.to_string(),
73
redirect_uri: redirect_uri.to_owned(),
74
state,
75
code_verifier,
76
}
77
}
78
}
79
80
pub async fn exchange_code(
81
oauth: &GoogleOAuth,
82
pending: &AuthPending,
83
code: &str,
84
) -> Result<TokenBundle> {
85
let client = reqwest::Client::new();
86
let mut form = vec![
87
("code", code.to_owned()),
88
("client_id", oauth.client_id.clone()),
89
("redirect_uri", pending.redirect_uri.clone()),
90
("grant_type", "authorization_code".to_owned()),
91
("code_verifier", pending.code_verifier.clone()),
92
];
93
if !oauth.client_secret.is_empty() {
94
form.push(("client_secret", oauth.client_secret.clone()));
95
}
96
let response = client
97
.post(TOKEN_URL)
98
.form(&form)
99
.send()
100
.await
101
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
102
let status = response.status().as_u16();
103
let body = response
104
.json::<serde_json::Value>()
105
.await
106
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
107
if !(200..300).contains(&status) {
108
return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));
109
}
110
serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))
111
}
112
113
pub async fn refresh_access_token(oauth: &GoogleOAuth, refresh_token: &str) -> Result<TokenBundle> {
114
let client = reqwest::Client::new();
115
let mut form = vec![
116
("client_id", oauth.client_id.clone()),
117
("grant_type", "refresh_token".to_owned()),
118
("refresh_token", refresh_token.to_owned()),
119
];
120
if !oauth.client_secret.is_empty() {
121
form.push(("client_secret", oauth.client_secret.clone()));
122
}
123
let response = client
124
.post(TOKEN_URL)
125
.form(&form)
126
.send()
127
.await
128
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
129
let status = response.status().as_u16();
130
let body = response
131
.json::<serde_json::Value>()
132
.await
133
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
134
if !(200..300).contains(&status) {
135
return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));
136
}
137
let mut bundle: TokenBundle =
138
serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
139
if bundle.refresh_token.is_empty() {
140
bundle.refresh_token = refresh_token.to_owned();
141
}
142
Ok(bundle)
143
}
144
145
fn random_url_token(bytes: usize) -> String {
146
let mut buffer = vec![0_u8; bytes];
147
rand::rng().fill_bytes(&mut buffer);
148
URL_SAFE_NO_PAD.encode(buffer)
149
}
150
151
fn code_challenge(verifier: &str) -> String {
152
let digest = Sha256::digest(verifier.as_bytes());
153
URL_SAFE_NO_PAD.encode(digest)
154
}
155
156
#[cfg(test)]
157
mod tests {
158
use super::*;
159
160
#[test]
161
fn begin_builds_pkce_authorize_url() {
162
let oauth = GoogleOAuth {
163
client_id: "cid".into(),
164
client_secret: String::new(),
165
};
166
let pending = oauth.begin("http://127.0.0.1:8765/");
167
assert!(pending.authorize_url.contains("client_id=cid"));
168
assert!(pending.authorize_url.contains("code_challenge_method=S256"));
169
assert!(!pending.code_verifier.is_empty());
170
assert_eq!(
171
code_challenge("abc"),
172
URL_SAFE_NO_PAD.encode(Sha256::digest(b"abc"))
173
);
174
}
175
176
#[test]
177
fn token_bundle_deserializes() {
178
let json =
179
r#"{"access_token":"a","refresh_token":"r","expires_in":3600,"token_type":"Bearer"}"#;
180
let bundle: TokenBundle = serde_json::from_str(json).unwrap();
181
assert_eq!(bundle.access_token, "a");
182
assert_eq!(bundle.refresh_token, "r");
183
assert_eq!(bundle.expires_in, 3600);
184
}
185
}
@@ -0,0 +1,185 @@1
use base64::Engine as _;2
use base64::engine::general_purpose::URL_SAFE_NO_PAD;3
use rand::RngCore;4
use serde::Deserialize;5
use sha2::{Digest, Sha256};6
7
use crate::error::{Error, Result};8
9
pub const GOOGLE_CLIENT_ID_ENV: &str = "TEAMS_GOOGLE_CLIENT_ID";10
pub const GOOGLE_CLIENT_SECRET_ENV: &str = "TEAMS_GOOGLE_CLIENT_SECRET";11
const AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";12
const TOKEN_URL: &str = "https://oauth2.googleapis.com/token";13
const SCOPES: &str =14
"https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email";15
16
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct GoogleOAuth {18
pub client_id: String,19
pub client_secret: String,20
}21
22
#[derive(Debug, Clone, PartialEq, Eq)]23
pub struct AuthPending {24
pub authorize_url: String,25
pub redirect_uri: String,26
pub state: String,27
pub code_verifier: String,28
}29
30
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]31
pub struct TokenBundle {32
pub access_token: String,33
#[serde(default)]34
pub refresh_token: String,35
#[serde(default)]36
pub expires_in: i64,37
#[serde(default)]38
pub token_type: String,39
}40
41
pub fn client_id_from_env() -> Option<GoogleOAuth> {42
let client_id = std::env::var(GOOGLE_CLIENT_ID_ENV).ok()?;43
if client_id.trim().is_empty() {44
return None;45
}46
let client_secret = std::env::var(GOOGLE_CLIENT_SECRET_ENV).unwrap_or_default();47
Some(GoogleOAuth {48
client_id,49
client_secret,50
})51
}52
53
impl GoogleOAuth {54
pub fn begin(&self, redirect_uri: &str) -> AuthPending {55
let state = random_url_token(16);56
let code_verifier = random_url_token(32);57
let challenge = code_challenge(&code_verifier);58
let mut url = url::Url::parse(AUTH_URL).expect("auth url");59
{60
let mut query = url.query_pairs_mut();61
query.append_pair("client_id", &self.client_id);62
query.append_pair("redirect_uri", redirect_uri);63
query.append_pair("response_type", "code");64
query.append_pair("scope", SCOPES);65
query.append_pair("access_type", "offline");66
query.append_pair("prompt", "consent");67
query.append_pair("state", &state);68
query.append_pair("code_challenge", &challenge);69
query.append_pair("code_challenge_method", "S256");70
}71
AuthPending {72
authorize_url: url.to_string(),73
redirect_uri: redirect_uri.to_owned(),74
state,75
code_verifier,76
}77
}78
}79
80
pub async fn exchange_code(81
oauth: &GoogleOAuth,82
pending: &AuthPending,83
code: &str,84
) -> Result<TokenBundle> {85
let client = reqwest::Client::new();86
let mut form = vec![87
("code", code.to_owned()),88
("client_id", oauth.client_id.clone()),89
("redirect_uri", pending.redirect_uri.clone()),90
("grant_type", "authorization_code".to_owned()),91
("code_verifier", pending.code_verifier.clone()),92
];93
if !oauth.client_secret.is_empty() {94
form.push(("client_secret", oauth.client_secret.clone()));95
}96
let response = client97
.post(TOKEN_URL)98
.form(&form)99
.send()100
.await101
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;102
let status = response.status().as_u16();103
let body = response104
.json::<serde_json::Value>()105
.await106
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;107
if !(200..300).contains(&status) {108
return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));109
}110
serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))111
}112
113
pub async fn refresh_access_token(oauth: &GoogleOAuth, refresh_token: &str) -> Result<TokenBundle> {114
let client = reqwest::Client::new();115
let mut form = vec![116
("client_id", oauth.client_id.clone()),117
("grant_type", "refresh_token".to_owned()),118
("refresh_token", refresh_token.to_owned()),119
];120
if !oauth.client_secret.is_empty() {121
form.push(("client_secret", oauth.client_secret.clone()));122
}123
let response = client124
.post(TOKEN_URL)125
.form(&form)126
.send()127
.await128
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;129
let status = response.status().as_u16();130
let body = response131
.json::<serde_json::Value>()132
.await133
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;134
if !(200..300).contains(&status) {135
return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));136
}137
let mut bundle: TokenBundle =138
serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;139
if bundle.refresh_token.is_empty() {140
bundle.refresh_token = refresh_token.to_owned();141
}142
Ok(bundle)143
}144
145
fn random_url_token(bytes: usize) -> String {146
let mut buffer = vec![0_u8; bytes];147
rand::rng().fill_bytes(&mut buffer);148
URL_SAFE_NO_PAD.encode(buffer)149
}150
151
fn code_challenge(verifier: &str) -> String {152
let digest = Sha256::digest(verifier.as_bytes());153
URL_SAFE_NO_PAD.encode(digest)154
}155
156
#[cfg(test)]157
mod tests {158
use super::*;159
160
#[test]161
fn begin_builds_pkce_authorize_url() {162
let oauth = GoogleOAuth {163
client_id: "cid".into(),164
client_secret: String::new(),165
};166
let pending = oauth.begin("http://127.0.0.1:8765/");167
assert!(pending.authorize_url.contains("client_id=cid"));168
assert!(pending.authorize_url.contains("code_challenge_method=S256"));169
assert!(!pending.code_verifier.is_empty());170
assert_eq!(171
code_challenge("abc"),172
URL_SAFE_NO_PAD.encode(Sha256::digest(b"abc"))173
);174
}175
176
#[test]177
fn token_bundle_deserializes() {178
let json =179
r#"{"access_token":"a","refresh_token":"r","expires_in":3600,"token_type":"Bearer"}"#;180
let bundle: TokenBundle = serde_json::from_str(json).unwrap();181
assert_eq!(bundle.access_token, "a");182
assert_eq!(bundle.refresh_token, "r");183
assert_eq!(bundle.expires_in, 3600);184
}185
}@@ -0,0 +1,203 @@
1
use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
2
use serde_json::Value;
3
4
use crate::calendar::{CalendarEvent, CalendarSource, ResponseType, ShowAs};
5
6
pub fn parse_calendar_list(body: &Value) -> Vec<(String, String, bool)> {
7
body.get("items")
8
.and_then(Value::as_array)
9
.into_iter()
10
.flatten()
11
.filter_map(|entry| {
12
Some((
13
entry.get("id")?.as_str()?.to_owned(),
14
entry
15
.get("summary")
16
.and_then(Value::as_str)
17
.unwrap_or("Calendar")
18
.to_owned(),
19
entry
20
.get("primary")
21
.and_then(Value::as_bool)
22
.unwrap_or(false),
23
))
24
})
25
.collect()
26
}
27
28
pub fn parse_google_events(
29
body: &Value,
30
account_id: Option<&str>,
31
calendar_id: Option<&str>,
32
) -> Vec<CalendarEvent> {
33
let mut events: Vec<CalendarEvent> = body
34
.get("items")
35
.and_then(Value::as_array)
36
.into_iter()
37
.flatten()
38
.filter_map(|entry| parse_event(entry, account_id, calendar_id))
39
.collect();
40
events.sort_by_key(|event| (event.start, event.end));
41
events
42
}
43
44
fn parse_event(
45
entry: &Value,
46
account_id: Option<&str>,
47
calendar_id: Option<&str>,
48
) -> Option<CalendarEvent> {
49
if entry.get("status").and_then(Value::as_str) == Some("cancelled") {
50
// Still show cancelled when times exist.
51
}
52
let object_id = entry.get("id")?.as_str()?.to_owned();
53
let (start, all_day) = event_instant(entry.get("start")?)?;
54
let (end, _) = event_instant(entry.get("end")?)?;
55
let join_url = conference_join_url(entry)
56
.or_else(|| text(entry, "location").filter(|value| value.contains("teams.microsoft.com")))
57
.or_else(|| {
58
text(entry, "description").and_then(|description| {
59
description
60
.split_whitespace()
61
.find(|token| token.contains("teams.microsoft.com"))
62
.map(str::to_owned)
63
})
64
});
65
Some(CalendarEvent {
66
object_id,
67
subject: text(entry, "summary").unwrap_or_default(),
68
start,
69
end,
70
all_day,
71
cancelled: entry.get("status").and_then(Value::as_str) == Some("cancelled"),
72
online: join_url.is_some(),
73
join_url,
74
thread_id: None,
75
organizer_name: entry
76
.pointer("/organizer/displayName")
77
.and_then(Value::as_str)
78
.map(str::to_owned),
79
organizer_address: entry
80
.pointer("/organizer/email")
81
.and_then(Value::as_str)
82
.map(str::to_owned),
83
ical_uid: text(entry, "iCalUID"),
84
response: response_status(entry),
85
show_as: ShowAs::Busy,
86
dial_in: None,
87
source: CalendarSource::Google,
88
account_id: account_id.map(str::to_owned),
89
calendar_id: calendar_id.map(str::to_owned),
90
sources: vec![CalendarSource::Google],
91
})
92
}
93
94
fn conference_join_url(entry: &Value) -> Option<String> {
95
entry
96
.pointer("/conferenceData/entryPoints")
97
.and_then(Value::as_array)?
98
.iter()
99
.find_map(|point| {
100
if point.get("entryPointType").and_then(Value::as_str) == Some("video") {
101
text(point, "uri")
102
} else {
103
None
104
}
105
})
106
}
107
108
fn event_instant(value: &Value) -> Option<(DateTime<Utc>, bool)> {
109
if let Some(date) = value.get("date").and_then(Value::as_str) {
110
let day = NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
111
let start = day.and_time(NaiveTime::MIN).and_utc();
112
return Some((start, true));
113
}
114
let date_time = value.get("dateTime")?.as_str()?;
115
DateTime::parse_from_rfc3339(date_time)
116
.ok()
117
.map(|time| (time.with_timezone(&Utc), false))
118
}
119
120
fn response_status(entry: &Value) -> ResponseType {
121
let status = entry
122
.get("attendees")
123
.and_then(Value::as_array)
124
.into_iter()
125
.flatten()
126
.find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true))
127
.and_then(|attendee| attendee.get("responseStatus").and_then(Value::as_str))
128
.or_else(|| {
129
entry
130
.pointer("/organizer/self")
131
.and_then(Value::as_bool)
132
.filter(|value| *value)
133
.map(|_| "accepted")
134
});
135
match status {
136
Some("accepted")
137
if entry.pointer("/organizer/self").and_then(Value::as_bool) == Some(true) =>
138
{
139
ResponseType::Organizer
140
}
141
Some("accepted") => ResponseType::Accepted,
142
Some("tentative") => ResponseType::Tentative,
143
Some("declined") => ResponseType::Declined,
144
_ => ResponseType::NotResponded,
145
}
146
}
147
148
fn text(entry: &Value, key: &str) -> Option<String> {
149
entry.get(key)?.as_str().map(str::to_owned)
150
}
151
152
#[cfg(test)]
153
mod tests {
154
use super::*;
155
156
#[test]
157
fn parses_timed_event_with_teams_link_in_location() {
158
let body = serde_json::json!({
159
"items": [{
160
"id": "evt1",
161
"summary": "Standup",
162
"iCalUID": "uid-1",
163
"start": {"dateTime": "2026-11-11T09:00:00Z"},
164
"end": {"dateTime": "2026-11-11T09:30:00Z"},
165
"location": "https://teams.microsoft.com/l/meetup-join/abc",
166
"attendees": [{"self": true, "responseStatus": "accepted"}]
167
}]
168
});
169
let events = parse_google_events(&body, Some("acc"), Some("primary"));
170
assert_eq!(events.len(), 1);
171
assert_eq!(events[0].subject, "Standup");
172
assert_eq!(events[0].source, CalendarSource::Google);
173
assert_eq!(events[0].account_id.as_deref(), Some("acc"));
174
assert_eq!(
175
events[0].join_url.as_deref(),
176
Some("https://teams.microsoft.com/l/meetup-join/abc")
177
);
178
assert_eq!(events[0].response, ResponseType::Accepted);
179
}
180
181
#[test]
182
fn parses_all_day_and_calendar_list() {
183
let body = serde_json::json!({
184
"items": [{
185
"id": "day",
186
"summary": "Offsite",
187
"start": {"date": "2026-11-12"},
188
"end": {"date": "2026-11-13"},
189
"status": "confirmed"
190
}]
191
});
192
let events = parse_google_events(&body, None, None);
193
assert!(events[0].all_day);
194
let list = parse_calendar_list(&serde_json::json!({
195
"items": [
196
{"id": "primary", "summary": "Joe", "primary": true},
197
{"id": "work", "summary": "Work"}
198
]
199
}));
200
assert_eq!(list[0].0, "primary");
201
assert!(list[0].2);
202
}
203
}
@@ -0,0 +1,203 @@1
use chrono::{DateTime, NaiveDate, NaiveTime, Utc};2
use serde_json::Value;3
4
use crate::calendar::{CalendarEvent, CalendarSource, ResponseType, ShowAs};5
6
pub fn parse_calendar_list(body: &Value) -> Vec<(String, String, bool)> {7
body.get("items")8
.and_then(Value::as_array)9
.into_iter()10
.flatten()11
.filter_map(|entry| {12
Some((13
entry.get("id")?.as_str()?.to_owned(),14
entry15
.get("summary")16
.and_then(Value::as_str)17
.unwrap_or("Calendar")18
.to_owned(),19
entry20
.get("primary")21
.and_then(Value::as_bool)22
.unwrap_or(false),23
))24
})25
.collect()26
}27
28
pub fn parse_google_events(29
body: &Value,30
account_id: Option<&str>,31
calendar_id: Option<&str>,32
) -> Vec<CalendarEvent> {33
let mut events: Vec<CalendarEvent> = body34
.get("items")35
.and_then(Value::as_array)36
.into_iter()37
.flatten()38
.filter_map(|entry| parse_event(entry, account_id, calendar_id))39
.collect();40
events.sort_by_key(|event| (event.start, event.end));41
events42
}43
44
fn parse_event(45
entry: &Value,46
account_id: Option<&str>,47
calendar_id: Option<&str>,48
) -> Option<CalendarEvent> {49
if entry.get("status").and_then(Value::as_str) == Some("cancelled") {50
// Still show cancelled when times exist.51
}52
let object_id = entry.get("id")?.as_str()?.to_owned();53
let (start, all_day) = event_instant(entry.get("start")?)?;54
let (end, _) = event_instant(entry.get("end")?)?;55
let join_url = conference_join_url(entry)56
.or_else(|| text(entry, "location").filter(|value| value.contains("teams.microsoft.com")))57
.or_else(|| {58
text(entry, "description").and_then(|description| {59
description60
.split_whitespace()61
.find(|token| token.contains("teams.microsoft.com"))62
.map(str::to_owned)63
})64
});65
Some(CalendarEvent {66
object_id,67
subject: text(entry, "summary").unwrap_or_default(),68
start,69
end,70
all_day,71
cancelled: entry.get("status").and_then(Value::as_str) == Some("cancelled"),72
online: join_url.is_some(),73
join_url,74
thread_id: None,75
organizer_name: entry76
.pointer("/organizer/displayName")77
.and_then(Value::as_str)78
.map(str::to_owned),79
organizer_address: entry80
.pointer("/organizer/email")81
.and_then(Value::as_str)82
.map(str::to_owned),83
ical_uid: text(entry, "iCalUID"),84
response: response_status(entry),85
show_as: ShowAs::Busy,86
dial_in: None,87
source: CalendarSource::Google,88
account_id: account_id.map(str::to_owned),89
calendar_id: calendar_id.map(str::to_owned),90
sources: vec![CalendarSource::Google],91
})92
}93
94
fn conference_join_url(entry: &Value) -> Option<String> {95
entry96
.pointer("/conferenceData/entryPoints")97
.and_then(Value::as_array)?98
.iter()99
.find_map(|point| {100
if point.get("entryPointType").and_then(Value::as_str) == Some("video") {101
text(point, "uri")102
} else {103
None104
}105
})106
}107
108
fn event_instant(value: &Value) -> Option<(DateTime<Utc>, bool)> {109
if let Some(date) = value.get("date").and_then(Value::as_str) {110
let day = NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;111
let start = day.and_time(NaiveTime::MIN).and_utc();112
return Some((start, true));113
}114
let date_time = value.get("dateTime")?.as_str()?;115
DateTime::parse_from_rfc3339(date_time)116
.ok()117
.map(|time| (time.with_timezone(&Utc), false))118
}119
120
fn response_status(entry: &Value) -> ResponseType {121
let status = entry122
.get("attendees")123
.and_then(Value::as_array)124
.into_iter()125
.flatten()126
.find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true))127
.and_then(|attendee| attendee.get("responseStatus").and_then(Value::as_str))128
.or_else(|| {129
entry130
.pointer("/organizer/self")131
.and_then(Value::as_bool)132
.filter(|value| *value)133
.map(|_| "accepted")134
});135
match status {136
Some("accepted")137
if entry.pointer("/organizer/self").and_then(Value::as_bool) == Some(true) =>138
{139
ResponseType::Organizer140
}141
Some("accepted") => ResponseType::Accepted,142
Some("tentative") => ResponseType::Tentative,143
Some("declined") => ResponseType::Declined,144
_ => ResponseType::NotResponded,145
}146
}147
148
fn text(entry: &Value, key: &str) -> Option<String> {149
entry.get(key)?.as_str().map(str::to_owned)150
}151
152
#[cfg(test)]153
mod tests {154
use super::*;155
156
#[test]157
fn parses_timed_event_with_teams_link_in_location() {158
let body = serde_json::json!({159
"items": [{160
"id": "evt1",161
"summary": "Standup",162
"iCalUID": "uid-1",163
"start": {"dateTime": "2026-11-11T09:00:00Z"},164
"end": {"dateTime": "2026-11-11T09:30:00Z"},165
"location": "https://teams.microsoft.com/l/meetup-join/abc",166
"attendees": [{"self": true, "responseStatus": "accepted"}]167
}]168
});169
let events = parse_google_events(&body, Some("acc"), Some("primary"));170
assert_eq!(events.len(), 1);171
assert_eq!(events[0].subject, "Standup");172
assert_eq!(events[0].source, CalendarSource::Google);173
assert_eq!(events[0].account_id.as_deref(), Some("acc"));174
assert_eq!(175
events[0].join_url.as_deref(),176
Some("https://teams.microsoft.com/l/meetup-join/abc")177
);178
assert_eq!(events[0].response, ResponseType::Accepted);179
}180
181
#[test]182
fn parses_all_day_and_calendar_list() {183
let body = serde_json::json!({184
"items": [{185
"id": "day",186
"summary": "Offsite",187
"start": {"date": "2026-11-12"},188
"end": {"date": "2026-11-13"},189
"status": "confirmed"190
}]191
});192
let events = parse_google_events(&body, None, None);193
assert!(events[0].all_day);194
let list = parse_calendar_list(&serde_json::json!({195
"items": [196
{"id": "primary", "summary": "Joe", "primary": true},197
{"id": "work", "summary": "Work"}198
]199
}));200
assert_eq!(list[0].0, "primary");201
assert!(list[0].2);202
}203
}@@ -0,0 +1,152 @@
1
use chrono::{Datelike, Timelike};
2
use serde_json::{Value, json};
3
4
use crate::calendar::{Attendee, NewEvent, Repeat, Reply};
5
6
#[derive(Debug, Clone, PartialEq, Eq)]
7
pub struct GoogleEventDraft {
8
pub subject: String,
9
pub start: chrono::DateTime<chrono::Utc>,
10
pub end: chrono::DateTime<chrono::Utc>,
11
pub attendees: Vec<Attendee>,
12
pub details: String,
13
pub join_url: Option<String>,
14
pub repeat: Repeat,
15
}
16
17
impl From<&NewEvent> for GoogleEventDraft {
18
fn from(event: &NewEvent) -> Self {
19
GoogleEventDraft {
20
subject: event.subject.clone(),
21
start: event.start,
22
end: event.end,
23
attendees: event.attendees.clone(),
24
details: event.details.clone(),
25
join_url: None,
26
repeat: event.repeat,
27
}
28
}
29
}
30
31
pub fn rrule_for_repeat(repeat: Repeat, start: chrono::DateTime<chrono::Utc>) -> Option<String> {
32
match repeat {
33
Repeat::Never => None,
34
Repeat::Daily => Some("RRULE:FREQ=DAILY".to_owned()),
35
Repeat::Weekdays => Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR".to_owned()),
36
Repeat::Weekly => {
37
let day = match start.weekday() {
38
chrono::Weekday::Mon => "MO",
39
chrono::Weekday::Tue => "TU",
40
chrono::Weekday::Wed => "WE",
41
chrono::Weekday::Thu => "TH",
42
chrono::Weekday::Fri => "FR",
43
chrono::Weekday::Sat => "SA",
44
chrono::Weekday::Sun => "SU",
45
};
46
Some(format!("RRULE:FREQ=WEEKLY;BYDAY={day}"))
47
}
48
}
49
}
50
51
pub fn google_event_body(draft: &GoogleEventDraft) -> Value {
52
let mut description = draft.details.clone();
53
if let Some(join_url) = &draft.join_url {
54
if !description.is_empty() {
55
description.push_str("\n\n");
56
}
57
description.push_str(join_url);
58
}
59
let mut body = json!({
60
"summary": draft.subject,
61
"start": {
62
"dateTime": draft.start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
63
"timeZone": "UTC",
64
},
65
"end": {
66
"dateTime": draft.end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
67
"timeZone": "UTC",
68
},
69
"attendees": draft.attendees.iter().map(|attendee| json!({
70
"email": attendee.address,
71
"displayName": attendee.name,
72
})).collect::<Vec<_>>(),
73
});
74
if let Some(join_url) = &draft.join_url {
75
body["location"] = json!(join_url);
76
}
77
if !description.is_empty() {
78
body["description"] = json!(description);
79
}
80
if let Some(rrule) = rrule_for_repeat(draft.repeat, draft.start) {
81
body["recurrence"] = json!([rrule]);
82
}
83
let _ = (draft.start.hour(), draft.start.minute());
84
body
85
}
86
87
pub fn google_rsvp_status(reply: Reply) -> &'static str {
88
match reply {
89
Reply::Accept => "accepted",
90
Reply::Tentative => "tentative",
91
Reply::Decline => "declined",
92
}
93
}
94
95
pub fn google_rsvp_query(send_updates: bool) -> String {
96
format!("sendUpdates={}", if send_updates { "all" } else { "none" })
97
}
98
99
#[cfg(test)]
100
mod tests {
101
use chrono::TimeZone;
102
103
use super::*;
104
105
fn draft(repeat: Repeat) -> GoogleEventDraft {
106
GoogleEventDraft {
107
subject: "Sync".into(),
108
start: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap(),
109
end: chrono::Utc
110
.with_ymd_and_hms(2026, 11, 11, 9, 30, 0)
111
.unwrap(),
112
attendees: vec![Attendee {
113
name: "Mara".into(),
114
address: "mara@example.com".into(),
115
}],
116
details: "Notes".into(),
117
join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
118
repeat,
119
}
120
}
121
122
#[test]
123
fn body_puts_join_link_in_location_and_description() {
124
let body = google_event_body(&draft(Repeat::Never));
125
assert_eq!(
126
body["location"],
127
"https://teams.microsoft.com/l/meetup-join/x"
128
);
129
assert!(
130
body["description"]
131
.as_str()
132
.unwrap()
133
.contains("teams.microsoft.com")
134
);
135
assert!(body.get("recurrence").is_none());
136
}
137
138
#[test]
139
fn weekdays_rrule_and_rsvp_query() {
140
assert_eq!(
141
rrule_for_repeat(
142
Repeat::Weekdays,
143
chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap()
144
)
145
.as_deref(),
146
Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR")
147
);
148
assert_eq!(google_rsvp_status(Reply::Decline), "declined");
149
assert_eq!(google_rsvp_query(true), "sendUpdates=all");
150
assert_eq!(google_rsvp_query(false), "sendUpdates=none");
151
}
152
}
@@ -0,0 +1,152 @@1
use chrono::{Datelike, Timelike};2
use serde_json::{Value, json};3
4
use crate::calendar::{Attendee, NewEvent, Repeat, Reply};5
6
#[derive(Debug, Clone, PartialEq, Eq)]7
pub struct GoogleEventDraft {8
pub subject: String,9
pub start: chrono::DateTime<chrono::Utc>,10
pub end: chrono::DateTime<chrono::Utc>,11
pub attendees: Vec<Attendee>,12
pub details: String,13
pub join_url: Option<String>,14
pub repeat: Repeat,15
}16
17
impl From<&NewEvent> for GoogleEventDraft {18
fn from(event: &NewEvent) -> Self {19
GoogleEventDraft {20
subject: event.subject.clone(),21
start: event.start,22
end: event.end,23
attendees: event.attendees.clone(),24
details: event.details.clone(),25
join_url: None,26
repeat: event.repeat,27
}28
}29
}30
31
pub fn rrule_for_repeat(repeat: Repeat, start: chrono::DateTime<chrono::Utc>) -> Option<String> {32
match repeat {33
Repeat::Never => None,34
Repeat::Daily => Some("RRULE:FREQ=DAILY".to_owned()),35
Repeat::Weekdays => Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR".to_owned()),36
Repeat::Weekly => {37
let day = match start.weekday() {38
chrono::Weekday::Mon => "MO",39
chrono::Weekday::Tue => "TU",40
chrono::Weekday::Wed => "WE",41
chrono::Weekday::Thu => "TH",42
chrono::Weekday::Fri => "FR",43
chrono::Weekday::Sat => "SA",44
chrono::Weekday::Sun => "SU",45
};46
Some(format!("RRULE:FREQ=WEEKLY;BYDAY={day}"))47
}48
}49
}50
51
pub fn google_event_body(draft: &GoogleEventDraft) -> Value {52
let mut description = draft.details.clone();53
if let Some(join_url) = &draft.join_url {54
if !description.is_empty() {55
description.push_str("\n\n");56
}57
description.push_str(join_url);58
}59
let mut body = json!({60
"summary": draft.subject,61
"start": {62
"dateTime": draft.start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),63
"timeZone": "UTC",64
},65
"end": {66
"dateTime": draft.end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),67
"timeZone": "UTC",68
},69
"attendees": draft.attendees.iter().map(|attendee| json!({70
"email": attendee.address,71
"displayName": attendee.name,72
})).collect::<Vec<_>>(),73
});74
if let Some(join_url) = &draft.join_url {75
body["location"] = json!(join_url);76
}77
if !description.is_empty() {78
body["description"] = json!(description);79
}80
if let Some(rrule) = rrule_for_repeat(draft.repeat, draft.start) {81
body["recurrence"] = json!([rrule]);82
}83
let _ = (draft.start.hour(), draft.start.minute());84
body85
}86
87
pub fn google_rsvp_status(reply: Reply) -> &'static str {88
match reply {89
Reply::Accept => "accepted",90
Reply::Tentative => "tentative",91
Reply::Decline => "declined",92
}93
}94
95
pub fn google_rsvp_query(send_updates: bool) -> String {96
format!("sendUpdates={}", if send_updates { "all" } else { "none" })97
}98
99
#[cfg(test)]100
mod tests {101
use chrono::TimeZone;102
103
use super::*;104
105
fn draft(repeat: Repeat) -> GoogleEventDraft {106
GoogleEventDraft {107
subject: "Sync".into(),108
start: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap(),109
end: chrono::Utc110
.with_ymd_and_hms(2026, 11, 11, 9, 30, 0)111
.unwrap(),112
attendees: vec![Attendee {113
name: "Mara".into(),114
address: "mara@example.com".into(),115
}],116
details: "Notes".into(),117
join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),118
repeat,119
}120
}121
122
#[test]123
fn body_puts_join_link_in_location_and_description() {124
let body = google_event_body(&draft(Repeat::Never));125
assert_eq!(126
body["location"],127
"https://teams.microsoft.com/l/meetup-join/x"128
);129
assert!(130
body["description"]131
.as_str()132
.unwrap()133
.contains("teams.microsoft.com")134
);135
assert!(body.get("recurrence").is_none());136
}137
138
#[test]139
fn weekdays_rrule_and_rsvp_query() {140
assert_eq!(141
rrule_for_repeat(142
Repeat::Weekdays,143
chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap()144
)145
.as_deref(),146
Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR")147
);148
assert_eq!(google_rsvp_status(Reply::Decline), "declined");149
assert_eq!(google_rsvp_query(true), "sendUpdates=all");150
assert_eq!(google_rsvp_query(false), "sendUpdates=none");151
}152
}@@ -10,6 +10,7 @@ chrono.workspace = true
10
10
directories.workspace = true
11
11
rusqlite.workspace = true
12
12
scraper.workspace = true
13
serde = { workspace = true, features = ["derive"] }
13
14
serde_json.workspace = true
14
15
thiserror.workspace = true
15
16
@@ -10,6 +10,7 @@ chrono.workspace = true10
directories.workspace = true10
directories.workspace = true11
rusqlite.workspace = true11
rusqlite.workspace = true12
scraper.workspace = true12
scraper.workspace = true13
serde = { workspace = true, features = ["derive"] }13
serde_json.workspace = true14
serde_json.workspace = true14
thiserror.workspace = true15
thiserror.workspace = true15
16
@@ -0,0 +1,242 @@
1
use serde::{Deserialize, Serialize};
2
use serde_json::json;
3
4
use crate::error::Result;
5
use crate::store::Store;
6
7
pub const CALENDAR_ACCOUNTS_KEY: &str = "calendar.accounts";
8
9
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
10
#[serde(rename_all = "snake_case")]
11
pub enum CalendarProvider {
12
#[default]
13
Outlook,
14
Google,
15
}
16
17
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18
pub struct CalendarRef {
19
pub provider: CalendarProvider,
20
/// Stable account id (empty for the single Outlook mailbox).
21
#[serde(default)]
22
pub account_id: String,
23
/// Provider calendar id (`primary` for Google default, empty for Outlook).
24
#[serde(default)]
25
pub calendar_id: String,
26
}
27
28
impl CalendarRef {
29
pub fn outlook() -> Self {
30
CalendarRef {
31
provider: CalendarProvider::Outlook,
32
account_id: String::new(),
33
calendar_id: String::new(),
34
}
35
}
36
37
pub fn google(account_id: impl Into<String>, calendar_id: impl Into<String>) -> Self {
38
CalendarRef {
39
provider: CalendarProvider::Google,
40
account_id: account_id.into(),
41
calendar_id: calendar_id.into(),
42
}
43
}
44
45
pub fn key(&self) -> String {
46
format!(
47
"{}:{}:{}",
48
match self.provider {
49
CalendarProvider::Outlook => "outlook",
50
CalendarProvider::Google => "google",
51
},
52
self.account_id,
53
self.calendar_id
54
)
55
}
56
}
57
58
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59
pub struct GoogleCalendarInfo {
60
pub id: String,
61
pub summary: String,
62
#[serde(default = "default_true")]
63
pub selected: bool,
64
#[serde(default)]
65
pub primary: bool,
66
}
67
68
fn default_true() -> bool {
69
true
70
}
71
72
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
73
pub struct GoogleTokenSet {
74
#[serde(default)]
75
pub access_token: String,
76
#[serde(default)]
77
pub refresh_token: String,
78
/// Unix seconds when the access token expires.
79
#[serde(default)]
80
pub expires_at: i64,
81
}
82
83
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84
pub struct GoogleAccount {
85
pub id: String,
86
#[serde(default)]
87
pub email: String,
88
#[serde(default)]
89
pub calendars: Vec<GoogleCalendarInfo>,
90
#[serde(default)]
91
pub tokens: GoogleTokenSet,
92
}
93
94
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95
pub struct CalendarAccounts {
96
#[serde(default = "CalendarRef::outlook")]
97
pub home: CalendarRef,
98
/// Extra write targets beyond home (may include Google calendars).
99
#[serde(default)]
100
pub write_targets: Vec<CalendarRef>,
101
/// Show Outlook mailbox events in the calendar grid.
102
#[serde(default = "default_true")]
103
pub outlook_selected: bool,
104
#[serde(default)]
105
pub google_accounts: Vec<GoogleAccount>,
106
}
107
108
impl Default for CalendarAccounts {
109
fn default() -> Self {
110
CalendarAccounts {
111
home: CalendarRef::outlook(),
112
write_targets: Vec::new(),
113
outlook_selected: true,
114
google_accounts: Vec::new(),
115
}
116
}
117
}
118
119
impl CalendarAccounts {
120
pub fn from_json(text: &str) -> std::result::Result<Self, serde_json::Error> {
121
serde_json::from_str(text)
122
}
123
124
pub fn to_json(&self) -> String {
125
serde_json::to_string(self).unwrap_or_else(|_| json!({}).to_string())
126
}
127
128
pub fn has_google(&self) -> bool {
129
!self.google_accounts.is_empty()
130
}
131
132
pub fn google_account(&self, id: &str) -> Option<&GoogleAccount> {
133
self.google_accounts.iter().find(|account| account.id == id)
134
}
135
136
pub fn google_account_mut(&mut self, id: &str) -> Option<&mut GoogleAccount> {
137
self.google_accounts
138
.iter_mut()
139
.find(|account| account.id == id)
140
}
141
142
pub fn disconnect_google(&mut self, account_id: &str) {
143
self.google_accounts
144
.retain(|account| account.id != account_id);
145
if self.home.provider == CalendarProvider::Google && self.home.account_id == account_id {
146
self.home = CalendarRef::outlook();
147
}
148
self.write_targets.retain(|target| {
149
!(target.provider == CalendarProvider::Google && target.account_id == account_id)
150
});
151
}
152
153
/// Home plus extra write targets, de-duplicated by key.
154
pub fn resolved_write_targets(&self) -> Vec<CalendarRef> {
155
let mut targets = vec![self.home.clone()];
156
for target in &self.write_targets {
157
if targets
158
.iter()
159
.all(|existing| existing.key() != target.key())
160
{
161
targets.push(target.clone());
162
}
163
}
164
targets
165
}
166
}
167
168
pub fn load_calendar_accounts(store: &Store) -> CalendarAccounts {
169
store
170
.meta(CALENDAR_ACCOUNTS_KEY)
171
.ok()
172
.flatten()
173
.and_then(|json| CalendarAccounts::from_json(&json).ok())
174
.unwrap_or_default()
175
}
176
177
pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Result<()> {
178
store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())
179
}
180
181
#[cfg(test)]
182
mod tests {
183
use super::*;
184
use crate::store::Store;
185
use tempfile::tempdir;
186
187
#[test]
188
fn defaults_to_outlook_home() {
189
let accounts = CalendarAccounts::default();
190
assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
191
assert!(accounts.write_targets.is_empty());
192
assert!(!accounts.has_google());
193
}
194
195
#[test]
196
fn roundtrips_through_store_meta() {
197
let directory = tempdir().unwrap();
198
let store = Store::open(&directory.path().join("db.sqlite")).unwrap();
199
let mut accounts = CalendarAccounts::default();
200
accounts.google_accounts.push(GoogleAccount {
201
id: "g1".into(),
202
email: "joe@example.com".into(),
203
calendars: vec![GoogleCalendarInfo {
204
id: "primary".into(),
205
summary: "Joe".into(),
206
selected: true,
207
primary: true,
208
}],
209
tokens: GoogleTokenSet {
210
access_token: "access".into(),
211
refresh_token: "refresh".into(),
212
expires_at: 1,
213
},
214
});
215
accounts.home = CalendarRef::google("g1", "primary");
216
accounts.write_targets.push(CalendarRef::outlook());
217
save_calendar_accounts(&store, &accounts).unwrap();
218
let loaded = load_calendar_accounts(&store);
219
assert_eq!(loaded.home, accounts.home);
220
assert_eq!(loaded.google_accounts[0].email, "joe@example.com");
221
assert_eq!(loaded.resolved_write_targets().len(), 2);
222
}
223
224
#[test]
225
fn disconnect_clears_home_and_write_targets() {
226
let mut accounts = CalendarAccounts {
227
home: CalendarRef::google("g1", "primary"),
228
write_targets: vec![CalendarRef::google("g1", "work")],
229
outlook_selected: true,
230
google_accounts: vec![GoogleAccount {
231
id: "g1".into(),
232
email: "a@b.c".into(),
233
calendars: Vec::new(),
234
tokens: GoogleTokenSet::default(),
235
}],
236
};
237
accounts.disconnect_google("g1");
238
assert!(!accounts.has_google());
239
assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
240
assert!(accounts.write_targets.is_empty());
241
}
242
}
@@ -0,0 +1,242 @@1
use serde::{Deserialize, Serialize};2
use serde_json::json;3
4
use crate::error::Result;5
use crate::store::Store;6
7
pub const CALENDAR_ACCOUNTS_KEY: &str = "calendar.accounts";8
9
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]10
#[serde(rename_all = "snake_case")]11
pub enum CalendarProvider {12
#[default]13
Outlook,14
Google,15
}16
17
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]18
pub struct CalendarRef {19
pub provider: CalendarProvider,20
/// Stable account id (empty for the single Outlook mailbox).21
#[serde(default)]22
pub account_id: String,23
/// Provider calendar id (`primary` for Google default, empty for Outlook).24
#[serde(default)]25
pub calendar_id: String,26
}27
28
impl CalendarRef {29
pub fn outlook() -> Self {30
CalendarRef {31
provider: CalendarProvider::Outlook,32
account_id: String::new(),33
calendar_id: String::new(),34
}35
}36
37
pub fn google(account_id: impl Into<String>, calendar_id: impl Into<String>) -> Self {38
CalendarRef {39
provider: CalendarProvider::Google,40
account_id: account_id.into(),41
calendar_id: calendar_id.into(),42
}43
}44
45
pub fn key(&self) -> String {46
format!(47
"{}:{}:{}",48
match self.provider {49
CalendarProvider::Outlook => "outlook",50
CalendarProvider::Google => "google",51
},52
self.account_id,53
self.calendar_id54
)55
}56
}57
58
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]59
pub struct GoogleCalendarInfo {60
pub id: String,61
pub summary: String,62
#[serde(default = "default_true")]63
pub selected: bool,64
#[serde(default)]65
pub primary: bool,66
}67
68
fn default_true() -> bool {69
true70
}71
72
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]73
pub struct GoogleTokenSet {74
#[serde(default)]75
pub access_token: String,76
#[serde(default)]77
pub refresh_token: String,78
/// Unix seconds when the access token expires.79
#[serde(default)]80
pub expires_at: i64,81
}82
83
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]84
pub struct GoogleAccount {85
pub id: String,86
#[serde(default)]87
pub email: String,88
#[serde(default)]89
pub calendars: Vec<GoogleCalendarInfo>,90
#[serde(default)]91
pub tokens: GoogleTokenSet,92
}93
94
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]95
pub struct CalendarAccounts {96
#[serde(default = "CalendarRef::outlook")]97
pub home: CalendarRef,98
/// Extra write targets beyond home (may include Google calendars).99
#[serde(default)]100
pub write_targets: Vec<CalendarRef>,101
/// Show Outlook mailbox events in the calendar grid.102
#[serde(default = "default_true")]103
pub outlook_selected: bool,104
#[serde(default)]105
pub google_accounts: Vec<GoogleAccount>,106
}107
108
impl Default for CalendarAccounts {109
fn default() -> Self {110
CalendarAccounts {111
home: CalendarRef::outlook(),112
write_targets: Vec::new(),113
outlook_selected: true,114
google_accounts: Vec::new(),115
}116
}117
}118
119
impl CalendarAccounts {120
pub fn from_json(text: &str) -> std::result::Result<Self, serde_json::Error> {121
serde_json::from_str(text)122
}123
124
pub fn to_json(&self) -> String {125
serde_json::to_string(self).unwrap_or_else(|_| json!({}).to_string())126
}127
128
pub fn has_google(&self) -> bool {129
!self.google_accounts.is_empty()130
}131
132
pub fn google_account(&self, id: &str) -> Option<&GoogleAccount> {133
self.google_accounts.iter().find(|account| account.id == id)134
}135
136
pub fn google_account_mut(&mut self, id: &str) -> Option<&mut GoogleAccount> {137
self.google_accounts138
.iter_mut()139
.find(|account| account.id == id)140
}141
142
pub fn disconnect_google(&mut self, account_id: &str) {143
self.google_accounts144
.retain(|account| account.id != account_id);145
if self.home.provider == CalendarProvider::Google && self.home.account_id == account_id {146
self.home = CalendarRef::outlook();147
}148
self.write_targets.retain(|target| {149
!(target.provider == CalendarProvider::Google && target.account_id == account_id)150
});151
}152
153
/// Home plus extra write targets, de-duplicated by key.154
pub fn resolved_write_targets(&self) -> Vec<CalendarRef> {155
let mut targets = vec![self.home.clone()];156
for target in &self.write_targets {157
if targets158
.iter()159
.all(|existing| existing.key() != target.key())160
{161
targets.push(target.clone());162
}163
}164
targets165
}166
}167
168
pub fn load_calendar_accounts(store: &Store) -> CalendarAccounts {169
store170
.meta(CALENDAR_ACCOUNTS_KEY)171
.ok()172
.flatten()173
.and_then(|json| CalendarAccounts::from_json(&json).ok())174
.unwrap_or_default()175
}176
177
pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Result<()> {178
store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())179
}180
181
#[cfg(test)]182
mod tests {183
use super::*;184
use crate::store::Store;185
use tempfile::tempdir;186
187
#[test]188
fn defaults_to_outlook_home() {189
let accounts = CalendarAccounts::default();190
assert_eq!(accounts.home.provider, CalendarProvider::Outlook);191
assert!(accounts.write_targets.is_empty());192
assert!(!accounts.has_google());193
}194
195
#[test]196
fn roundtrips_through_store_meta() {197
let directory = tempdir().unwrap();198
let store = Store::open(&directory.path().join("db.sqlite")).unwrap();199
let mut accounts = CalendarAccounts::default();200
accounts.google_accounts.push(GoogleAccount {201
id: "g1".into(),202
email: "joe@example.com".into(),203
calendars: vec![GoogleCalendarInfo {204
id: "primary".into(),205
summary: "Joe".into(),206
selected: true,207
primary: true,208
}],209
tokens: GoogleTokenSet {210
access_token: "access".into(),211
refresh_token: "refresh".into(),212
expires_at: 1,213
},214
});215
accounts.home = CalendarRef::google("g1", "primary");216
accounts.write_targets.push(CalendarRef::outlook());217
save_calendar_accounts(&store, &accounts).unwrap();218
let loaded = load_calendar_accounts(&store);219
assert_eq!(loaded.home, accounts.home);220
assert_eq!(loaded.google_accounts[0].email, "joe@example.com");221
assert_eq!(loaded.resolved_write_targets().len(), 2);222
}223
224
#[test]225
fn disconnect_clears_home_and_write_targets() {226
let mut accounts = CalendarAccounts {227
home: CalendarRef::google("g1", "primary"),228
write_targets: vec![CalendarRef::google("g1", "work")],229
outlook_selected: true,230
google_accounts: vec![GoogleAccount {231
id: "g1".into(),232
email: "a@b.c".into(),233
calendars: Vec::new(),234
tokens: GoogleTokenSet::default(),235
}],236
};237
accounts.disconnect_google("g1");238
assert!(!accounts.has_google());239
assert_eq!(accounts.home.provider, CalendarProvider::Outlook);240
assert!(accounts.write_targets.is_empty());241
}242
}