BlueGit

ict rusty-teams

feat(calendar): CalDAV accounts, ICS subscriptions, settings layout

Add generic CalDAV (keyring app passwords, discovery, R/W, series) and
read-only ICS on a shared iCalendar core. Split Calendar settings into
view vs accounts and fix stacked credential fields.

metis Joachim Mild · pushed by metis

Authored 2026-11-16 · 2 weeks ago

Hash
78c6539ef34d235270d58c8168beee77ba77ee44
Parent
6617aeaa
46 files changed +3616 −254
Cargo.lock +68 −2
@@ -384,9 +384,11 @@ dependencies = [
384 384 "gpui-kit",
385 385 "graph",
386 386 "image",
387 "keyring",
387 388 "log",
388 389 "mcp",
389 390 "regex",
391 "reqwest 0.13.5",
390 392 "serde",
391 393 "serde_json",
392 394 "session",
@@ -394,6 +396,7 @@ dependencies = [
394 396 "teams-core",
395 397 "tempfile",
396 398 "tokio",
399 "url",
397 400 "uuid",
398 401 "webview",
399 402 ]
@@ -1376,11 +1379,14 @@ version = "0.4.0"
1376 1379 dependencies = [
1377 1380 "base64 0.22.1",
1378 1381 "chrono",
1382 "chrono-tz",
1379 1383 "futures-util",
1380 1384 "iana-time-zone",
1381 1385 "percent-encoding",
1386 "quick-xml 0.37.5",
1382 1387 "rand 0.9.5",
1383 1388 "reqwest 0.13.5",
1389 "rrule",
1384 1390 "serde",
1385 1391 "serde_json",
1386 1392 "session",
@@ -1406,6 +1412,16 @@ dependencies = [
1406 1412 "windows-link 0.2.1",
1407 1413 ]
1408 1414
1415 [[package]]
1416 name = "chrono-tz"
1417 version = "0.10.4"
1418 source = "registry+https://github.com/rust-lang/crates.io-index"
1419 checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
1420 dependencies = [
1421 "chrono",
1422 "phf 0.12.1",
1423 ]
1424
1409 1425 [[package]]
1410 1426 name = "cipher"
1411 1427 version = "0.4.4"
@@ -5004,6 +5020,16 @@ dependencies = [
5004 5020 "unicode-segmentation",
5005 5021 ]
5006 5022
5023 [[package]]
5024 name = "keyring"
5025 version = "3.6.3"
5026 source = "registry+https://github.com/rust-lang/crates.io-index"
5027 checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
5028 dependencies = [
5029 "log",
5030 "zeroize",
5031 ]
5032
5007 5033 [[package]]
5008 5034 name = "khronos-egl"
5009 5035 version = "6.0.0"
@@ -6768,6 +6794,15 @@ dependencies = [
6768 6794 "phf_shared 0.11.3",
6769 6795 ]
6770 6796
6797 [[package]]
6798 name = "phf"
6799 version = "0.12.1"
6800 source = "registry+https://github.com/rust-lang/crates.io-index"
6801 checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
6802 dependencies = [
6803 "phf_shared 0.12.1",
6804 ]
6805
6771 6806 [[package]]
6772 6807 name = "phf"
6773 6808 version = "0.13.1"
@@ -6844,6 +6879,15 @@ dependencies = [
6844 6879 "siphasher",
6845 6880 ]
6846 6881
6882 [[package]]
6883 name = "phf_shared"
6884 version = "0.12.1"
6885 source = "registry+https://github.com/rust-lang/crates.io-index"
6886 checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
6887 dependencies = [
6888 "siphasher",
6889 ]
6890
6847 6891 [[package]]
6848 6892 name = "phf_shared"
6849 6893 version = "0.13.1"
@@ -7235,6 +7279,15 @@ version = "2.0.1"
7235 7279 source = "registry+https://github.com/rust-lang/crates.io-index"
7236 7280 checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
7237 7281
7282 [[package]]
7283 name = "quick-xml"
7284 version = "0.37.5"
7285 source = "registry+https://github.com/rust-lang/crates.io-index"
7286 checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
7287 dependencies = [
7288 "memchr",
7289 ]
7290
7238 7291 [[package]]
7239 7292 name = "quick-xml"
7240 7293 version = "0.41.0"
@@ -7884,6 +7937,19 @@ dependencies = [
7884 7937 "memchr",
7885 7938 ]
7886 7939
7940 [[package]]
7941 name = "rrule"
7942 version = "0.14.0"
7943 source = "registry+https://github.com/rust-lang/crates.io-index"
7944 checksum = "720acfb4980b9d8a6a430f6d7a11933e701ebbeba5eee39cc9d8c5f932aaff74"
7945 dependencies = [
7946 "chrono",
7947 "chrono-tz",
7948 "log",
7949 "regex",
7950 "thiserror 2.0.21",
7951 ]
7952
7887 7953 [[package]]
7888 7954 name = "rtrb"
7889 7955 version = "0.3.5"
@@ -10533,7 +10599,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
10533 10599 checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
10534 10600 dependencies = [
10535 10601 "proc-macro2",
10536 "quick-xml",
10602 "quick-xml 0.41.0",
10537 10603 "quote",
10538 10604 ]
10539 10605
@@ -11660,7 +11726,7 @@ checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566"
11660 11726 dependencies = [
11661 11727 "bitflags 2.13.2",
11662 11728 "libc",
11663 "quick-xml",
11729 "quick-xml 0.41.0",
11664 11730 "x11",
11665 11731 ]
11666 11732
@@ -384,9 +384,11 @@ dependencies = [
384 "gpui-kit",
384 "gpui-kit",
385 "graph",
385 "graph",
386 "image",
386 "image",
387 "keyring",
387 "log",
388 "log",
388 "mcp",
389 "mcp",
389 "regex",
390 "regex",
391 "reqwest 0.13.5",
390 "serde",
392 "serde",
391 "serde_json",
393 "serde_json",
392 "session",
394 "session",
@@ -394,6 +396,7 @@ dependencies = [
394 "teams-core",
396 "teams-core",
395 "tempfile",
397 "tempfile",
396 "tokio",
398 "tokio",
399 "url",
397 "uuid",
400 "uuid",
398 "webview",
401 "webview",
399]
402]
@@ -1376,11 +1379,14 @@ version = "0.4.0"
1376dependencies = [
1379dependencies = [
1377 "base64 0.22.1",
1380 "base64 0.22.1",
1378 "chrono",
1381 "chrono",
1382 "chrono-tz",
1379 "futures-util",
1383 "futures-util",
1380 "iana-time-zone",
1384 "iana-time-zone",
1381 "percent-encoding",
1385 "percent-encoding",
1386 "quick-xml 0.37.5",
1382 "rand 0.9.5",
1387 "rand 0.9.5",
1383 "reqwest 0.13.5",
1388 "reqwest 0.13.5",
1389 "rrule",
1384 "serde",
1390 "serde",
1385 "serde_json",
1391 "serde_json",
1386 "session",
1392 "session",
@@ -1406,6 +1412,16 @@ dependencies = [
1406 "windows-link 0.2.1",
1412 "windows-link 0.2.1",
1407]
1413]
1408
1414
1415[[package]]
1416name = "chrono-tz"
1417version = "0.10.4"
1418source = "registry+https://github.com/rust-lang/crates.io-index"
1419checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
1420dependencies = [
1421 "chrono",
1422 "phf 0.12.1",
1423]
1424
1409[[package]]
1425[[package]]
1410name = "cipher"
1426name = "cipher"
1411version = "0.4.4"
1427version = "0.4.4"
@@ -5004,6 +5020,16 @@ dependencies = [
5004 "unicode-segmentation",
5020 "unicode-segmentation",
5005]
5021]
5006
5022
5023[[package]]
5024name = "keyring"
5025version = "3.6.3"
5026source = "registry+https://github.com/rust-lang/crates.io-index"
5027checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
5028dependencies = [
5029 "log",
5030 "zeroize",
5031]
5032
5007[[package]]
5033[[package]]
5008name = "khronos-egl"
5034name = "khronos-egl"
5009version = "6.0.0"
5035version = "6.0.0"
@@ -6768,6 +6794,15 @@ dependencies = [
6768 "phf_shared 0.11.3",
6794 "phf_shared 0.11.3",
6769]
6795]
6770
6796
6797[[package]]
6798name = "phf"
6799version = "0.12.1"
6800source = "registry+https://github.com/rust-lang/crates.io-index"
6801checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
6802dependencies = [
6803 "phf_shared 0.12.1",
6804]
6805
6771[[package]]
6806[[package]]
6772name = "phf"
6807name = "phf"
6773version = "0.13.1"
6808version = "0.13.1"
@@ -6844,6 +6879,15 @@ dependencies = [
6844 "siphasher",
6879 "siphasher",
6845]
6880]
6846
6881
6882[[package]]
6883name = "phf_shared"
6884version = "0.12.1"
6885source = "registry+https://github.com/rust-lang/crates.io-index"
6886checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
6887dependencies = [
6888 "siphasher",
6889]
6890
6847[[package]]
6891[[package]]
6848name = "phf_shared"
6892name = "phf_shared"
6849version = "0.13.1"
6893version = "0.13.1"
@@ -7235,6 +7279,15 @@ version = "2.0.1"
7235source = "registry+https://github.com/rust-lang/crates.io-index"
7279source = "registry+https://github.com/rust-lang/crates.io-index"
7236checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
7280checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
7237
7281
7282[[package]]
7283name = "quick-xml"
7284version = "0.37.5"
7285source = "registry+https://github.com/rust-lang/crates.io-index"
7286checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
7287dependencies = [
7288 "memchr",
7289]
7290
7238[[package]]
7291[[package]]
7239name = "quick-xml"
7292name = "quick-xml"
7240version = "0.41.0"
7293version = "0.41.0"
@@ -7884,6 +7937,19 @@ dependencies = [
7884 "memchr",
7937 "memchr",
7885]
7938]
7886
7939
7940[[package]]
7941name = "rrule"
7942version = "0.14.0"
7943source = "registry+https://github.com/rust-lang/crates.io-index"
7944checksum = "720acfb4980b9d8a6a430f6d7a11933e701ebbeba5eee39cc9d8c5f932aaff74"
7945dependencies = [
7946 "chrono",
7947 "chrono-tz",
7948 "log",
7949 "regex",
7950 "thiserror 2.0.21",
7951]
7952
7887[[package]]
7953[[package]]
7888name = "rtrb"
7954name = "rtrb"
7889version = "0.3.5"
7955version = "0.3.5"
@@ -10533,7 +10599,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
10533checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
10599checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
10534dependencies = [
10600dependencies = [
10535 "proc-macro2",
10601 "proc-macro2",
10536 "quick-xml",
10602 "quick-xml 0.41.0",
10537 "quote",
10603 "quote",
10538]
10604]
10539
10605
@@ -11660,7 +11726,7 @@ checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566"
11660dependencies = [
11726dependencies = [
11661 "bitflags 2.13.2",
11727 "bitflags 2.13.2",
11662 "libc",
11728 "libc",
11663 "quick-xml",
11729 "quick-xml 0.41.0",
11664 "x11",
11730 "x11",
11665]
11731]
11666
11732
crates/app-base/locales/app.yml +72 −6
@@ -106,6 +106,9 @@ settings:
106 106 calendar:
107 107 en: Calendar
108 108 de: Kalender
109 calendar_accounts:
110 en: Calendar accounts
111 de: Kalenderkonten
109 112 devices:
110 113 en: Devices
111 114 de: Geräte
@@ -262,6 +265,12 @@ settings:
262 265 section_google:
263 266 en: GOOGLE
264 267 de: GOOGLE
268 section_caldav:
269 en: CALDAV
270 de: CALDAV
271 section_ics:
272 en: ICS SUBSCRIPTIONS
273 de: ICS-ABOS
265 274 section_home:
266 275 en: HOME CALENDAR
267 276 de: HAUPTKALENDER
@@ -271,6 +280,63 @@ settings:
271 280 google_title:
272 281 en: Google Calendar
273 282 de: Google Kalender
283 caldav_title:
284 en: CalDAV calendar
285 de: CalDAV-Kalender
286 caldav_url:
287 en: Server URL
288 de: Server-URL
289 caldav_username:
290 en: Username
291 de: Benutzername
292 caldav_password:
293 en: App password
294 de: App-Passwort
295 caldav_connect:
296 en: Connect CalDAV
297 de: CalDAV verbinden
298 caldav_hint:
299 en: Use an app password. Templates fill a typical URL for Nextcloud, Fastmail, or iCloud.
300 de: Nutzen Sie ein App-Passwort. Vorlagen setzen eine typische URL für Nextcloud, Fastmail oder iCloud.
301 caldav_template_nextcloud:
302 en: Nextcloud
303 de: Nextcloud
304 caldav_template_fastmail:
305 en: Fastmail
306 de: Fastmail
307 caldav_template_icloud:
308 en: iCloud
309 de: iCloud
310 caldav_connected:
311 en: CalDAV account connected
312 de: CalDAV-Konto verbunden
313 caldav_connect_failed:
314 en: CalDAV connect failed
315 de: CalDAV-Verbindung fehlgeschlagen
316 caldav_readonly:
317 en: Read-only
318 de: Nur lesen
319 ics_title:
320 en: ICS subscription
321 de: ICS-Abo
322 ics_url:
323 en: ICS URL
324 de: ICS-URL
325 ics_name:
326 en: Display name
327 de: Anzeigename
328 ics_connect:
329 en: Add subscription
330 de: Abo hinzufügen
331 ics_hint:
332 en: Read-only. For holidays or shared calendar links (including Proton share links).
333 de: Nur lesen. Für Feiertage oder geteilte Kalenderlinks (auch Proton-Share-Links).
334 ics_connected:
335 en: ICS subscription added
336 de: ICS-Abo hinzugefügt
337 ics_connect_failed:
338 en: ICS subscription failed
339 de: ICS-Abo fehlgeschlagen
274 340 connect_button:
275 341 en: Connect Google
276 342 de: Google verbinden
@@ -308,17 +374,17 @@ settings:
308 374 en: Outlook (Microsoft mailbox)
309 375 de: Outlook (Microsoft-Postfach)
310 376 dual_write_when_google_home:
311 en: Dual-write when home is Google
312 de: Zusätzlich schreiben, wenn der Hauptkalender Google ist
377 en: Also write when home is not Outlook
378 de: Zusätzlich schreiben, wenn der Hauptkalender nicht Outlook ist
313 379 outlook_home_detail:
314 en: Default when no Google home is chosen
315 de: Standard, wenn kein Google-Hauptkalender gewählt ist
380 en: Default when no other home calendar is chosen
381 de: Standard, wenn kein anderer Hauptkalender gewählt ist
316 382 no_extra_targets:
317 383 en: No extra write targets
318 384 de: Keine weiteren Schreibziele
319 385 connect_then_dual_write:
320 en: Connect Google, then enable dual-write on a calendar above.
321 de: Google verbinden, dann oben Dual-Write für einen Kalender einschalten.
386 en: Connect another account, then enable dual-write on a calendar above.
387 de: Weiteres Konto verbinden, dann oben Dual-Write für einen Kalender einschalten.
322 388 section_view:
323 389 en: VIEW
324 390 de: ANSICHT
@@ -106,6 +106,9 @@ settings:
106 calendar:
106 calendar:
107 en: Calendar
107 en: Calendar
108 de: Kalender
108 de: Kalender
109 calendar_accounts:
110 en: Calendar accounts
111 de: Kalenderkonten
109 devices:
112 devices:
110 en: Devices
113 en: Devices
111 de: Geräte
114 de: Geräte
@@ -262,6 +265,12 @@ settings:
262 section_google:
265 section_google:
263 en: GOOGLE
266 en: GOOGLE
264 de: GOOGLE
267 de: GOOGLE
268 section_caldav:
269 en: CALDAV
270 de: CALDAV
271 section_ics:
272 en: ICS SUBSCRIPTIONS
273 de: ICS-ABOS
265 section_home:
274 section_home:
266 en: HOME CALENDAR
275 en: HOME CALENDAR
267 de: HAUPTKALENDER
276 de: HAUPTKALENDER
@@ -271,6 +280,63 @@ settings:
271 google_title:
280 google_title:
272 en: Google Calendar
281 en: Google Calendar
273 de: Google Kalender
282 de: Google Kalender
283 caldav_title:
284 en: CalDAV calendar
285 de: CalDAV-Kalender
286 caldav_url:
287 en: Server URL
288 de: Server-URL
289 caldav_username:
290 en: Username
291 de: Benutzername
292 caldav_password:
293 en: App password
294 de: App-Passwort
295 caldav_connect:
296 en: Connect CalDAV
297 de: CalDAV verbinden
298 caldav_hint:
299 en: Use an app password. Templates fill a typical URL for Nextcloud, Fastmail, or iCloud.
300 de: Nutzen Sie ein App-Passwort. Vorlagen setzen eine typische URL für Nextcloud, Fastmail oder iCloud.
301 caldav_template_nextcloud:
302 en: Nextcloud
303 de: Nextcloud
304 caldav_template_fastmail:
305 en: Fastmail
306 de: Fastmail
307 caldav_template_icloud:
308 en: iCloud
309 de: iCloud
310 caldav_connected:
311 en: CalDAV account connected
312 de: CalDAV-Konto verbunden
313 caldav_connect_failed:
314 en: CalDAV connect failed
315 de: CalDAV-Verbindung fehlgeschlagen
316 caldav_readonly:
317 en: Read-only
318 de: Nur lesen
319 ics_title:
320 en: ICS subscription
321 de: ICS-Abo
322 ics_url:
323 en: ICS URL
324 de: ICS-URL
325 ics_name:
326 en: Display name
327 de: Anzeigename
328 ics_connect:
329 en: Add subscription
330 de: Abo hinzufügen
331 ics_hint:
332 en: Read-only. For holidays or shared calendar links (including Proton share links).
333 de: Nur lesen. Für Feiertage oder geteilte Kalenderlinks (auch Proton-Share-Links).
334 ics_connected:
335 en: ICS subscription added
336 de: ICS-Abo hinzugefügt
337 ics_connect_failed:
338 en: ICS subscription failed
339 de: ICS-Abo fehlgeschlagen
274 connect_button:
340 connect_button:
275 en: Connect Google
341 en: Connect Google
276 de: Google verbinden
342 de: Google verbinden
@@ -308,17 +374,17 @@ settings:
308 en: Outlook (Microsoft mailbox)
374 en: Outlook (Microsoft mailbox)
309 de: Outlook (Microsoft-Postfach)
375 de: Outlook (Microsoft-Postfach)
310 dual_write_when_google_home:
376 dual_write_when_google_home:
311 en: Dual-write when home is Google
377 en: Also write when home is not Outlook
312 de: Zusätzlich schreiben, wenn der Hauptkalender Google ist
378 de: Zusätzlich schreiben, wenn der Hauptkalender nicht Outlook ist
313 outlook_home_detail:
379 outlook_home_detail:
314 en: Default when no Google home is chosen
380 en: Default when no other home calendar is chosen
315 de: Standard, wenn kein Google-Hauptkalender gewählt ist
381 de: Standard, wenn kein anderer Hauptkalender gewählt ist
316 no_extra_targets:
382 no_extra_targets:
317 en: No extra write targets
383 en: No extra write targets
318 de: Keine weiteren Schreibziele
384 de: Keine weiteren Schreibziele
319 connect_then_dual_write:
385 connect_then_dual_write:
320 en: Connect Google, then enable dual-write on a calendar above.
386 en: Connect another account, then enable dual-write on a calendar above.
321 de: Google verbinden, dann oben Dual-Write für einen Kalender einschalten.
387 de: Weiteres Konto verbinden, dann oben Dual-Write für einen Kalender einschalten.
322 section_view:
388 section_view:
323 en: VIEW
389 en: VIEW
324 de: ANSICHT
390 de: ANSICHT
crates/app-call-model/src/week_grid.rs +51 −0
@@ -254,6 +254,57 @@ pub fn calendar_index(event: &CalendarEvent, accounts: &store::CalendarAccounts)
254 254 .zip(event.calendar_id.as_deref())
255 255 .and_then(|(account, calendar)| google_calendar_index(accounts, account, calendar))
256 256 .unwrap_or(1),
257 chatsvc::CalendarSource::CalDav => {
258 let google_len = accounts
259 .google_accounts
260 .iter()
261 .map(|account| account.calendars.len())
262 .sum::<usize>();
263 event
264 .account_id
265 .as_deref()
266 .zip(event.calendar_id.as_deref())
267 .and_then(|(account_id, calendar_id)| {
268 accounts
269 .caldav_accounts
270 .iter()
271 .flat_map(|account| {
272 account
273 .calendars
274 .iter()
275 .map(move |calendar| (account.id.as_str(), calendar.id.as_str()))
276 })
277 .position(|(account, calendar)| {
278 account == account_id && calendar == calendar_id
279 })
280 .map(|position| position + 1 + google_len)
281 })
282 .unwrap_or(1 + google_len)
283 }
284 chatsvc::CalendarSource::Ics => {
285 let offset = 1
286 + accounts
287 .google_accounts
288 .iter()
289 .map(|account| account.calendars.len())
290 .sum::<usize>()
291 + accounts
292 .caldav_accounts
293 .iter()
294 .map(|account| account.calendars.len())
295 .sum::<usize>();
296 event
297 .account_id
298 .as_deref()
299 .and_then(|id| {
300 accounts
301 .ics_subscriptions
302 .iter()
303 .position(|subscription| subscription.id == id)
304 .map(|position| position + offset)
305 })
306 .unwrap_or(offset)
307 }
257 308 }
258 309 }
259 310
@@ -254,6 +254,57 @@ pub fn calendar_index(event: &CalendarEvent, accounts: &store::CalendarAccounts)
254 .zip(event.calendar_id.as_deref())
254 .zip(event.calendar_id.as_deref())
255 .and_then(|(account, calendar)| google_calendar_index(accounts, account, calendar))
255 .and_then(|(account, calendar)| google_calendar_index(accounts, account, calendar))
256 .unwrap_or(1),
256 .unwrap_or(1),
257 chatsvc::CalendarSource::CalDav => {
258 let google_len = accounts
259 .google_accounts
260 .iter()
261 .map(|account| account.calendars.len())
262 .sum::<usize>();
263 event
264 .account_id
265 .as_deref()
266 .zip(event.calendar_id.as_deref())
267 .and_then(|(account_id, calendar_id)| {
268 accounts
269 .caldav_accounts
270 .iter()
271 .flat_map(|account| {
272 account
273 .calendars
274 .iter()
275 .map(move |calendar| (account.id.as_str(), calendar.id.as_str()))
276 })
277 .position(|(account, calendar)| {
278 account == account_id && calendar == calendar_id
279 })
280 .map(|position| position + 1 + google_len)
281 })
282 .unwrap_or(1 + google_len)
283 }
284 chatsvc::CalendarSource::Ics => {
285 let offset = 1
286 + accounts
287 .google_accounts
288 .iter()
289 .map(|account| account.calendars.len())
290 .sum::<usize>()
291 + accounts
292 .caldav_accounts
293 .iter()
294 .map(|account| account.calendars.len())
295 .sum::<usize>();
296 event
297 .account_id
298 .as_deref()
299 .and_then(|id| {
300 accounts
301 .ics_subscriptions
302 .iter()
303 .position(|subscription| subscription.id == id)
304 .map(|position| position + offset)
305 })
306 .unwrap_or(offset)
307 }
257 }
308 }
258}
309}
259
310
crates/app-state/Cargo.toml +3 −0
@@ -37,6 +37,9 @@ teams-core.workspace = true
37 37 tokio.workspace = true
38 38 uuid.workspace = true
39 39 image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
40 keyring = "3"
41 reqwest = { version = "0.13", default-features = false, features = ["rustls"] }
42 url = "2"
40 43
41 44 [target.'cfg(windows)'.dependencies]
42 45 webview.workspace = true
@@ -37,6 +37,9 @@ teams-core.workspace = true
37tokio.workspace = true
37tokio.workspace = true
38uuid.workspace = true
38uuid.workspace = true
39image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
39image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
40keyring = "3"
41reqwest = { version = "0.13", default-features = false, features = ["rustls"] }
42url = "2"
40
43
41[target.'cfg(windows)'.dependencies]
44[target.'cfg(windows)'.dependencies]
42webview.workspace = true
45webview.workspace = true
crates/app-state/src/backend.rs +14 −1
@@ -585,7 +585,20 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
585 585 if combined.is_empty() && outlook_failed && !accounts.has_google() {
586 586 continue;
587 587 }
588 let merged = chatsvc::merge_calendar_events(combined);
588 let home = {
589 use store::CalendarProvider;
590 let source = match accounts.home.provider {
591 CalendarProvider::Outlook => chatsvc::CalendarSource::Outlook,
592 CalendarProvider::Google => chatsvc::CalendarSource::Google,
593 CalendarProvider::CalDav => chatsvc::CalendarSource::CalDav,
594 };
595 Some(chatsvc::HomeCalendar {
596 source,
597 account_id: accounts.home.account_id.as_str(),
598 calendar_id: accounts.home.calendar_id.as_str(),
599 })
600 };
601 let merged = chatsvc::merge_calendar_events(combined, home);
589 602 if events.send(BackendEvent::Calendar(merged)).is_err() {
590 603 return;
591 604 }
@@ -585,7 +585,20 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
585 if combined.is_empty() && outlook_failed && !accounts.has_google() {
585 if combined.is_empty() && outlook_failed && !accounts.has_google() {
586 continue;
586 continue;
587 }
587 }
588 let merged = chatsvc::merge_calendar_events(combined);
588 let home = {
589 use store::CalendarProvider;
590 let source = match accounts.home.provider {
591 CalendarProvider::Outlook => chatsvc::CalendarSource::Outlook,
592 CalendarProvider::Google => chatsvc::CalendarSource::Google,
593 CalendarProvider::CalDav => chatsvc::CalendarSource::CalDav,
594 };
595 Some(chatsvc::HomeCalendar {
596 source,
597 account_id: accounts.home.account_id.as_str(),
598 calendar_id: accounts.home.calendar_id.as_str(),
599 })
600 };
601 let merged = chatsvc::merge_calendar_events(combined, home);
589 if events.send(BackendEvent::Calendar(merged)).is_err() {
602 if events.send(BackendEvent::Calendar(merged)).is_err() {
590 return;
603 return;
591 }
604 }
crates/app-state/src/caldav_credentials.rs added +50 −0
@@ -0,0 +1,50 @@
1 //! OS keyring storage for CalDAV app passwords (ADR 0019).
2
3 const SERVICE: &str = "rusty-teams.caldav";
4
5 pub fn store_password(account_id: &str, password: &str) -> Result<(), String> {
6 let entry = keyring::Entry::new(SERVICE, account_id).map_err(|e| e.to_string())?;
7 entry.set_password(password).map_err(|e| e.to_string())
8 }
9
10 pub fn load_password(account_id: &str) -> Result<String, String> {
11 let entry = keyring::Entry::new(SERVICE, account_id).map_err(|e| e.to_string())?;
12 entry.get_password().map_err(|e| e.to_string())
13 }
14
15 pub fn delete_password(account_id: &str) -> Result<(), String> {
16 let entry = keyring::Entry::new(SERVICE, account_id).map_err(|e| e.to_string())?;
17 match entry.delete_credential() {
18 Ok(()) => Ok(()),
19 Err(keyring::Error::NoEntry) => Ok(()),
20 Err(error) => Err(error.to_string()),
21 }
22 }
23
24 /// Redact credentials that must never appear in diagnostics or support bundles.
25 pub fn redact_secret_text(text: &str) -> String {
26 let mut out = text.to_owned();
27 // user:pass@host
28 if let Some(scheme_end) = out.find("://") {
29 let after = scheme_end + 3;
30 if let Some(at) = out[after..].find('@') {
31 let creds = &out[after..after + at];
32 if creds.contains(':') {
33 out.replace_range(after..after + at, "***:***");
34 }
35 }
36 }
37 out
38 }
39
40 #[cfg(test)]
41 mod tests {
42 use super::*;
43
44 #[test]
45 fn redacts_userinfo_in_urls() {
46 let scrubbed = redact_secret_text("GET https://joe:s3cret@cloud.example/dav/ ok");
47 assert!(!scrubbed.contains("s3cret"));
48 assert!(scrubbed.contains("***:***@cloud.example"));
49 }
50 }
@@ -0,0 +1,50 @@
1//! OS keyring storage for CalDAV app passwords (ADR 0019).
2
3const SERVICE: &str = "rusty-teams.caldav";
4
5pub fn store_password(account_id: &str, password: &str) -> Result<(), String> {
6 let entry = keyring::Entry::new(SERVICE, account_id).map_err(|e| e.to_string())?;
7 entry.set_password(password).map_err(|e| e.to_string())
8}
9
10pub fn load_password(account_id: &str) -> Result<String, String> {
11 let entry = keyring::Entry::new(SERVICE, account_id).map_err(|e| e.to_string())?;
12 entry.get_password().map_err(|e| e.to_string())
13}
14
15pub fn delete_password(account_id: &str) -> Result<(), String> {
16 let entry = keyring::Entry::new(SERVICE, account_id).map_err(|e| e.to_string())?;
17 match entry.delete_credential() {
18 Ok(()) => Ok(()),
19 Err(keyring::Error::NoEntry) => Ok(()),
20 Err(error) => Err(error.to_string()),
21 }
22}
23
24/// Redact credentials that must never appear in diagnostics or support bundles.
25pub fn redact_secret_text(text: &str) -> String {
26 let mut out = text.to_owned();
27 // user:pass@host
28 if let Some(scheme_end) = out.find("://") {
29 let after = scheme_end + 3;
30 if let Some(at) = out[after..].find('@') {
31 let creds = &out[after..after + at];
32 if creds.contains(':') {
33 out.replace_range(after..after + at, "***:***");
34 }
35 }
36 }
37 out
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 #[test]
45 fn redacts_userinfo_in_urls() {
46 let scrubbed = redact_secret_text("GET https://joe:s3cret@cloud.example/dav/ ok");
47 assert!(!scrubbed.contains("s3cret"));
48 assert!(scrubbed.contains("***:***@cloud.example"));
49 }
50}
crates/app-state/src/caldav_sync.rs added +209 −0
@@ -0,0 +1,209 @@
1 use chrono::{DateTime, Utc};
2 use store::{CalDavAccount, CalDavCalendarInfo, CalendarAccounts};
3 use uuid::Uuid;
4
5 use chatsvc::{
6 CalDavClient, CalDavEventDraft, CalendarEvent, Reply, discover_caldav, new_event_uid,
7 partstat_for_reply,
8 };
9
10 use crate::caldav_credentials::{delete_password, load_password, store_password};
11
12 pub async fn connect_caldav(
13 accounts: &mut CalendarAccounts,
14 url: &str,
15 username: &str,
16 password: &str,
17 ) -> Result<String, String> {
18 let url = normalize_url(url)?;
19 let client = CalDavClient::new(username, password);
20 let discovered = discover_caldav(&client, &url)
21 .await
22 .map_err(|e| e.to_string())?;
23 let listed = client
24 .list_calendars(&discovered.home_set)
25 .await
26 .map_err(|e| e.to_string())?;
27 if listed.is_empty() {
28 return Err("No event calendars found on this CalDAV account".into());
29 }
30 let id = Uuid::new_v4().to_string();
31 store_password(&id, password)?;
32 accounts.caldav_accounts.push(CalDavAccount {
33 id: id.clone(),
34 url,
35 username: username.to_owned(),
36 display_name: username.to_owned(),
37 calendars: listed
38 .into_iter()
39 .map(|calendar| CalDavCalendarInfo {
40 id: calendar.href,
41 summary: calendar.summary,
42 selected: true,
43 writable: calendar.writable,
44 color: calendar.color,
45 })
46 .collect(),
47 user_addresses: discovered.user_addresses,
48 schedule_outbox: discovered.schedule_outbox,
49 });
50 Ok(id)
51 }
52
53 pub fn disconnect_caldav(accounts: &mut CalendarAccounts, account_id: &str) -> Result<(), String> {
54 delete_password(account_id)?;
55 accounts.disconnect_caldav(account_id);
56 Ok(())
57 }
58
59 pub async fn fetch_caldav_events(
60 accounts: &mut CalendarAccounts,
61 start: DateTime<Utc>,
62 end: DateTime<Utc>,
63 ) -> Result<Vec<CalendarEvent>, String> {
64 let mut all = Vec::new();
65 for index in 0..accounts.caldav_accounts.len() {
66 let account = &accounts.caldav_accounts[index];
67 let password = match load_password(&account.id) {
68 Ok(password) => password,
69 Err(error) => {
70 return Err(format!(
71 "CalDAV password missing for {}: {error}",
72 account.username
73 ));
74 }
75 };
76 let client = CalDavClient::new(&account.username, &password);
77 let account_id = account.id.clone();
78 let calendars: Vec<(String, String)> = account
79 .calendars
80 .iter()
81 .filter(|calendar| calendar.selected)
82 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
83 .collect();
84 for (calendar_id, calendar_name) in calendars {
85 match client
86 .fetch_events(&calendar_id, &account_id, Some(&calendar_name), start, end)
87 .await
88 {
89 Ok(events) => all.extend(events.into_iter().map(|item| item.event)),
90 Err(error) => {
91 return Err(format!("CalDAV {calendar_name}: {error}"));
92 }
93 }
94 }
95 }
96 Ok(all)
97 }
98
99 pub async fn insert_caldav_event(
100 accounts: &mut CalendarAccounts,
101 account_id: &str,
102 calendar_id: &str,
103 draft: &CalDavEventDraft,
104 ) -> Result<(), String> {
105 let account = accounts
106 .caldav_account(account_id)
107 .ok_or_else(|| format!("CalDAV account {account_id} missing"))?;
108 let password = load_password(account_id)?;
109 let client = CalDavClient::new(&account.username, password);
110 client
111 .put_event(calendar_id, draft, Utc::now())
112 .await
113 .map(|_| ())
114 .map_err(|e| e.to_string())
115 }
116
117 pub async fn respond_caldav_event(
118 accounts: &mut CalendarAccounts,
119 account_id: &str,
120 href: &str,
121 reply: Reply,
122 ) -> Result<bool, String> {
123 let account = accounts
124 .caldav_account(account_id)
125 .ok_or_else(|| format!("CalDAV account {account_id} missing"))?;
126 let password = load_password(account_id)?;
127 let mailto = account
128 .user_addresses
129 .iter()
130 .find(|addr| addr.to_ascii_lowercase().contains('@'))
131 .cloned()
132 .or_else(|| {
133 account
134 .username
135 .contains('@')
136 .then(|| format!("mailto:{}", account.username))
137 })
138 .ok_or_else(|| "CalDAV calendar-user-address missing".to_owned())?;
139 let notified = account.schedule_outbox.is_some();
140 let client = CalDavClient::new(&account.username, password);
141 client
142 .update_partstat(href, None, &mailto, partstat_for_reply(reply))
143 .await
144 .map_err(|e| e.to_string())?;
145 Ok(notified)
146 }
147
148 pub async fn delete_caldav_event(
149 accounts: &mut CalendarAccounts,
150 account_id: &str,
151 href: &str,
152 ) -> Result<(), String> {
153 let account = accounts
154 .caldav_account(account_id)
155 .ok_or_else(|| format!("CalDAV account {account_id} missing"))?;
156 let password = load_password(account_id)?;
157 let client = CalDavClient::new(&account.username, password);
158 // Series occurrence exclusion is handled by callers that rewrite EXDATE; single events DELETE.
159 let href = href.split('#').next().unwrap_or(href);
160 client
161 .delete(href, None)
162 .await
163 .map_err(|e| e.to_string())
164 }
165
166 pub fn draft_from_meeting(
167 subject: &str,
168 start: DateTime<Utc>,
169 end: DateTime<Utc>,
170 join_url: Option<&str>,
171 attendees: &[String],
172 include_attendees: bool,
173 repeat: chatsvc::Repeat,
174 ) -> CalDavEventDraft {
175 CalDavEventDraft {
176 uid: new_event_uid(),
177 summary: subject.to_owned(),
178 start,
179 end,
180 all_day: false,
181 description: None,
182 location: None,
183 join_url: join_url.map(str::to_owned),
184 attendees: if include_attendees {
185 attendees.to_vec()
186 } else {
187 Vec::new()
188 },
189 repeat,
190 sequence: 0,
191 }
192 }
193
194 fn normalize_url(url: &str) -> Result<String, String> {
195 let trimmed = url.trim();
196 if trimmed.is_empty() {
197 return Err("CalDAV URL is empty".into());
198 }
199 let with_scheme = if trimmed.contains("://") {
200 trimmed.to_owned()
201 } else {
202 format!("https://{trimmed}")
203 };
204 let parsed = url::Url::parse(&with_scheme).map_err(|e| e.to_string())?;
205 if parsed.username() != "" || parsed.password().is_some() {
206 return Err("Put the username and app password in the form fields, not in the URL".into());
207 }
208 Ok(parsed.to_string())
209 }
@@ -0,0 +1,209 @@
1use chrono::{DateTime, Utc};
2use store::{CalDavAccount, CalDavCalendarInfo, CalendarAccounts};
3use uuid::Uuid;
4
5use chatsvc::{
6 CalDavClient, CalDavEventDraft, CalendarEvent, Reply, discover_caldav, new_event_uid,
7 partstat_for_reply,
8};
9
10use crate::caldav_credentials::{delete_password, load_password, store_password};
11
12pub async fn connect_caldav(
13 accounts: &mut CalendarAccounts,
14 url: &str,
15 username: &str,
16 password: &str,
17) -> Result<String, String> {
18 let url = normalize_url(url)?;
19 let client = CalDavClient::new(username, password);
20 let discovered = discover_caldav(&client, &url)
21 .await
22 .map_err(|e| e.to_string())?;
23 let listed = client
24 .list_calendars(&discovered.home_set)
25 .await
26 .map_err(|e| e.to_string())?;
27 if listed.is_empty() {
28 return Err("No event calendars found on this CalDAV account".into());
29 }
30 let id = Uuid::new_v4().to_string();
31 store_password(&id, password)?;
32 accounts.caldav_accounts.push(CalDavAccount {
33 id: id.clone(),
34 url,
35 username: username.to_owned(),
36 display_name: username.to_owned(),
37 calendars: listed
38 .into_iter()
39 .map(|calendar| CalDavCalendarInfo {
40 id: calendar.href,
41 summary: calendar.summary,
42 selected: true,
43 writable: calendar.writable,
44 color: calendar.color,
45 })
46 .collect(),
47 user_addresses: discovered.user_addresses,
48 schedule_outbox: discovered.schedule_outbox,
49 });
50 Ok(id)
51}
52
53pub fn disconnect_caldav(accounts: &mut CalendarAccounts, account_id: &str) -> Result<(), String> {
54 delete_password(account_id)?;
55 accounts.disconnect_caldav(account_id);
56 Ok(())
57}
58
59pub async fn fetch_caldav_events(
60 accounts: &mut CalendarAccounts,
61 start: DateTime<Utc>,
62 end: DateTime<Utc>,
63) -> Result<Vec<CalendarEvent>, String> {
64 let mut all = Vec::new();
65 for index in 0..accounts.caldav_accounts.len() {
66 let account = &accounts.caldav_accounts[index];
67 let password = match load_password(&account.id) {
68 Ok(password) => password,
69 Err(error) => {
70 return Err(format!(
71 "CalDAV password missing for {}: {error}",
72 account.username
73 ));
74 }
75 };
76 let client = CalDavClient::new(&account.username, &password);
77 let account_id = account.id.clone();
78 let calendars: Vec<(String, String)> = account
79 .calendars
80 .iter()
81 .filter(|calendar| calendar.selected)
82 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
83 .collect();
84 for (calendar_id, calendar_name) in calendars {
85 match client
86 .fetch_events(&calendar_id, &account_id, Some(&calendar_name), start, end)
87 .await
88 {
89 Ok(events) => all.extend(events.into_iter().map(|item| item.event)),
90 Err(error) => {
91 return Err(format!("CalDAV {calendar_name}: {error}"));
92 }
93 }
94 }
95 }
96 Ok(all)
97}
98
99pub async fn insert_caldav_event(
100 accounts: &mut CalendarAccounts,
101 account_id: &str,
102 calendar_id: &str,
103 draft: &CalDavEventDraft,
104) -> Result<(), String> {
105 let account = accounts
106 .caldav_account(account_id)
107 .ok_or_else(|| format!("CalDAV account {account_id} missing"))?;
108 let password = load_password(account_id)?;
109 let client = CalDavClient::new(&account.username, password);
110 client
111 .put_event(calendar_id, draft, Utc::now())
112 .await
113 .map(|_| ())
114 .map_err(|e| e.to_string())
115}
116
117pub async fn respond_caldav_event(
118 accounts: &mut CalendarAccounts,
119 account_id: &str,
120 href: &str,
121 reply: Reply,
122) -> Result<bool, String> {
123 let account = accounts
124 .caldav_account(account_id)
125 .ok_or_else(|| format!("CalDAV account {account_id} missing"))?;
126 let password = load_password(account_id)?;
127 let mailto = account
128 .user_addresses
129 .iter()
130 .find(|addr| addr.to_ascii_lowercase().contains('@'))
131 .cloned()
132 .or_else(|| {
133 account
134 .username
135 .contains('@')
136 .then(|| format!("mailto:{}", account.username))
137 })
138 .ok_or_else(|| "CalDAV calendar-user-address missing".to_owned())?;
139 let notified = account.schedule_outbox.is_some();
140 let client = CalDavClient::new(&account.username, password);
141 client
142 .update_partstat(href, None, &mailto, partstat_for_reply(reply))
143 .await
144 .map_err(|e| e.to_string())?;
145 Ok(notified)
146}
147
148pub async fn delete_caldav_event(
149 accounts: &mut CalendarAccounts,
150 account_id: &str,
151 href: &str,
152) -> Result<(), String> {
153 let account = accounts
154 .caldav_account(account_id)
155 .ok_or_else(|| format!("CalDAV account {account_id} missing"))?;
156 let password = load_password(account_id)?;
157 let client = CalDavClient::new(&account.username, password);
158 // Series occurrence exclusion is handled by callers that rewrite EXDATE; single events DELETE.
159 let href = href.split('#').next().unwrap_or(href);
160 client
161 .delete(href, None)
162 .await
163 .map_err(|e| e.to_string())
164}
165
166pub fn draft_from_meeting(
167 subject: &str,
168 start: DateTime<Utc>,
169 end: DateTime<Utc>,
170 join_url: Option<&str>,
171 attendees: &[String],
172 include_attendees: bool,
173 repeat: chatsvc::Repeat,
174) -> CalDavEventDraft {
175 CalDavEventDraft {
176 uid: new_event_uid(),
177 summary: subject.to_owned(),
178 start,
179 end,
180 all_day: false,
181 description: None,
182 location: None,
183 join_url: join_url.map(str::to_owned),
184 attendees: if include_attendees {
185 attendees.to_vec()
186 } else {
187 Vec::new()
188 },
189 repeat,
190 sequence: 0,
191 }
192}
193
194fn normalize_url(url: &str) -> Result<String, String> {
195 let trimmed = url.trim();
196 if trimmed.is_empty() {
197 return Err("CalDAV URL is empty".into());
198 }
199 let with_scheme = if trimmed.contains("://") {
200 trimmed.to_owned()
201 } else {
202 format!("https://{trimmed}")
203 };
204 let parsed = url::Url::parse(&with_scheme).map_err(|e| e.to_string())?;
205 if parsed.username() != "" || parsed.password().is_some() {
206 return Err("Put the username and app password in the form fields, not in the URL".into());
207 }
208 Ok(parsed.to_string())
209}
crates/app-state/src/calendar_accounts_actions.rs +142 −0
@@ -33,6 +33,148 @@ impl AppState {
33 33 cx.notify();
34 34 }
35 35
36 pub fn connect_caldav_account(
37 &mut self,
38 url: String,
39 username: String,
40 password: String,
41 cx: &mut Context<Self>,
42 ) {
43 let store = self.store.clone();
44 let connecting = runtime::spawn(async move {
45 let mut accounts = load_calendar_accounts(&store);
46 let id =
47 crate::caldav_sync::connect_caldav(&mut accounts, &url, &username, &password).await?;
48 save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
49 Ok::<_, String>(id)
50 });
51 cx.spawn(async move |this, cx| {
52 match connecting.await {
53 Ok(Ok(_)) => {
54 this.update(cx, |state, cx| {
55 state.raise_notice(tr("settings.calendar.caldav_connected"), None, cx);
56 state.refresh_calendar(cx);
57 state.load_calendar_week(cx);
58 cx.notify();
59 })
60 .ok();
61 }
62 Ok(Err(error)) => {
63 this.update(cx, |state, cx| {
64 state.raise_notice(
65 crate::caldav_credentials::redact_secret_text(&error),
66 None,
67 cx,
68 );
69 })
70 .ok();
71 }
72 Err(_) => {
73 this.update(cx, |state, cx| {
74 state.raise_notice(tr("settings.calendar.caldav_connect_failed"), None, cx);
75 })
76 .ok();
77 }
78 }
79 })
80 .detach();
81 }
82
83 pub fn disconnect_caldav_account(&mut self, account_id: &str, cx: &mut Context<Self>) {
84 let mut accounts = load_calendar_accounts(&self.store);
85 if let Err(error) = crate::caldav_sync::disconnect_caldav(&mut accounts, account_id) {
86 self.raise_notice(error, None, cx);
87 return;
88 }
89 let _ = save_calendar_accounts(&self.store, &accounts);
90 self.refresh_calendar(cx);
91 self.load_calendar_week(cx);
92 cx.notify();
93 }
94
95 pub fn toggle_caldav_calendar_selected(
96 &mut self,
97 account_id: &str,
98 calendar_id: &str,
99 cx: &mut Context<Self>,
100 ) {
101 let mut accounts = load_calendar_accounts(&self.store);
102 if let Some(calendar) = accounts.caldav_account_mut(account_id).and_then(|account| {
103 account
104 .calendars
105 .iter_mut()
106 .find(|calendar| calendar.id == calendar_id)
107 }) {
108 calendar.selected = !calendar.selected;
109 }
110 let _ = save_calendar_accounts(&self.store, &accounts);
111 self.refresh_calendar(cx);
112 self.load_calendar_week(cx);
113 cx.notify();
114 }
115
116 pub fn connect_ics_subscription(&mut self, url: String, summary: String, cx: &mut Context<Self>) {
117 let store = self.store.clone();
118 let connecting = runtime::spawn(async move {
119 let mut accounts = load_calendar_accounts(&store);
120 let id = crate::ics_sync::add_ics_subscription(&mut accounts, &url, &summary).await?;
121 save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
122 Ok::<_, String>(id)
123 });
124 cx.spawn(async move |this, cx| {
125 match connecting.await {
126 Ok(Ok(_)) => {
127 this.update(cx, |state, cx| {
128 state.raise_notice(tr("settings.calendar.ics_connected"), None, cx);
129 state.refresh_calendar(cx);
130 state.load_calendar_week(cx);
131 cx.notify();
132 })
133 .ok();
134 }
135 Ok(Err(error)) => {
136 this.update(cx, |state, cx| state.raise_notice(error, None, cx))
137 .ok();
138 }
139 Err(_) => {
140 this.update(cx, |state, cx| {
141 state.raise_notice(tr("settings.calendar.ics_connect_failed"), None, cx);
142 })
143 .ok();
144 }
145 }
146 })
147 .detach();
148 }
149
150 pub fn disconnect_ics_subscription(&mut self, subscription_id: &str, cx: &mut Context<Self>) {
151 let mut accounts = load_calendar_accounts(&self.store);
152 accounts.disconnect_ics(subscription_id);
153 let _ = save_calendar_accounts(&self.store, &accounts);
154 self.refresh_calendar(cx);
155 self.load_calendar_week(cx);
156 cx.notify();
157 }
158
159 pub fn toggle_ics_subscription_selected(
160 &mut self,
161 subscription_id: &str,
162 cx: &mut Context<Self>,
163 ) {
164 let mut accounts = load_calendar_accounts(&self.store);
165 if let Some(subscription) = accounts
166 .ics_subscriptions
167 .iter_mut()
168 .find(|subscription| subscription.id == subscription_id)
169 {
170 subscription.selected = !subscription.selected;
171 }
172 let _ = save_calendar_accounts(&self.store, &accounts);
173 self.refresh_calendar(cx);
174 self.load_calendar_week(cx);
175 cx.notify();
176 }
177
36 178 pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {
37 179 let mut accounts = load_calendar_accounts(&self.store);
38 180 accounts.home = home;
@@ -33,6 +33,148 @@ impl AppState {
33 cx.notify();
33 cx.notify();
34 }
34 }
35
35
36 pub fn connect_caldav_account(
37 &mut self,
38 url: String,
39 username: String,
40 password: String,
41 cx: &mut Context<Self>,
42 ) {
43 let store = self.store.clone();
44 let connecting = runtime::spawn(async move {
45 let mut accounts = load_calendar_accounts(&store);
46 let id =
47 crate::caldav_sync::connect_caldav(&mut accounts, &url, &username, &password).await?;
48 save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
49 Ok::<_, String>(id)
50 });
51 cx.spawn(async move |this, cx| {
52 match connecting.await {
53 Ok(Ok(_)) => {
54 this.update(cx, |state, cx| {
55 state.raise_notice(tr("settings.calendar.caldav_connected"), None, cx);
56 state.refresh_calendar(cx);
57 state.load_calendar_week(cx);
58 cx.notify();
59 })
60 .ok();
61 }
62 Ok(Err(error)) => {
63 this.update(cx, |state, cx| {
64 state.raise_notice(
65 crate::caldav_credentials::redact_secret_text(&error),
66 None,
67 cx,
68 );
69 })
70 .ok();
71 }
72 Err(_) => {
73 this.update(cx, |state, cx| {
74 state.raise_notice(tr("settings.calendar.caldav_connect_failed"), None, cx);
75 })
76 .ok();
77 }
78 }
79 })
80 .detach();
81 }
82
83 pub fn disconnect_caldav_account(&mut self, account_id: &str, cx: &mut Context<Self>) {
84 let mut accounts = load_calendar_accounts(&self.store);
85 if let Err(error) = crate::caldav_sync::disconnect_caldav(&mut accounts, account_id) {
86 self.raise_notice(error, None, cx);
87 return;
88 }
89 let _ = save_calendar_accounts(&self.store, &accounts);
90 self.refresh_calendar(cx);
91 self.load_calendar_week(cx);
92 cx.notify();
93 }
94
95 pub fn toggle_caldav_calendar_selected(
96 &mut self,
97 account_id: &str,
98 calendar_id: &str,
99 cx: &mut Context<Self>,
100 ) {
101 let mut accounts = load_calendar_accounts(&self.store);
102 if let Some(calendar) = accounts.caldav_account_mut(account_id).and_then(|account| {
103 account
104 .calendars
105 .iter_mut()
106 .find(|calendar| calendar.id == calendar_id)
107 }) {
108 calendar.selected = !calendar.selected;
109 }
110 let _ = save_calendar_accounts(&self.store, &accounts);
111 self.refresh_calendar(cx);
112 self.load_calendar_week(cx);
113 cx.notify();
114 }
115
116 pub fn connect_ics_subscription(&mut self, url: String, summary: String, cx: &mut Context<Self>) {
117 let store = self.store.clone();
118 let connecting = runtime::spawn(async move {
119 let mut accounts = load_calendar_accounts(&store);
120 let id = crate::ics_sync::add_ics_subscription(&mut accounts, &url, &summary).await?;
121 save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
122 Ok::<_, String>(id)
123 });
124 cx.spawn(async move |this, cx| {
125 match connecting.await {
126 Ok(Ok(_)) => {
127 this.update(cx, |state, cx| {
128 state.raise_notice(tr("settings.calendar.ics_connected"), None, cx);
129 state.refresh_calendar(cx);
130 state.load_calendar_week(cx);
131 cx.notify();
132 })
133 .ok();
134 }
135 Ok(Err(error)) => {
136 this.update(cx, |state, cx| state.raise_notice(error, None, cx))
137 .ok();
138 }
139 Err(_) => {
140 this.update(cx, |state, cx| {
141 state.raise_notice(tr("settings.calendar.ics_connect_failed"), None, cx);
142 })
143 .ok();
144 }
145 }
146 })
147 .detach();
148 }
149
150 pub fn disconnect_ics_subscription(&mut self, subscription_id: &str, cx: &mut Context<Self>) {
151 let mut accounts = load_calendar_accounts(&self.store);
152 accounts.disconnect_ics(subscription_id);
153 let _ = save_calendar_accounts(&self.store, &accounts);
154 self.refresh_calendar(cx);
155 self.load_calendar_week(cx);
156 cx.notify();
157 }
158
159 pub fn toggle_ics_subscription_selected(
160 &mut self,
161 subscription_id: &str,
162 cx: &mut Context<Self>,
163 ) {
164 let mut accounts = load_calendar_accounts(&self.store);
165 if let Some(subscription) = accounts
166 .ics_subscriptions
167 .iter_mut()
168 .find(|subscription| subscription.id == subscription_id)
169 {
170 subscription.selected = !subscription.selected;
171 }
172 let _ = save_calendar_accounts(&self.store, &accounts);
173 self.refresh_calendar(cx);
174 self.load_calendar_week(cx);
175 cx.notify();
176 }
177
36 pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {
178 pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {
37 let mut accounts = load_calendar_accounts(&self.store);
179 let mut accounts = load_calendar_accounts(&self.store);
38 accounts.home = home;
180 accounts.home = home;
crates/app-state/src/call/meeting_create.rs +62 −21
@@ -8,11 +8,10 @@ use super::schedule::MeetingDraft;
8 8
9 9 /// Whether create must mint a Teams join URL before per-target inserts.
10 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)
11 accounts
12 .resolved_write_targets()
13 .iter()
14 .any(|target| target.provider != CalendarProvider::Outlook)
16 15 }
17 16
18 17 /// Write targets used for New meeting (home + extras, de-duplicated).
@@ -40,10 +39,22 @@ pub async fn create_across_targets(
40 39 let event = launcher.resolve_new_event(draft).await?;
41 40 let join_url = launcher.create_meet_now(&event.subject).await?;
42 41 let targets = create_targets(&accounts);
42 let outlook_invites = targets
43 .iter()
44 .any(|target| target.provider == CalendarProvider::Outlook);
43 45 let mut failed = Vec::new();
44 46 let mut first_id = String::new();
45 47 for target in targets {
46 match write_target(launcher.as_ref(), &mut accounts, &target, &event, &join_url).await {
48 match write_target(
49 launcher.as_ref(),
50 &mut accounts,
51 &target,
52 &event,
53 &join_url,
54 outlook_invites,
55 )
56 .await
57 {
47 58 Ok(id) => {
48 59 if first_id.is_empty() {
49 60 first_id = id;
@@ -75,6 +86,7 @@ async fn write_target(
75 86 target: &CalendarRef,
76 87 event: &NewEvent,
77 88 join_url: &str,
89 outlook_invites: bool,
78 90 ) -> Result<String, String> {
79 91 match target.provider {
80 92 CalendarProvider::Outlook => launcher
@@ -98,6 +110,30 @@ async fn write_target(
98 110 .await?;
99 111 Ok(format!("google:{}:{}", target.account_id, calendar_id))
100 112 }
113 CalendarProvider::CalDav => {
114 let attendees: Vec<String> = event
115 .attendees
116 .iter()
117 .map(|attendee| attendee.address.clone())
118 .collect();
119 let draft = crate::caldav_sync::draft_from_meeting(
120 &event.subject,
121 event.start,
122 event.end,
123 Some(join_url),
124 &attendees,
125 !outlook_invites,
126 event.repeat,
127 );
128 crate::caldav_sync::insert_caldav_event(
129 accounts,
130 &target.account_id,
131 &target.calendar_id,
132 &draft,
133 )
134 .await?;
135 Ok(format!("caldav:{}:{}", target.account_id, target.calendar_id))
136 }
101 137 }
102 138 }
103 139
@@ -108,22 +144,20 @@ mod tests {
108 144 use super::*;
109 145
110 146 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(),
147 let mut accounts = CalendarAccounts::default();
148 accounts.home = CalendarRef::google("g1", "primary");
149 accounts.google_accounts.push(GoogleAccount {
150 id: "g1".into(),
151 email: "joe@example.com".into(),
152 calendars: vec![GoogleCalendarInfo {
153 id: "primary".into(),
154 summary: "Joe".into(),
155 selected: true,
156 primary: true,
125 157 }],
126 }
158 tokens: GoogleTokenSet::default(),
159 });
160 accounts
127 161 }
128 162
129 163 #[test]
@@ -142,6 +176,13 @@ mod tests {
142 176 assert!(needs_join_first(&google_home()));
143 177 }
144 178
179 #[test]
180 fn caldav_only_home_needs_join_first() {
181 let mut accounts = CalendarAccounts::default();
182 accounts.home = CalendarRef::caldav("c1", "/cal/");
183 assert!(needs_join_first(&accounts));
184 }
185
145 186 #[test]
146 187 fn outlook_home_with_google_extra_needs_join_first() {
147 188 let mut accounts = CalendarAccounts::default();
@@ -8,11 +8,10 @@ use super::schedule::MeetingDraft;
8
8
9/// Whether create must mint a Teams join URL before per-target inserts.
9/// Whether create must mint a Teams join URL before per-target inserts.
10pub fn needs_join_first(accounts: &CalendarAccounts) -> bool {
10pub fn needs_join_first(accounts: &CalendarAccounts) -> bool {
11 let targets = accounts.resolved_write_targets();
11 accounts
12 targets.len() > 1
12 .resolved_write_targets()
13 || targets
13 .iter()
14 .iter()
14 .any(|target| target.provider != CalendarProvider::Outlook)
15 .any(|target| target.provider == CalendarProvider::Google)
16}
15}
17
16
18/// Write targets used for New meeting (home + extras, de-duplicated).
17/// Write targets used for New meeting (home + extras, de-duplicated).
@@ -40,10 +39,22 @@ pub async fn create_across_targets(
40 let event = launcher.resolve_new_event(draft).await?;
39 let event = launcher.resolve_new_event(draft).await?;
41 let join_url = launcher.create_meet_now(&event.subject).await?;
40 let join_url = launcher.create_meet_now(&event.subject).await?;
42 let targets = create_targets(&accounts);
41 let targets = create_targets(&accounts);
42 let outlook_invites = targets
43 .iter()
44 .any(|target| target.provider == CalendarProvider::Outlook);
43 let mut failed = Vec::new();
45 let mut failed = Vec::new();
44 let mut first_id = String::new();
46 let mut first_id = String::new();
45 for target in targets {
47 for target in targets {
46 match write_target(launcher.as_ref(), &mut accounts, &target, &event, &join_url).await {
48 match write_target(
49 launcher.as_ref(),
50 &mut accounts,
51 &target,
52 &event,
53 &join_url,
54 outlook_invites,
55 )
56 .await
57 {
47 Ok(id) => {
58 Ok(id) => {
48 if first_id.is_empty() {
59 if first_id.is_empty() {
49 first_id = id;
60 first_id = id;
@@ -75,6 +86,7 @@ async fn write_target(
75 target: &CalendarRef,
86 target: &CalendarRef,
76 event: &NewEvent,
87 event: &NewEvent,
77 join_url: &str,
88 join_url: &str,
89 outlook_invites: bool,
78) -> Result<String, String> {
90) -> Result<String, String> {
79 match target.provider {
91 match target.provider {
80 CalendarProvider::Outlook => launcher
92 CalendarProvider::Outlook => launcher
@@ -98,6 +110,30 @@ async fn write_target(
98 .await?;
110 .await?;
99 Ok(format!("google:{}:{}", target.account_id, calendar_id))
111 Ok(format!("google:{}:{}", target.account_id, calendar_id))
100 }
112 }
113 CalendarProvider::CalDav => {
114 let attendees: Vec<String> = event
115 .attendees
116 .iter()
117 .map(|attendee| attendee.address.clone())
118 .collect();
119 let draft = crate::caldav_sync::draft_from_meeting(
120 &event.subject,
121 event.start,
122 event.end,
123 Some(join_url),
124 &attendees,
125 !outlook_invites,
126 event.repeat,
127 );
128 crate::caldav_sync::insert_caldav_event(
129 accounts,
130 &target.account_id,
131 &target.calendar_id,
132 &draft,
133 )
134 .await?;
135 Ok(format!("caldav:{}:{}", target.account_id, target.calendar_id))
136 }
101 }
137 }
102}
138}
103
139
@@ -108,22 +144,20 @@ mod tests {
108 use super::*;
144 use super::*;
109
145
110 fn google_home() -> CalendarAccounts {
146 fn google_home() -> CalendarAccounts {
111 CalendarAccounts {
147 let mut accounts = CalendarAccounts::default();
112 home: CalendarRef::google("g1", "primary"),
148 accounts.home = CalendarRef::google("g1", "primary");
113 write_targets: Vec::new(),
149 accounts.google_accounts.push(GoogleAccount {
114 outlook_selected: true,
150 id: "g1".into(),
115 google_accounts: vec![GoogleAccount {
151 email: "joe@example.com".into(),
116 id: "g1".into(),
152 calendars: vec![GoogleCalendarInfo {
117 email: "joe@example.com".into(),
153 id: "primary".into(),
118 calendars: vec![GoogleCalendarInfo {
154 summary: "Joe".into(),
119 id: "primary".into(),
155 selected: true,
120 summary: "Joe".into(),
156 primary: true,
121 selected: true,
122 primary: true,
123 }],
124 tokens: GoogleTokenSet::default(),
125 }],
157 }],
126 }
158 tokens: GoogleTokenSet::default(),
159 });
160 accounts
127 }
161 }
128
162
129 #[test]
163 #[test]
@@ -142,6 +176,13 @@ mod tests {
142 assert!(needs_join_first(&google_home()));
176 assert!(needs_join_first(&google_home()));
143 }
177 }
144
178
179 #[test]
180 fn caldav_only_home_needs_join_first() {
181 let mut accounts = CalendarAccounts::default();
182 accounts.home = CalendarRef::caldav("c1", "/cal/");
183 assert!(needs_join_first(&accounts));
184 }
185
145 #[test]
186 #[test]
146 fn outlook_home_with_google_extra_needs_join_first() {
187 fn outlook_home_with_google_extra_needs_join_first() {
147 let mut accounts = CalendarAccounts::default();
188 let mut accounts = CalendarAccounts::default();
crates/app-state/src/call/outlook_reminders.rs +1 −1
@@ -82,7 +82,7 @@ impl OutlookReminders {
82 82 }
83 83
84 84 pub fn allows(&self, event: &CalendarEvent, now: DateTime<Utc>) -> bool {
85 // Google (and later sources) use the local Soon/Started phase only —
85 // Non-Outlook sources use the local Soon/Started phase only —
86 86 // Outlook ReminderView must not suppress them when the id is absent.
87 87 if event.source != CalendarSource::Outlook {
88 88 return true;
@@ -82,7 +82,7 @@ impl OutlookReminders {
82 }
82 }
83
83
84 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 —
85 // Non-Outlook sources use the local Soon/Started phase only —
86 // Outlook ReminderView must not suppress them when the id is absent.
86 // Outlook ReminderView must not suppress them when the id is absent.
87 if event.source != CalendarSource::Outlook {
87 if event.source != CalendarSource::Outlook {
88 return true;
88 return true;
crates/app-state/src/call/reminder.rs +1 −1
@@ -355,7 +355,7 @@ impl AppState {
355 355 .iter()
356 356 .chain(self.calendar_week.events.iter())
357 357 .find(|event| event.object_id == event_id)
358 .is_none_or(|event| event.source == chatsvc::CalendarSource::Outlook)
358 .is_some_and(|event| event.source == chatsvc::CalendarSource::Outlook)
359 359 }
360 360 }
361 361
@@ -355,7 +355,7 @@ impl AppState {
355 .iter()
355 .iter()
356 .chain(self.calendar_week.events.iter())
356 .chain(self.calendar_week.events.iter())
357 .find(|event| event.object_id == event_id)
357 .find(|event| event.object_id == event_id)
358 .is_none_or(|event| event.source == chatsvc::CalendarSource::Outlook)
358 .is_some_and(|event| event.source == chatsvc::CalendarSource::Outlook)
359 }
359 }
360}
360}
361
361
crates/app-state/src/call/schedule.rs +33 −0
@@ -316,6 +316,20 @@ impl AppState {
316 316 let _ = store::save_calendar_accounts(&store, &accounts);
317 317 result
318 318 }
319 chatsvc::CalendarSource::CalDav => {
320 let mut accounts = store::load_calendar_accounts(&store);
321 let account =
322 account_id.ok_or_else(|| "CalDAV account missing".to_owned())?;
323 let href = event_id.split('#').next().unwrap_or(&event_id).to_owned();
324 let result =
325 crate::caldav_sync::delete_caldav_event(&mut accounts, &account, &href)
326 .await;
327 let _ = store::save_calendar_accounts(&store, &accounts);
328 result
329 }
330 chatsvc::CalendarSource::Ics => {
331 Err("Read-only ICS subscriptions cannot delete events".into())
332 }
319 333 }
320 334 }
321 335 });
@@ -544,6 +558,25 @@ impl AppState {
544 558 let _ = store::save_calendar_accounts(&store, &accounts);
545 559 result
546 560 }
561 chatsvc::CalendarSource::CalDav => {
562 let mut accounts = store::load_calendar_accounts(&store);
563 let account =
564 account_id.ok_or_else(|| "CalDAV account missing".to_owned())?;
565 let href = event_id.split('#').next().unwrap_or(&event_id).to_owned();
566 let result = crate::caldav_sync::respond_caldav_event(
567 &mut accounts,
568 &account,
569 &href,
570 reply,
571 )
572 .await
573 .map(|_| ());
574 let _ = store::save_calendar_accounts(&store, &accounts);
575 result
576 }
577 chatsvc::CalendarSource::Ics => {
578 Err("Read-only ICS subscriptions cannot RSVP".into())
579 }
547 580 }
548 581 }
549 582 });
@@ -316,6 +316,20 @@ impl AppState {
316 let _ = store::save_calendar_accounts(&store, &accounts);
316 let _ = store::save_calendar_accounts(&store, &accounts);
317 result
317 result
318 }
318 }
319 chatsvc::CalendarSource::CalDav => {
320 let mut accounts = store::load_calendar_accounts(&store);
321 let account =
322 account_id.ok_or_else(|| "CalDAV account missing".to_owned())?;
323 let href = event_id.split('#').next().unwrap_or(&event_id).to_owned();
324 let result =
325 crate::caldav_sync::delete_caldav_event(&mut accounts, &account, &href)
326 .await;
327 let _ = store::save_calendar_accounts(&store, &accounts);
328 result
329 }
330 chatsvc::CalendarSource::Ics => {
331 Err("Read-only ICS subscriptions cannot delete events".into())
332 }
319 }
333 }
320 }
334 }
321 });
335 });
@@ -544,6 +558,25 @@ impl AppState {
544 let _ = store::save_calendar_accounts(&store, &accounts);
558 let _ = store::save_calendar_accounts(&store, &accounts);
545 result
559 result
546 }
560 }
561 chatsvc::CalendarSource::CalDav => {
562 let mut accounts = store::load_calendar_accounts(&store);
563 let account =
564 account_id.ok_or_else(|| "CalDAV account missing".to_owned())?;
565 let href = event_id.split('#').next().unwrap_or(&event_id).to_owned();
566 let result = crate::caldav_sync::respond_caldav_event(
567 &mut accounts,
568 &account,
569 &href,
570 reply,
571 )
572 .await
573 .map(|_| ());
574 let _ = store::save_calendar_accounts(&store, &accounts);
575 result
576 }
577 chatsvc::CalendarSource::Ics => {
578 Err("Read-only ICS subscriptions cannot RSVP".into())
579 }
547 }
580 }
548 }
581 }
549 });
582 });
crates/app-state/src/call/week.rs +49 −4
@@ -274,15 +274,44 @@ impl AppState {
274 274 }),
275 275 }
276 276 }
277 let mut caldav_count = None;
278 if accounts.has_caldav() {
279 match crate::caldav_sync::fetch_caldav_events(&mut fetched_accounts, from, to).await
280 {
281 Ok(events) => {
282 let _ = store::merge_caldav_metadata(&store, &fetched_accounts);
283 caldav_count = Some(events.len());
284 combined.extend(events);
285 }
286 Err(error) => failures.push(CalendarLoadFailure {
287 source: CalendarSource::CalDav,
288 message: error,
289 }),
290 }
291 }
292 if accounts.has_ics() {
293 match crate::ics_sync::fetch_ics_events(&accounts, from, to).await {
294 Ok(events) => combined.extend(events),
295 Err(error) => failures.push(CalendarLoadFailure {
296 source: CalendarSource::Ics,
297 message: error,
298 }),
299 }
300 }
277 301 crate::diagnostics::record(load_summary(
278 302 from,
279 303 to,
280 304 outlook_count,
281 305 google_count,
306 caldav_count,
282 307 started.elapsed().as_millis(),
283 308 &failures,
284 309 ));
285 (chatsvc::merge_calendar_events(combined), failures)
310 let home = home_calendar(&accounts);
311 (
312 chatsvc::merge_calendar_events(combined, home),
313 failures,
314 )
286 315 });
287 316 cx.spawn(async move |this, cx| {
288 317 let loaded = receiver.await.unwrap_or_else(|_| {
@@ -337,16 +366,18 @@ pub(crate) fn load_summary(
337 366 to: chrono::DateTime<chrono::Utc>,
338 367 outlook: Option<usize>,
339 368 google: Option<usize>,
369 caldav: Option<usize>,
340 370 elapsed_ms: u128,
341 371 failures: &[CalendarLoadFailure],
342 372 ) -> String {
343 373 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
344 374 let mut line = format!(
345 "calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",
375 "calendar grid: {}..{} outlook={} google={} caldav={} in {elapsed_ms} ms",
346 376 from.format("%Y-%m-%dT%H:%MZ"),
347 377 to.format("%Y-%m-%dT%H:%MZ"),
348 378 count(outlook),
349 379 count(google),
380 count(caldav),
350 381 );
351 382 for failure in failures {
352 383 line.push_str(&format!(
@@ -358,6 +389,20 @@ pub(crate) fn load_summary(
358 389 line
359 390 }
360 391
392 fn home_calendar(accounts: &store::CalendarAccounts) -> Option<chatsvc::HomeCalendar<'_>> {
393 use store::CalendarProvider;
394 let source = match accounts.home.provider {
395 CalendarProvider::Outlook => CalendarSource::Outlook,
396 CalendarProvider::Google => CalendarSource::Google,
397 CalendarProvider::CalDav => CalendarSource::CalDav,
398 };
399 Some(chatsvc::HomeCalendar {
400 source,
401 account_id: accounts.home.account_id.as_str(),
402 calendar_id: accounts.home.calendar_id.as_str(),
403 })
404 }
405
361 406 fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
362 407 for event in events {
363 408 let Some(old) = previous
@@ -642,8 +687,8 @@ mod tests {
642 687 message: "client_secret is missing".into(),
643 688 }];
644 689 assert_eq!(
645 load_summary(from, to, Some(3), None, 412, &failures),
646 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- in 412 ms; \
690 load_summary(from, to, Some(3), None, None, 412, &failures),
691 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- caldav=- in 412 ms; \
647 692 Google failed: client_secret is missing"
648 693 );
649 694 }
@@ -274,15 +274,44 @@ impl AppState {
274 }),
274 }),
275 }
275 }
276 }
276 }
277 let mut caldav_count = None;
278 if accounts.has_caldav() {
279 match crate::caldav_sync::fetch_caldav_events(&mut fetched_accounts, from, to).await
280 {
281 Ok(events) => {
282 let _ = store::merge_caldav_metadata(&store, &fetched_accounts);
283 caldav_count = Some(events.len());
284 combined.extend(events);
285 }
286 Err(error) => failures.push(CalendarLoadFailure {
287 source: CalendarSource::CalDav,
288 message: error,
289 }),
290 }
291 }
292 if accounts.has_ics() {
293 match crate::ics_sync::fetch_ics_events(&accounts, from, to).await {
294 Ok(events) => combined.extend(events),
295 Err(error) => failures.push(CalendarLoadFailure {
296 source: CalendarSource::Ics,
297 message: error,
298 }),
299 }
300 }
277 crate::diagnostics::record(load_summary(
301 crate::diagnostics::record(load_summary(
278 from,
302 from,
279 to,
303 to,
280 outlook_count,
304 outlook_count,
281 google_count,
305 google_count,
306 caldav_count,
282 started.elapsed().as_millis(),
307 started.elapsed().as_millis(),
283 &failures,
308 &failures,
284 ));
309 ));
285 (chatsvc::merge_calendar_events(combined), failures)
310 let home = home_calendar(&accounts);
311 (
312 chatsvc::merge_calendar_events(combined, home),
313 failures,
314 )
286 });
315 });
287 cx.spawn(async move |this, cx| {
316 cx.spawn(async move |this, cx| {
288 let loaded = receiver.await.unwrap_or_else(|_| {
317 let loaded = receiver.await.unwrap_or_else(|_| {
@@ -337,16 +366,18 @@ pub(crate) fn load_summary(
337 to: chrono::DateTime<chrono::Utc>,
366 to: chrono::DateTime<chrono::Utc>,
338 outlook: Option<usize>,
367 outlook: Option<usize>,
339 google: Option<usize>,
368 google: Option<usize>,
369 caldav: Option<usize>,
340 elapsed_ms: u128,
370 elapsed_ms: u128,
341 failures: &[CalendarLoadFailure],
371 failures: &[CalendarLoadFailure],
342) -> String {
372) -> String {
343 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
373 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
344 let mut line = format!(
374 let mut line = format!(
345 "calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",
375 "calendar grid: {}..{} outlook={} google={} caldav={} in {elapsed_ms} ms",
346 from.format("%Y-%m-%dT%H:%MZ"),
376 from.format("%Y-%m-%dT%H:%MZ"),
347 to.format("%Y-%m-%dT%H:%MZ"),
377 to.format("%Y-%m-%dT%H:%MZ"),
348 count(outlook),
378 count(outlook),
349 count(google),
379 count(google),
380 count(caldav),
350 );
381 );
351 for failure in failures {
382 for failure in failures {
352 line.push_str(&format!(
383 line.push_str(&format!(
@@ -358,6 +389,20 @@ pub(crate) fn load_summary(
358 line
389 line
359}
390}
360
391
392fn home_calendar(accounts: &store::CalendarAccounts) -> Option<chatsvc::HomeCalendar<'_>> {
393 use store::CalendarProvider;
394 let source = match accounts.home.provider {
395 CalendarProvider::Outlook => CalendarSource::Outlook,
396 CalendarProvider::Google => CalendarSource::Google,
397 CalendarProvider::CalDav => CalendarSource::CalDav,
398 };
399 Some(chatsvc::HomeCalendar {
400 source,
401 account_id: accounts.home.account_id.as_str(),
402 calendar_id: accounts.home.calendar_id.as_str(),
403 })
404}
405
361fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
406fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
362 for event in events {
407 for event in events {
363 let Some(old) = previous
408 let Some(old) = previous
@@ -642,8 +687,8 @@ mod tests {
642 message: "client_secret is missing".into(),
687 message: "client_secret is missing".into(),
643 }];
688 }];
644 assert_eq!(
689 assert_eq!(
645 load_summary(from, to, Some(3), None, 412, &failures),
690 load_summary(from, to, Some(3), None, None, 412, &failures),
646 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- in 412 ms; \
691 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- caldav=- in 412 ms; \
647 Google failed: client_secret is missing"
692 Google failed: client_secret is missing"
648 );
693 );
649 }
694 }
crates/app-state/src/google_calendar_sync.rs +17 −0
@@ -175,3 +175,20 @@ async fn ensure_access_token(
175 175 fn missing_client_id() -> String {
176 176 app_base::ui_locale::tr("settings.calendar.not_in_build")
177 177 }
178
179 #[cfg(test)]
180 mod tests {
181 use super::*;
182
183 #[test]
184 fn refresh_failure_message_is_err_not_empty_ok() {
185 // Contract for week load: auth refresh problems must be Err so CalendarLoadFailure fires.
186 let err: Result<Vec<CalendarEvent>, String> =
187 Err("google token refresh failed: HTTP 400: client_secret is missing".into());
188 assert!(err.is_err());
189 assert!(err.unwrap_err().contains("token refresh failed"));
190 let empty_ok: Result<Vec<CalendarEvent>, String> = Ok(Vec::new());
191 assert!(empty_ok.is_ok());
192 assert!(empty_ok.unwrap().is_empty());
193 }
194 }
@@ -175,3 +175,20 @@ async fn ensure_access_token(
175fn missing_client_id() -> String {
175fn missing_client_id() -> String {
176 app_base::ui_locale::tr("settings.calendar.not_in_build")
176 app_base::ui_locale::tr("settings.calendar.not_in_build")
177}
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182
183 #[test]
184 fn refresh_failure_message_is_err_not_empty_ok() {
185 // Contract for week load: auth refresh problems must be Err so CalendarLoadFailure fires.
186 let err: Result<Vec<CalendarEvent>, String> =
187 Err("google token refresh failed: HTTP 400: client_secret is missing".into());
188 assert!(err.is_err());
189 assert!(err.unwrap_err().contains("token refresh failed"));
190 let empty_ok: Result<Vec<CalendarEvent>, String> = Ok(Vec::new());
191 assert!(empty_ok.is_ok());
192 assert!(empty_ok.unwrap().is_empty());
193 }
194}
crates/app-state/src/ics_sync.rs added +105 −0
@@ -0,0 +1,105 @@
1 //! Read-only ICS subscriptions (holidays, Proton share links).
2
3 use chrono::{DateTime, Utc};
4 use store::{CalendarAccounts, IcsSubscription};
5 use uuid::Uuid;
6
7 use chatsvc::{CalendarEvent, CalendarSource, expand_events, parse_calendar};
8
9 pub async fn add_ics_subscription(
10 accounts: &mut CalendarAccounts,
11 url: &str,
12 summary: &str,
13 ) -> Result<String, String> {
14 let url = url.trim().to_owned();
15 if url.is_empty() {
16 return Err("ICS URL is empty".into());
17 }
18 // Smoke-fetch once so a bad URL fails at connect time.
19 let _ = fetch_one(&url, "tmp", summary, Utc::now(), Utc::now() + chrono::Duration::days(1))
20 .await?;
21 let id = Uuid::new_v4().to_string();
22 accounts.ics_subscriptions.push(IcsSubscription {
23 id: id.clone(),
24 url,
25 summary: if summary.trim().is_empty() {
26 "ICS".into()
27 } else {
28 summary.to_owned()
29 },
30 selected: true,
31 });
32 Ok(id)
33 }
34
35 pub async fn fetch_ics_events(
36 accounts: &CalendarAccounts,
37 start: DateTime<Utc>,
38 end: DateTime<Utc>,
39 ) -> Result<Vec<CalendarEvent>, String> {
40 let mut all = Vec::new();
41 for subscription in accounts
42 .ics_subscriptions
43 .iter()
44 .filter(|subscription| subscription.selected)
45 {
46 match fetch_one(
47 &subscription.url,
48 &subscription.id,
49 &subscription.summary,
50 start,
51 end,
52 )
53 .await
54 {
55 Ok(events) => all.extend(events),
56 Err(error) => return Err(format!("ICS {}: {error}", subscription.summary)),
57 }
58 }
59 Ok(all)
60 }
61
62 async fn fetch_one(
63 url: &str,
64 account_id: &str,
65 calendar_name: &str,
66 start: DateTime<Utc>,
67 end: DateTime<Utc>,
68 ) -> Result<Vec<CalendarEvent>, String> {
69 let client = reqwest::Client::new();
70 let response = client
71 .get(url)
72 .send()
73 .await
74 .map_err(|e| e.to_string())?;
75 if !response.status().is_success() {
76 return Err(format!("HTTP {}", response.status()));
77 }
78 let body = response.text().await.map_err(|e| e.to_string())?;
79 let parsed = parse_calendar(&body);
80 let expanded = expand_events(parsed, start, end);
81 Ok(expanded
82 .into_iter()
83 .map(|item| CalendarEvent {
84 object_id: format!("ics:{}:{}", account_id, item.uid),
85 subject: item.summary,
86 start: item.start,
87 end: item.end,
88 all_day: item.all_day,
89 cancelled: item.cancelled,
90 online: item.join_url.is_some(),
91 join_url: item.join_url,
92 ical_uid: Some(item.uid),
93 source: CalendarSource::Ics,
94 account_id: Some(account_id.to_owned()),
95 calendar_id: Some(url.to_owned()),
96 sources: vec![CalendarSource::Ics],
97 location: item.location,
98 body_preview: item.description.clone(),
99 body_html: item.description,
100 reminders: item.reminders_minutes,
101 calendar_name: Some(calendar_name.to_owned()),
102 ..Default::default()
103 })
104 .collect())
105 }
@@ -0,0 +1,105 @@
1//! Read-only ICS subscriptions (holidays, Proton share links).
2
3use chrono::{DateTime, Utc};
4use store::{CalendarAccounts, IcsSubscription};
5use uuid::Uuid;
6
7use chatsvc::{CalendarEvent, CalendarSource, expand_events, parse_calendar};
8
9pub async fn add_ics_subscription(
10 accounts: &mut CalendarAccounts,
11 url: &str,
12 summary: &str,
13) -> Result<String, String> {
14 let url = url.trim().to_owned();
15 if url.is_empty() {
16 return Err("ICS URL is empty".into());
17 }
18 // Smoke-fetch once so a bad URL fails at connect time.
19 let _ = fetch_one(&url, "tmp", summary, Utc::now(), Utc::now() + chrono::Duration::days(1))
20 .await?;
21 let id = Uuid::new_v4().to_string();
22 accounts.ics_subscriptions.push(IcsSubscription {
23 id: id.clone(),
24 url,
25 summary: if summary.trim().is_empty() {
26 "ICS".into()
27 } else {
28 summary.to_owned()
29 },
30 selected: true,
31 });
32 Ok(id)
33}
34
35pub async fn fetch_ics_events(
36 accounts: &CalendarAccounts,
37 start: DateTime<Utc>,
38 end: DateTime<Utc>,
39) -> Result<Vec<CalendarEvent>, String> {
40 let mut all = Vec::new();
41 for subscription in accounts
42 .ics_subscriptions
43 .iter()
44 .filter(|subscription| subscription.selected)
45 {
46 match fetch_one(
47 &subscription.url,
48 &subscription.id,
49 &subscription.summary,
50 start,
51 end,
52 )
53 .await
54 {
55 Ok(events) => all.extend(events),
56 Err(error) => return Err(format!("ICS {}: {error}", subscription.summary)),
57 }
58 }
59 Ok(all)
60}
61
62async fn fetch_one(
63 url: &str,
64 account_id: &str,
65 calendar_name: &str,
66 start: DateTime<Utc>,
67 end: DateTime<Utc>,
68) -> Result<Vec<CalendarEvent>, String> {
69 let client = reqwest::Client::new();
70 let response = client
71 .get(url)
72 .send()
73 .await
74 .map_err(|e| e.to_string())?;
75 if !response.status().is_success() {
76 return Err(format!("HTTP {}", response.status()));
77 }
78 let body = response.text().await.map_err(|e| e.to_string())?;
79 let parsed = parse_calendar(&body);
80 let expanded = expand_events(parsed, start, end);
81 Ok(expanded
82 .into_iter()
83 .map(|item| CalendarEvent {
84 object_id: format!("ics:{}:{}", account_id, item.uid),
85 subject: item.summary,
86 start: item.start,
87 end: item.end,
88 all_day: item.all_day,
89 cancelled: item.cancelled,
90 online: item.join_url.is_some(),
91 join_url: item.join_url,
92 ical_uid: Some(item.uid),
93 source: CalendarSource::Ics,
94 account_id: Some(account_id.to_owned()),
95 calendar_id: Some(url.to_owned()),
96 sources: vec![CalendarSource::Ics],
97 location: item.location,
98 body_preview: item.description.clone(),
99 body_html: item.description,
100 reminders: item.reminders_minutes,
101 calendar_name: Some(calendar_name.to_owned()),
102 ..Default::default()
103 })
104 .collect())
105}
crates/app-state/src/lib.rs +3 −0
@@ -7,6 +7,8 @@ pub mod backend;
7 7 pub mod banner_image;
8 8 pub mod browser_sign_in;
9 9 pub mod calendar_accounts_actions;
10 pub mod caldav_credentials;
11 pub mod caldav_sync;
10 12 pub mod call;
11 13 pub mod call_rows;
12 14 pub mod card_actions;
@@ -32,6 +34,7 @@ pub mod find_in_chat;
32 34 pub mod forward_selection;
33 35 pub mod gifs;
34 36 pub mod google_calendar_sync;
37 pub mod ics_sync;
35 38 pub mod image_view_gallery;
36 39 pub mod importance;
37 40 pub mod local_previews;
@@ -7,6 +7,8 @@ pub mod backend;
7pub mod banner_image;
7pub mod banner_image;
8pub mod browser_sign_in;
8pub mod browser_sign_in;
9pub mod calendar_accounts_actions;
9pub mod calendar_accounts_actions;
10pub mod caldav_credentials;
11pub mod caldav_sync;
10pub mod call;
12pub mod call;
11pub mod call_rows;
13pub mod call_rows;
12pub mod card_actions;
14pub mod card_actions;
@@ -32,6 +34,7 @@ pub mod find_in_chat;
32pub mod forward_selection;
34pub mod forward_selection;
33pub mod gifs;
35pub mod gifs;
34pub mod google_calendar_sync;
36pub mod google_calendar_sync;
37pub mod ics_sync;
35pub mod image_view_gallery;
38pub mod image_view_gallery;
36pub mod importance;
39pub mod importance;
37pub mod local_previews;
40pub mod local_previews;
crates/app-state/src/settings_section.rs +1 −0
@@ -10,6 +10,7 @@ pub enum SettingsSection {
10 10 Chats,
11 11 Calls,
12 12 Calendar,
13 CalendarAccounts,
13 14 Devices,
14 15 Agents,
15 16 Mcp,
@@ -10,6 +10,7 @@ pub enum SettingsSection {
10 Chats,
10 Chats,
11 Calls,
11 Calls,
12 Calendar,
12 Calendar,
13 CalendarAccounts,
13 Devices,
14 Devices,
14 Agents,
15 Agents,
15 Mcp,
16 Mcp,
crates/app-state/src/support_bundle.rs +1 −1
@@ -55,7 +55,7 @@ fn write_scrubbed_text(raw: &str, destination: &Path) -> io::Result<()> {
55 55 return Ok(());
56 56 }
57 57 let mut scrubber = Scrubber::default();
58 let scrubbed = scrubber.scrub(raw);
58 let scrubbed = crate::caldav_credentials::redact_secret_text(&scrubber.scrub(raw));
59 59 fs::write(destination, scrubbed)
60 60 }
61 61
@@ -55,7 +55,7 @@ fn write_scrubbed_text(raw: &str, destination: &Path) -> io::Result<()> {
55 return Ok(());
55 return Ok(());
56 }
56 }
57 let mut scrubber = Scrubber::default();
57 let mut scrubber = Scrubber::default();
58 let scrubbed = scrubber.scrub(raw);
58 let scrubbed = crate::caldav_credentials::redact_secret_text(&scrubber.scrub(raw));
59 fs::write(destination, scrubbed)
59 fs::write(destination, scrubbed)
60}
60}
61
61
crates/app/src/layout_guard.rs +2 −1
@@ -374,13 +374,14 @@ mod frames {
374 374 SettingsSection::Agents,
375 375 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
376 376 )];
377 const SETTINGS_SECTIONS: [SettingsSection; 11] = [
377 const SETTINGS_SECTIONS: [SettingsSection; 12] = [
378 378 SettingsSection::General,
379 379 SettingsSection::Notifications,
380 380 SettingsSection::Appearance,
381 381 SettingsSection::Chats,
382 382 SettingsSection::Calls,
383 383 SettingsSection::Calendar,
384 SettingsSection::CalendarAccounts,
384 385 SettingsSection::Devices,
385 386 SettingsSection::Agents,
386 387 SettingsSection::Mcp,
@@ -374,13 +374,14 @@ mod frames {
374 SettingsSection::Agents,
374 SettingsSection::Agents,
375 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
375 "Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
376 )];
376 )];
377 const SETTINGS_SECTIONS: [SettingsSection; 11] = [
377 const SETTINGS_SECTIONS: [SettingsSection; 12] = [
378 SettingsSection::General,
378 SettingsSection::General,
379 SettingsSection::Notifications,
379 SettingsSection::Notifications,
380 SettingsSection::Appearance,
380 SettingsSection::Appearance,
381 SettingsSection::Chats,
381 SettingsSection::Chats,
382 SettingsSection::Calls,
382 SettingsSection::Calls,
383 SettingsSection::Calendar,
383 SettingsSection::Calendar,
384 SettingsSection::CalendarAccounts,
384 SettingsSection::Devices,
385 SettingsSection::Devices,
385 SettingsSection::Agents,
386 SettingsSection::Agents,
386 SettingsSection::Mcp,
387 SettingsSection::Mcp,
crates/app/src/settings/caldav_form.rs added +251 −0
@@ -0,0 +1,251 @@
1 use gpui_kit::component::input::{Input, InputContentType, InputState};
2 use gpui_kit::component::{h_flex, v_flex};
3 use gpui_kit::*;
4
5 use super::rows::{control_row, stacked_field, text_button};
6 use crate::app_state::AppState;
7 use crate::i18n::tr;
8
9 pub struct CalDavForm {
10 app: Entity<AppState>,
11 url: Entity<InputState>,
12 username: Entity<InputState>,
13 password: Entity<InputState>,
14 show_form: bool,
15 }
16
17 impl CalDavForm {
18 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
19 let password = cx.new(|cx| InputState::new(window, cx));
20 password.update(cx, |input, cx| input.toggle_masked(window, cx));
21 CalDavForm {
22 app,
23 url: cx.new(|cx| {
24 InputState::new(window, cx).placeholder("https://cloud.example/remote.php/dav/")
25 }),
26 username: cx.new(|cx| InputState::new(window, cx)),
27 password,
28 show_form: false,
29 }
30 }
31 }
32
33 impl Render for CalDavForm {
34 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
35 if self.show_form {
36 let connect = self.app.clone();
37 let url_input = self.url.clone();
38 let user_input = self.username.clone();
39 let pass_input = self.password.clone();
40 let set_nextcloud = self.url.clone();
41 let set_fastmail = self.url.clone();
42 let set_icloud = self.url.clone();
43 let hide = cx.entity().clone();
44 v_flex()
45 .w_full()
46 .gap(px(8.))
47 .child(control_row(
48 tr("settings.calendar.caldav_title"),
49 tr("settings.calendar.caldav_hint"),
50 h_flex()
51 .gap_2()
52 .child(
53 text_button(
54 "settings-caldav-nextcloud",
55 tr("settings.calendar.caldav_template_nextcloud"),
56 )
57 .on_click(move |_, window, cx| {
58 set_nextcloud.update(cx, |input, cx| {
59 input.set_value(
60 "https://cloud.example/remote.php/dav/",
61 window,
62 cx,
63 );
64 });
65 }),
66 )
67 .child(
68 text_button(
69 "settings-caldav-fastmail",
70 tr("settings.calendar.caldav_template_fastmail"),
71 )
72 .on_click(move |_, window, cx| {
73 set_fastmail.update(cx, |input, cx| {
74 input.set_value(
75 "https://caldav.fastmail.com/dav/",
76 window,
77 cx,
78 );
79 });
80 }),
81 )
82 .child(
83 text_button(
84 "settings-caldav-icloud",
85 tr("settings.calendar.caldav_template_icloud"),
86 )
87 .on_click(move |_, window, cx| {
88 set_icloud.update(cx, |input, cx| {
89 input.set_value("https://caldav.icloud.com/", window, cx);
90 });
91 }),
92 ),
93 ))
94 .child(stacked_field(
95 tr("settings.calendar.caldav_url"),
96 "",
97 Input::new(&self.url),
98 ))
99 .child(stacked_field(
100 tr("settings.calendar.caldav_username"),
101 "",
102 Input::new(&self.username),
103 ))
104 .child(stacked_field(
105 tr("settings.calendar.caldav_password"),
106 "",
107 Input::new(&self.password)
108 .content_type(InputContentType::Password)
109 .mask_toggle(),
110 ))
111 .child(control_row(
112 tr("settings.calendar.caldav_title"),
113 "",
114 h_flex()
115 .gap_2()
116 .child(
117 text_button(
118 "settings-caldav-connect",
119 tr("settings.calendar.caldav_connect"),
120 )
121 .on_click(move |_, _, cx| {
122 let url = url_input.read(cx).value().to_string();
123 let username = user_input.read(cx).value().to_string();
124 let password = pass_input.read(cx).value().to_string();
125 connect.update(cx, |state, cx| {
126 state.connect_caldav_account(url, username, password, cx)
127 })
128 }),
129 )
130 .child(
131 text_button("settings-caldav-cancel", tr("common.cancel")).on_click(
132 move |_, _, cx| {
133 hide.update(cx, |form, cx| {
134 form.show_form = false;
135 cx.notify();
136 });
137 },
138 ),
139 ),
140 ))
141 } else {
142 let show = cx.entity().clone();
143 control_row(
144 tr("settings.calendar.caldav_title"),
145 tr("settings.calendar.caldav_hint"),
146 text_button(
147 "settings-caldav-show",
148 tr("settings.calendar.caldav_connect"),
149 )
150 .on_click(move |_, _, cx| {
151 show.update(cx, |form, cx| {
152 form.show_form = true;
153 cx.notify();
154 });
155 }),
156 )
157 }
158 }
159 }
160
161 pub struct IcsForm {
162 app: Entity<AppState>,
163 url: Entity<InputState>,
164 name: Entity<InputState>,
165 show_form: bool,
166 }
167
168 impl IcsForm {
169 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
170 IcsForm {
171 app,
172 url: cx.new(|cx| {
173 InputState::new(window, cx).placeholder("https://example.com/calendar.ics")
174 }),
175 name: cx.new(|cx| InputState::new(window, cx).placeholder("Holidays")),
176 show_form: false,
177 }
178 }
179 }
180
181 impl Render for IcsForm {
182 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
183 if self.show_form {
184 let ics_connect = self.app.clone();
185 let url_input = self.url.clone();
186 let name_input = self.name.clone();
187 let hide = cx.entity().clone();
188 v_flex()
189 .w_full()
190 .gap(px(8.))
191 .child(control_row(
192 tr("settings.calendar.ics_title"),
193 tr("settings.calendar.ics_hint"),
194 div(),
195 ))
196 .child(stacked_field(
197 tr("settings.calendar.ics_url"),
198 "",
199 Input::new(&self.url),
200 ))
201 .child(stacked_field(
202 tr("settings.calendar.ics_name"),
203 "",
204 Input::new(&self.name),
205 ))
206 .child(control_row(
207 tr("settings.calendar.ics_title"),
208 "",
209 h_flex()
210 .gap_2()
211 .child(
212 text_button(
213 "settings-ics-connect",
214 tr("settings.calendar.ics_connect"),
215 )
216 .on_click(move |_, _, cx| {
217 let url = url_input.read(cx).value().to_string();
218 let name = name_input.read(cx).value().to_string();
219 ics_connect.update(cx, |state, cx| {
220 state.connect_ics_subscription(url, name, cx)
221 })
222 }),
223 )
224 .child(
225 text_button("settings-ics-cancel", tr("common.cancel")).on_click(
226 move |_, _, cx| {
227 hide.update(cx, |form, cx| {
228 form.show_form = false;
229 cx.notify();
230 });
231 },
232 ),
233 ),
234 ))
235 } else {
236 let show = cx.entity().clone();
237 control_row(
238 tr("settings.calendar.ics_title"),
239 tr("settings.calendar.ics_hint"),
240 text_button("settings-ics-show", tr("settings.calendar.ics_connect")).on_click(
241 move |_, _, cx| {
242 show.update(cx, |form, cx| {
243 form.show_form = true;
244 cx.notify();
245 });
246 },
247 ),
248 )
249 }
250 }
251 }
@@ -0,0 +1,251 @@
1use gpui_kit::component::input::{Input, InputContentType, InputState};
2use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::*;
4
5use super::rows::{control_row, stacked_field, text_button};
6use crate::app_state::AppState;
7use crate::i18n::tr;
8
9pub struct CalDavForm {
10 app: Entity<AppState>,
11 url: Entity<InputState>,
12 username: Entity<InputState>,
13 password: Entity<InputState>,
14 show_form: bool,
15}
16
17impl CalDavForm {
18 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
19 let password = cx.new(|cx| InputState::new(window, cx));
20 password.update(cx, |input, cx| input.toggle_masked(window, cx));
21 CalDavForm {
22 app,
23 url: cx.new(|cx| {
24 InputState::new(window, cx).placeholder("https://cloud.example/remote.php/dav/")
25 }),
26 username: cx.new(|cx| InputState::new(window, cx)),
27 password,
28 show_form: false,
29 }
30 }
31}
32
33impl Render for CalDavForm {
34 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
35 if self.show_form {
36 let connect = self.app.clone();
37 let url_input = self.url.clone();
38 let user_input = self.username.clone();
39 let pass_input = self.password.clone();
40 let set_nextcloud = self.url.clone();
41 let set_fastmail = self.url.clone();
42 let set_icloud = self.url.clone();
43 let hide = cx.entity().clone();
44 v_flex()
45 .w_full()
46 .gap(px(8.))
47 .child(control_row(
48 tr("settings.calendar.caldav_title"),
49 tr("settings.calendar.caldav_hint"),
50 h_flex()
51 .gap_2()
52 .child(
53 text_button(
54 "settings-caldav-nextcloud",
55 tr("settings.calendar.caldav_template_nextcloud"),
56 )
57 .on_click(move |_, window, cx| {
58 set_nextcloud.update(cx, |input, cx| {
59 input.set_value(
60 "https://cloud.example/remote.php/dav/",
61 window,
62 cx,
63 );
64 });
65 }),
66 )
67 .child(
68 text_button(
69 "settings-caldav-fastmail",
70 tr("settings.calendar.caldav_template_fastmail"),
71 )
72 .on_click(move |_, window, cx| {
73 set_fastmail.update(cx, |input, cx| {
74 input.set_value(
75 "https://caldav.fastmail.com/dav/",
76 window,
77 cx,
78 );
79 });
80 }),
81 )
82 .child(
83 text_button(
84 "settings-caldav-icloud",
85 tr("settings.calendar.caldav_template_icloud"),
86 )
87 .on_click(move |_, window, cx| {
88 set_icloud.update(cx, |input, cx| {
89 input.set_value("https://caldav.icloud.com/", window, cx);
90 });
91 }),
92 ),
93 ))
94 .child(stacked_field(
95 tr("settings.calendar.caldav_url"),
96 "",
97 Input::new(&self.url),
98 ))
99 .child(stacked_field(
100 tr("settings.calendar.caldav_username"),
101 "",
102 Input::new(&self.username),
103 ))
104 .child(stacked_field(
105 tr("settings.calendar.caldav_password"),
106 "",
107 Input::new(&self.password)
108 .content_type(InputContentType::Password)
109 .mask_toggle(),
110 ))
111 .child(control_row(
112 tr("settings.calendar.caldav_title"),
113 "",
114 h_flex()
115 .gap_2()
116 .child(
117 text_button(
118 "settings-caldav-connect",
119 tr("settings.calendar.caldav_connect"),
120 )
121 .on_click(move |_, _, cx| {
122 let url = url_input.read(cx).value().to_string();
123 let username = user_input.read(cx).value().to_string();
124 let password = pass_input.read(cx).value().to_string();
125 connect.update(cx, |state, cx| {
126 state.connect_caldav_account(url, username, password, cx)
127 })
128 }),
129 )
130 .child(
131 text_button("settings-caldav-cancel", tr("common.cancel")).on_click(
132 move |_, _, cx| {
133 hide.update(cx, |form, cx| {
134 form.show_form = false;
135 cx.notify();
136 });
137 },
138 ),
139 ),
140 ))
141 } else {
142 let show = cx.entity().clone();
143 control_row(
144 tr("settings.calendar.caldav_title"),
145 tr("settings.calendar.caldav_hint"),
146 text_button(
147 "settings-caldav-show",
148 tr("settings.calendar.caldav_connect"),
149 )
150 .on_click(move |_, _, cx| {
151 show.update(cx, |form, cx| {
152 form.show_form = true;
153 cx.notify();
154 });
155 }),
156 )
157 }
158 }
159}
160
161pub struct IcsForm {
162 app: Entity<AppState>,
163 url: Entity<InputState>,
164 name: Entity<InputState>,
165 show_form: bool,
166}
167
168impl IcsForm {
169 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
170 IcsForm {
171 app,
172 url: cx.new(|cx| {
173 InputState::new(window, cx).placeholder("https://example.com/calendar.ics")
174 }),
175 name: cx.new(|cx| InputState::new(window, cx).placeholder("Holidays")),
176 show_form: false,
177 }
178 }
179}
180
181impl Render for IcsForm {
182 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
183 if self.show_form {
184 let ics_connect = self.app.clone();
185 let url_input = self.url.clone();
186 let name_input = self.name.clone();
187 let hide = cx.entity().clone();
188 v_flex()
189 .w_full()
190 .gap(px(8.))
191 .child(control_row(
192 tr("settings.calendar.ics_title"),
193 tr("settings.calendar.ics_hint"),
194 div(),
195 ))
196 .child(stacked_field(
197 tr("settings.calendar.ics_url"),
198 "",
199 Input::new(&self.url),
200 ))
201 .child(stacked_field(
202 tr("settings.calendar.ics_name"),
203 "",
204 Input::new(&self.name),
205 ))
206 .child(control_row(
207 tr("settings.calendar.ics_title"),
208 "",
209 h_flex()
210 .gap_2()
211 .child(
212 text_button(
213 "settings-ics-connect",
214 tr("settings.calendar.ics_connect"),
215 )
216 .on_click(move |_, _, cx| {
217 let url = url_input.read(cx).value().to_string();
218 let name = name_input.read(cx).value().to_string();
219 ics_connect.update(cx, |state, cx| {
220 state.connect_ics_subscription(url, name, cx)
221 })
222 }),
223 )
224 .child(
225 text_button("settings-ics-cancel", tr("common.cancel")).on_click(
226 move |_, _, cx| {
227 hide.update(cx, |form, cx| {
228 form.show_form = false;
229 cx.notify();
230 });
231 },
232 ),
233 ),
234 ))
235 } else {
236 let show = cx.entity().clone();
237 control_row(
238 tr("settings.calendar.ics_title"),
239 tr("settings.calendar.ics_hint"),
240 text_button("settings-ics-show", tr("settings.calendar.ics_connect")).on_click(
241 move |_, _, cx| {
242 show.update(cx, |form, cx| {
243 form.show_form = true;
244 cx.notify();
245 });
246 },
247 ),
248 )
249 }
250 }
251}
crates/app/src/settings/calendar.rs +158 −5
@@ -18,11 +18,9 @@ use crate::call::calendar_prefs::{CalendarPrefs, DefaultView, TimeScale, Weekend
18 18 use crate::i18n::tr;
19 19 use crate::theme;
20 20
21 pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
22 let accounts = app.read(cx).calendar_accounts();
23 let pending = app.read(cx).google_connect_pending().is_some();
21 pub fn render_view(app: &Entity<AppState>, cx: &App) -> Div {
24 22 let prefs = app.read(cx).calendar_prefs.clone();
25 let mut body = v_flex()
23 v_flex()
26 24 .w_full()
27 25 .child(caption(tr("settings.calendar.section_view")))
28 26 .children(view_rows(
@@ -30,11 +28,37 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
30 28 &prefs,
31 29 app.read(cx).calendar_layout().first_day,
32 30 ))
31 }
32
33 pub fn render_accounts(
34 app: &Entity<AppState>,
35 caldav: Option<&Entity<super::caldav_form::CalDavForm>>,
36 ics: Option<&Entity<super::caldav_form::IcsForm>>,
37 cx: &App,
38 ) -> Div {
39 let accounts = app.read(cx).calendar_accounts();
40 let pending = app.read(cx).google_connect_pending().is_some();
41 let mut body = v_flex()
42 .w_full()
33 43 .child(caption(tr("settings.calendar.section_google")))
34 44 .child(connect_row(app, accounts.has_google(), pending));
35 45 for account in &accounts.google_accounts {
36 46 body = body.child(account_block(app, account, &accounts));
37 47 }
48 body = body.child(caption(tr("settings.calendar.section_caldav")));
49 for account in &accounts.caldav_accounts {
50 body = body.child(caldav_account_block(app, account, &accounts));
51 }
52 if let Some(form) = caldav {
53 body = body.child(form.clone());
54 }
55 body = body.child(caption(tr("settings.calendar.section_ics")));
56 for subscription in &accounts.ics_subscriptions {
57 body = body.child(ics_block(app, subscription));
58 }
59 if let Some(form) = ics {
60 body = body.child(form.clone());
61 }
38 62 body = body
39 63 .child(caption(tr("settings.calendar.section_home")))
40 64 .child(home_choices(app, &accounts))
@@ -60,7 +84,7 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
60 84 })
61 85 }),
62 86 );
63 } else if accounts.google_accounts.is_empty() {
87 } else if accounts.google_accounts.is_empty() && accounts.caldav_accounts.is_empty() {
64 88 body = body.child(control_row(
65 89 tr("settings.calendar.no_extra_targets"),
66 90 tr("settings.calendar.connect_then_dual_write"),
@@ -207,6 +231,113 @@ fn tr_args_write(summary: &str) -> String {
207 231 crate::i18n::tr_args("settings.calendar.also_write_to", &args)
208 232 }
209 233
234 fn caldav_account_block(
235 app: &Entity<AppState>,
236 account: &store::CalDavAccount,
237 accounts: &store::CalendarAccounts,
238 ) -> Div {
239 let disconnect_app = app.clone();
240 let account_id = account.id.clone();
241 let mut block = v_flex().w_full().child(control_row(
242 format!("{} · {}", account.display_name, account.url),
243 tr("settings.calendar.caldav_title"),
244 text_button(
245 format!("settings-caldav-disconnect-{}", account.id),
246 tr("settings.calendar.disconnect"),
247 )
248 .on_click(move |_, _, cx| {
249 disconnect_app.update(cx, |state, cx| {
250 state.disconnect_caldav_account(&account_id, cx)
251 })
252 }),
253 ));
254 for calendar in &account.calendars {
255 let toggle_app = app.clone();
256 let account_id = account.id.clone();
257 let calendar_id = calendar.id.clone();
258 let write_ref = CalendarRef::caldav(&account.id, &calendar.id);
259 let is_home = accounts.home.key() == write_ref.key();
260 let is_write = accounts
261 .write_targets
262 .iter()
263 .any(|target| target.key() == write_ref.key());
264 let detail = if calendar.writable {
265 tr("settings.calendar.show_in_grid")
266 } else {
267 tr("settings.calendar.caldav_readonly")
268 };
269 block = block.child(
270 toggle_row(
271 format!("settings-caldav-cal-{}", calendar.id),
272 calendar.summary.clone(),
273 detail,
274 theme::text_muted(),
275 calendar.selected,
276 )
277 .on_click(move |_, _, cx| {
278 toggle_app.update(cx, |state, cx| {
279 state.toggle_caldav_calendar_selected(&account_id, &calendar_id, cx)
280 })
281 }),
282 );
283 if calendar.writable && !is_home {
284 let write_app = app.clone();
285 let target = write_ref;
286 block = block.child(
287 toggle_row(
288 format!("settings-caldav-write-{}", calendar.id),
289 tr_args_write(&calendar.summary),
290 "",
291 theme::text_muted(),
292 is_write,
293 )
294 .on_click(move |_, _, cx| {
295 write_app.update(cx, |state, cx| {
296 state.toggle_write_target(target.clone(), cx)
297 })
298 }),
299 );
300 }
301 }
302 block
303 }
304
305 fn ics_block(app: &Entity<AppState>, subscription: &store::IcsSubscription) -> Div {
306 let disconnect = app.clone();
307 let toggle = app.clone();
308 let id = subscription.id.clone();
309 let id_toggle = subscription.id.clone();
310 v_flex()
311 .w_full()
312 .child(control_row(
313 subscription.summary.clone(),
314 subscription.url.clone(),
315 text_button(
316 format!("settings-ics-disconnect-{}", subscription.id),
317 tr("settings.calendar.disconnect"),
318 )
319 .on_click(move |_, _, cx| {
320 disconnect.update(cx, |state, cx| {
321 state.disconnect_ics_subscription(&id, cx)
322 })
323 }),
324 ))
325 .child(
326 toggle_row(
327 format!("settings-ics-selected-{}", subscription.id),
328 tr("settings.calendar.show_in_grid"),
329 tr("settings.calendar.caldav_readonly"),
330 theme::text_muted(),
331 subscription.selected,
332 )
333 .on_click(move |_, _, cx| {
334 toggle.update(cx, |state, cx| {
335 state.toggle_ics_subscription_selected(&id_toggle, cx)
336 })
337 }),
338 )
339 }
340
210 341 fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {
211 342 let mut choices = v_flex().w_full();
212 343 let outlook_app = app.clone();
@@ -248,6 +379,28 @@ fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> D
248 379 );
249 380 }
250 381 }
382 for account in &accounts.caldav_accounts {
383 for calendar in &account.calendars {
384 if !calendar.writable {
385 continue;
386 }
387 let home_app = app.clone();
388 let target = CalendarRef::caldav(&account.id, &calendar.id);
389 let selected = accounts.home.key() == target.key();
390 choices = choices.child(
391 toggle_row(
392 format!("settings-home-caldav-{}", calendar.id),
393 format!("CalDAV · {}", calendar.summary),
394 account.username.clone(),
395 theme::text_muted(),
396 selected,
397 )
398 .on_click(move |_, _, cx| {
399 home_app.update(cx, |state, cx| state.set_home_calendar(target.clone(), cx))
400 }),
401 );
402 }
403 }
251 404 choices
252 405 }
253 406
@@ -18,11 +18,9 @@ use crate::call::calendar_prefs::{CalendarPrefs, DefaultView, TimeScale, Weekend
18use crate::i18n::tr;
18use crate::i18n::tr;
19use crate::theme;
19use crate::theme;
20
20
21pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
21pub fn render_view(app: &Entity<AppState>, cx: &App) -> Div {
22 let accounts = app.read(cx).calendar_accounts();
23 let pending = app.read(cx).google_connect_pending().is_some();
24 let prefs = app.read(cx).calendar_prefs.clone();
22 let prefs = app.read(cx).calendar_prefs.clone();
25 let mut body = v_flex()
23 v_flex()
26 .w_full()
24 .w_full()
27 .child(caption(tr("settings.calendar.section_view")))
25 .child(caption(tr("settings.calendar.section_view")))
28 .children(view_rows(
26 .children(view_rows(
@@ -30,11 +28,37 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
30 &prefs,
28 &prefs,
31 app.read(cx).calendar_layout().first_day,
29 app.read(cx).calendar_layout().first_day,
32 ))
30 ))
31}
32
33pub fn render_accounts(
34 app: &Entity<AppState>,
35 caldav: Option<&Entity<super::caldav_form::CalDavForm>>,
36 ics: Option<&Entity<super::caldav_form::IcsForm>>,
37 cx: &App,
38) -> Div {
39 let accounts = app.read(cx).calendar_accounts();
40 let pending = app.read(cx).google_connect_pending().is_some();
41 let mut body = v_flex()
42 .w_full()
33 .child(caption(tr("settings.calendar.section_google")))
43 .child(caption(tr("settings.calendar.section_google")))
34 .child(connect_row(app, accounts.has_google(), pending));
44 .child(connect_row(app, accounts.has_google(), pending));
35 for account in &accounts.google_accounts {
45 for account in &accounts.google_accounts {
36 body = body.child(account_block(app, account, &accounts));
46 body = body.child(account_block(app, account, &accounts));
37 }
47 }
48 body = body.child(caption(tr("settings.calendar.section_caldav")));
49 for account in &accounts.caldav_accounts {
50 body = body.child(caldav_account_block(app, account, &accounts));
51 }
52 if let Some(form) = caldav {
53 body = body.child(form.clone());
54 }
55 body = body.child(caption(tr("settings.calendar.section_ics")));
56 for subscription in &accounts.ics_subscriptions {
57 body = body.child(ics_block(app, subscription));
58 }
59 if let Some(form) = ics {
60 body = body.child(form.clone());
61 }
38 body = body
62 body = body
39 .child(caption(tr("settings.calendar.section_home")))
63 .child(caption(tr("settings.calendar.section_home")))
40 .child(home_choices(app, &accounts))
64 .child(home_choices(app, &accounts))
@@ -60,7 +84,7 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
60 })
84 })
61 }),
85 }),
62 );
86 );
63 } else if accounts.google_accounts.is_empty() {
87 } else if accounts.google_accounts.is_empty() && accounts.caldav_accounts.is_empty() {
64 body = body.child(control_row(
88 body = body.child(control_row(
65 tr("settings.calendar.no_extra_targets"),
89 tr("settings.calendar.no_extra_targets"),
66 tr("settings.calendar.connect_then_dual_write"),
90 tr("settings.calendar.connect_then_dual_write"),
@@ -207,6 +231,113 @@ fn tr_args_write(summary: &str) -> String {
207 crate::i18n::tr_args("settings.calendar.also_write_to", &args)
231 crate::i18n::tr_args("settings.calendar.also_write_to", &args)
208}
232}
209
233
234fn caldav_account_block(
235 app: &Entity<AppState>,
236 account: &store::CalDavAccount,
237 accounts: &store::CalendarAccounts,
238) -> Div {
239 let disconnect_app = app.clone();
240 let account_id = account.id.clone();
241 let mut block = v_flex().w_full().child(control_row(
242 format!("{} · {}", account.display_name, account.url),
243 tr("settings.calendar.caldav_title"),
244 text_button(
245 format!("settings-caldav-disconnect-{}", account.id),
246 tr("settings.calendar.disconnect"),
247 )
248 .on_click(move |_, _, cx| {
249 disconnect_app.update(cx, |state, cx| {
250 state.disconnect_caldav_account(&account_id, cx)
251 })
252 }),
253 ));
254 for calendar in &account.calendars {
255 let toggle_app = app.clone();
256 let account_id = account.id.clone();
257 let calendar_id = calendar.id.clone();
258 let write_ref = CalendarRef::caldav(&account.id, &calendar.id);
259 let is_home = accounts.home.key() == write_ref.key();
260 let is_write = accounts
261 .write_targets
262 .iter()
263 .any(|target| target.key() == write_ref.key());
264 let detail = if calendar.writable {
265 tr("settings.calendar.show_in_grid")
266 } else {
267 tr("settings.calendar.caldav_readonly")
268 };
269 block = block.child(
270 toggle_row(
271 format!("settings-caldav-cal-{}", calendar.id),
272 calendar.summary.clone(),
273 detail,
274 theme::text_muted(),
275 calendar.selected,
276 )
277 .on_click(move |_, _, cx| {
278 toggle_app.update(cx, |state, cx| {
279 state.toggle_caldav_calendar_selected(&account_id, &calendar_id, cx)
280 })
281 }),
282 );
283 if calendar.writable && !is_home {
284 let write_app = app.clone();
285 let target = write_ref;
286 block = block.child(
287 toggle_row(
288 format!("settings-caldav-write-{}", calendar.id),
289 tr_args_write(&calendar.summary),
290 "",
291 theme::text_muted(),
292 is_write,
293 )
294 .on_click(move |_, _, cx| {
295 write_app.update(cx, |state, cx| {
296 state.toggle_write_target(target.clone(), cx)
297 })
298 }),
299 );
300 }
301 }
302 block
303}
304
305fn ics_block(app: &Entity<AppState>, subscription: &store::IcsSubscription) -> Div {
306 let disconnect = app.clone();
307 let toggle = app.clone();
308 let id = subscription.id.clone();
309 let id_toggle = subscription.id.clone();
310 v_flex()
311 .w_full()
312 .child(control_row(
313 subscription.summary.clone(),
314 subscription.url.clone(),
315 text_button(
316 format!("settings-ics-disconnect-{}", subscription.id),
317 tr("settings.calendar.disconnect"),
318 )
319 .on_click(move |_, _, cx| {
320 disconnect.update(cx, |state, cx| {
321 state.disconnect_ics_subscription(&id, cx)
322 })
323 }),
324 ))
325 .child(
326 toggle_row(
327 format!("settings-ics-selected-{}", subscription.id),
328 tr("settings.calendar.show_in_grid"),
329 tr("settings.calendar.caldav_readonly"),
330 theme::text_muted(),
331 subscription.selected,
332 )
333 .on_click(move |_, _, cx| {
334 toggle.update(cx, |state, cx| {
335 state.toggle_ics_subscription_selected(&id_toggle, cx)
336 })
337 }),
338 )
339}
340
210fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {
341fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {
211 let mut choices = v_flex().w_full();
342 let mut choices = v_flex().w_full();
212 let outlook_app = app.clone();
343 let outlook_app = app.clone();
@@ -248,6 +379,28 @@ fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> D
248 );
379 );
249 }
380 }
250 }
381 }
382 for account in &accounts.caldav_accounts {
383 for calendar in &account.calendars {
384 if !calendar.writable {
385 continue;
386 }
387 let home_app = app.clone();
388 let target = CalendarRef::caldav(&account.id, &calendar.id);
389 let selected = accounts.home.key() == target.key();
390 choices = choices.child(
391 toggle_row(
392 format!("settings-home-caldav-{}", calendar.id),
393 format!("CalDAV · {}", calendar.summary),
394 account.username.clone(),
395 theme::text_muted(),
396 selected,
397 )
398 .on_click(move |_, _, cx| {
399 home_app.update(cx, |state, cx| state.set_home_calendar(target.clone(), cx))
400 }),
401 );
402 }
403 }
251 choices
404 choices
252}
405}
253
406
crates/app/src/settings/dialog.rs +23 −1
@@ -6,6 +6,7 @@ use gpui_kit::component::{h_flex, v_flex};
6 6 use gpui_kit::prelude::FluentBuilder as _;
7 7 use gpui_kit::*;
8 8
9 use super::caldav_form::{CalDavForm, IcsForm};
9 10 use super::devices::DevicesView;
10 11 use super::help::HelpView;
11 12 use super::mcp::McpView;
@@ -68,6 +69,8 @@ pub struct SettingsDialog {
68 69 help: Option<Entity<HelpView>>,
69 70 mcp: Option<Entity<McpView>>,
70 71 agents: Option<Entity<AgentsSettings>>,
72 caldav: Option<Entity<CalDavForm>>,
73 ics: Option<Entity<IcsForm>>,
71 74 body_scroll: ScrollHandle,
72 75 focus_handle: FocusHandle,
73 76 search: Entity<InputState>,
@@ -108,6 +111,8 @@ impl SettingsDialog {
108 111 help: None,
109 112 mcp: None,
110 113 agents: None,
114 caldav: None,
115 ics: None,
111 116 body_scroll: ScrollHandle::new(),
112 117 focus_handle,
113 118 search,
@@ -152,6 +157,16 @@ impl SettingsDialog {
152 157 self.agents = crate::agents::runs_handle(cx)
153 158 .map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
154 159 }
160 if section == SettingsSection::CalendarAccounts {
161 if self.caldav.is_none() {
162 let app = self.app.clone();
163 self.caldav = Some(cx.new(|cx| CalDavForm::new(app, window, cx)));
164 }
165 if self.ics.is_none() {
166 let app = self.app.clone();
167 self.ics = Some(cx.new(|cx| IcsForm::new(app, window, cx)));
168 }
169 }
155 170 cx.notify();
156 171 }
157 172
@@ -203,7 +218,14 @@ impl SettingsDialog {
203 218 SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),
204 219 SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
205 220 SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),
206 SettingsSection::Calendar => calendar::render(&self.app, cx).into_any_element(),
221 SettingsSection::Calendar => calendar::render_view(&self.app, cx).into_any_element(),
222 SettingsSection::CalendarAccounts => calendar::render_accounts(
223 &self.app,
224 self.caldav.as_ref(),
225 self.ics.as_ref(),
226 cx,
227 )
228 .into_any_element(),
207 229 SettingsSection::Devices => self
208 230 .devices
209 231 .clone()
@@ -6,6 +6,7 @@ use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
7use gpui_kit::*;
8
8
9use super::caldav_form::{CalDavForm, IcsForm};
9use super::devices::DevicesView;
10use super::devices::DevicesView;
10use super::help::HelpView;
11use super::help::HelpView;
11use super::mcp::McpView;
12use super::mcp::McpView;
@@ -68,6 +69,8 @@ pub struct SettingsDialog {
68 help: Option<Entity<HelpView>>,
69 help: Option<Entity<HelpView>>,
69 mcp: Option<Entity<McpView>>,
70 mcp: Option<Entity<McpView>>,
70 agents: Option<Entity<AgentsSettings>>,
71 agents: Option<Entity<AgentsSettings>>,
72 caldav: Option<Entity<CalDavForm>>,
73 ics: Option<Entity<IcsForm>>,
71 body_scroll: ScrollHandle,
74 body_scroll: ScrollHandle,
72 focus_handle: FocusHandle,
75 focus_handle: FocusHandle,
73 search: Entity<InputState>,
76 search: Entity<InputState>,
@@ -108,6 +111,8 @@ impl SettingsDialog {
108 help: None,
111 help: None,
109 mcp: None,
112 mcp: None,
110 agents: None,
113 agents: None,
114 caldav: None,
115 ics: None,
111 body_scroll: ScrollHandle::new(),
116 body_scroll: ScrollHandle::new(),
112 focus_handle,
117 focus_handle,
113 search,
118 search,
@@ -152,6 +157,16 @@ impl SettingsDialog {
152 self.agents = crate::agents::runs_handle(cx)
157 self.agents = crate::agents::runs_handle(cx)
153 .map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
158 .map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
154 }
159 }
160 if section == SettingsSection::CalendarAccounts {
161 if self.caldav.is_none() {
162 let app = self.app.clone();
163 self.caldav = Some(cx.new(|cx| CalDavForm::new(app, window, cx)));
164 }
165 if self.ics.is_none() {
166 let app = self.app.clone();
167 self.ics = Some(cx.new(|cx| IcsForm::new(app, window, cx)));
168 }
169 }
155 cx.notify();
170 cx.notify();
156 }
171 }
157
172
@@ -203,7 +218,14 @@ impl SettingsDialog {
203 SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),
218 SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),
204 SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
219 SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
205 SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),
220 SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),
206 SettingsSection::Calendar => calendar::render(&self.app, cx).into_any_element(),
221 SettingsSection::Calendar => calendar::render_view(&self.app, cx).into_any_element(),
222 SettingsSection::CalendarAccounts => calendar::render_accounts(
223 &self.app,
224 self.caldav.as_ref(),
225 self.ics.as_ref(),
226 cx,
227 )
228 .into_any_element(),
207 SettingsSection::Devices => self
229 SettingsSection::Devices => self
208 .devices
230 .devices
209 .clone()
231 .clone()
crates/app/src/settings/mod.rs +1 −0
@@ -1,6 +1,7 @@
1 1 mod about;
2 2 mod account;
3 3 mod appearance;
4 mod caldav_form;
4 5 mod calendar;
5 6 mod calls;
6 7 mod chats;
@@ -1,6 +1,7 @@
1mod about;
1mod about;
2mod account;
2mod account;
3mod appearance;
3mod appearance;
4mod caldav_form;
4mod calendar;
5mod calendar;
5mod calls;
6mod calls;
6mod chats;
7mod chats;
crates/app/src/settings/nav.rs +26 −4
@@ -9,13 +9,14 @@ use crate::settings_section::SettingsSection;
9 9 use crate::theme;
10 10 use crate::views::widgets::icon;
11 11
12 pub const TEAMS_GROUP: [SettingsSection; 7] = [
12 pub const TEAMS_GROUP: [SettingsSection; 8] = [
13 13 SettingsSection::General,
14 14 SettingsSection::Notifications,
15 15 SettingsSection::Appearance,
16 16 SettingsSection::Chats,
17 17 SettingsSection::Calls,
18 18 SettingsSection::Calendar,
19 SettingsSection::CalendarAccounts,
19 20 SettingsSection::Devices,
20 21 ];
21 22 pub const RUSTY_GROUP: [SettingsSection; 2] = [SettingsSection::Agents, SettingsSection::Mcp];
@@ -27,14 +28,21 @@ const ITEM_RADIUS: f32 = 6.;
27 28 const ITEM_ICON: f32 = 16.;
28 29 const NAV_PADDING_X: f32 = 12.;
29 30
30 const CALENDAR_TERMS: [&str; 10] = [
31 const CALENDAR_VIEW_TERMS: [&str; 5] = [
31 32 "settings.calendar.default_view",
32 33 "settings.calendar.work_days",
33 34 "settings.calendar.work_hours",
34 35 "settings.calendar.time_scale",
35 36 "settings.calendar.weekend",
37 ];
38
39 const CALENDAR_ACCOUNTS_TERMS: [&str; 9] = [
36 40 "settings.calendar.google_title",
37 41 "settings.calendar.connect_button",
42 "settings.calendar.caldav_title",
43 "settings.calendar.caldav_connect",
44 "settings.calendar.ics_title",
45 "settings.calendar.ics_connect",
38 46 "settings.calendar.section_home",
39 47 "settings.calendar.section_write",
40 48 "settings.calendar.outlook_mailbox",
@@ -82,7 +90,11 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
82 90 tr("settings.chats.markdown"),
83 91 ],
84 92 SettingsSection::Calls => vec![tr("settings.calls.ringtones")],
85 SettingsSection::Calendar => CALENDAR_TERMS.iter().map(|key| tr(key)).collect(),
93 SettingsSection::Calendar => CALENDAR_VIEW_TERMS.iter().map(|key| tr(key)).collect(),
94 SettingsSection::CalendarAccounts => CALENDAR_ACCOUNTS_TERMS
95 .iter()
96 .map(|key| tr(key))
97 .collect(),
86 98 SettingsSection::Devices => vec![
87 99 "Speaker".to_owned(),
88 100 "Microphone".to_owned(),
@@ -137,6 +149,7 @@ pub fn label(section: SettingsSection) -> String {
137 149 SettingsSection::Chats => tr("settings.nav.chats"),
138 150 SettingsSection::Calls => tr("settings.nav.calls"),
139 151 SettingsSection::Calendar => tr("settings.nav.calendar"),
152 SettingsSection::CalendarAccounts => tr("settings.nav.calendar_accounts"),
140 153 SettingsSection::Devices => tr("settings.nav.devices"),
141 154 SettingsSection::Agents => tr("settings.nav.agents"),
142 155 SettingsSection::Mcp => tr("settings.nav.mcp"),
@@ -153,6 +166,7 @@ fn icon_name(section: SettingsSection) -> IconName {
153 166 SettingsSection::Chats => IconName::MessageSquare,
154 167 SettingsSection::Calls => IconName::Phone,
155 168 SettingsSection::Calendar => IconName::Calendar,
169 SettingsSection::CalendarAccounts => IconName::Calendar,
156 170 SettingsSection::Devices => IconName::Headphones,
157 171 SettingsSection::Agents => IconName::Bot,
158 172 SettingsSection::Mcp => IconName::Plug,
@@ -177,6 +191,7 @@ fn element_id(section: SettingsSection) -> &'static str {
177 191 SettingsSection::Chats => "settings-nav-chats",
178 192 SettingsSection::Calls => "settings-nav-calls",
179 193 SettingsSection::Calendar => "settings-nav-calendar",
194 SettingsSection::CalendarAccounts => "settings-nav-calendar-accounts",
180 195 SettingsSection::Devices => "settings-nav-devices",
181 196 SettingsSection::Agents => "settings-nav-agents",
182 197 SettingsSection::Mcp => "settings-nav-mcp",
@@ -424,7 +439,8 @@ mod tests {
424 439 "settings.chats.enter_to",
425 440 "settings.chats.markdown",
426 441 ],
427 SettingsSection::Calendar => &super::CALENDAR_TERMS,
442 SettingsSection::Calendar => &super::CALENDAR_VIEW_TERMS,
443 SettingsSection::CalendarAccounts => &super::CALENDAR_ACCOUNTS_TERMS,
428 444 _ => &[],
429 445 }
430 446 }
@@ -433,6 +449,11 @@ mod tests {
433 449 fn every_search_term_names_a_setting_on_its_page() {
434 450 let _guard = crate::i18n::locale_test_lock();
435 451 apply_locale("en");
452 let calendar_accounts_source = concat!(
453 include_str!("calendar.rs"),
454 "\n",
455 include_str!("caldav_form.rs"),
456 );
436 457 let pages = [
437 458 (SettingsSection::General, include_str!("general.rs")),
438 459 (
@@ -442,6 +463,7 @@ mod tests {
442 463 (SettingsSection::Appearance, include_str!("appearance.rs")),
443 464 (SettingsSection::Devices, include_str!("devices.rs")),
444 465 (SettingsSection::Calendar, include_str!("calendar.rs")),
466 (SettingsSection::CalendarAccounts, calendar_accounts_source),
445 467 ];
446 468 for (section, source) in pages {
447 469 for key in search_term_keys(section) {
@@ -9,13 +9,14 @@ use crate::settings_section::SettingsSection;
9use crate::theme;
9use crate::theme;
10use crate::views::widgets::icon;
10use crate::views::widgets::icon;
11
11
12pub const TEAMS_GROUP: [SettingsSection; 7] = [
12pub const TEAMS_GROUP: [SettingsSection; 8] = [
13 SettingsSection::General,
13 SettingsSection::General,
14 SettingsSection::Notifications,
14 SettingsSection::Notifications,
15 SettingsSection::Appearance,
15 SettingsSection::Appearance,
16 SettingsSection::Chats,
16 SettingsSection::Chats,
17 SettingsSection::Calls,
17 SettingsSection::Calls,
18 SettingsSection::Calendar,
18 SettingsSection::Calendar,
19 SettingsSection::CalendarAccounts,
19 SettingsSection::Devices,
20 SettingsSection::Devices,
20];
21];
21pub const RUSTY_GROUP: [SettingsSection; 2] = [SettingsSection::Agents, SettingsSection::Mcp];
22pub const RUSTY_GROUP: [SettingsSection; 2] = [SettingsSection::Agents, SettingsSection::Mcp];
@@ -27,14 +28,21 @@ const ITEM_RADIUS: f32 = 6.;
27const ITEM_ICON: f32 = 16.;
28const ITEM_ICON: f32 = 16.;
28const NAV_PADDING_X: f32 = 12.;
29const NAV_PADDING_X: f32 = 12.;
29
30
30const CALENDAR_TERMS: [&str; 10] = [
31const CALENDAR_VIEW_TERMS: [&str; 5] = [
31 "settings.calendar.default_view",
32 "settings.calendar.default_view",
32 "settings.calendar.work_days",
33 "settings.calendar.work_days",
33 "settings.calendar.work_hours",
34 "settings.calendar.work_hours",
34 "settings.calendar.time_scale",
35 "settings.calendar.time_scale",
35 "settings.calendar.weekend",
36 "settings.calendar.weekend",
37];
38
39const CALENDAR_ACCOUNTS_TERMS: [&str; 9] = [
36 "settings.calendar.google_title",
40 "settings.calendar.google_title",
37 "settings.calendar.connect_button",
41 "settings.calendar.connect_button",
42 "settings.calendar.caldav_title",
43 "settings.calendar.caldav_connect",
44 "settings.calendar.ics_title",
45 "settings.calendar.ics_connect",
38 "settings.calendar.section_home",
46 "settings.calendar.section_home",
39 "settings.calendar.section_write",
47 "settings.calendar.section_write",
40 "settings.calendar.outlook_mailbox",
48 "settings.calendar.outlook_mailbox",
@@ -82,7 +90,11 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
82 tr("settings.chats.markdown"),
90 tr("settings.chats.markdown"),
83 ],
91 ],
84 SettingsSection::Calls => vec![tr("settings.calls.ringtones")],
92 SettingsSection::Calls => vec![tr("settings.calls.ringtones")],
85 SettingsSection::Calendar => CALENDAR_TERMS.iter().map(|key| tr(key)).collect(),
93 SettingsSection::Calendar => CALENDAR_VIEW_TERMS.iter().map(|key| tr(key)).collect(),
94 SettingsSection::CalendarAccounts => CALENDAR_ACCOUNTS_TERMS
95 .iter()
96 .map(|key| tr(key))
97 .collect(),
86 SettingsSection::Devices => vec![
98 SettingsSection::Devices => vec![
87 "Speaker".to_owned(),
99 "Speaker".to_owned(),
88 "Microphone".to_owned(),
100 "Microphone".to_owned(),
@@ -137,6 +149,7 @@ pub fn label(section: SettingsSection) -> String {
137 SettingsSection::Chats => tr("settings.nav.chats"),
149 SettingsSection::Chats => tr("settings.nav.chats"),
138 SettingsSection::Calls => tr("settings.nav.calls"),
150 SettingsSection::Calls => tr("settings.nav.calls"),
139 SettingsSection::Calendar => tr("settings.nav.calendar"),
151 SettingsSection::Calendar => tr("settings.nav.calendar"),
152 SettingsSection::CalendarAccounts => tr("settings.nav.calendar_accounts"),
140 SettingsSection::Devices => tr("settings.nav.devices"),
153 SettingsSection::Devices => tr("settings.nav.devices"),
141 SettingsSection::Agents => tr("settings.nav.agents"),
154 SettingsSection::Agents => tr("settings.nav.agents"),
142 SettingsSection::Mcp => tr("settings.nav.mcp"),
155 SettingsSection::Mcp => tr("settings.nav.mcp"),
@@ -153,6 +166,7 @@ fn icon_name(section: SettingsSection) -> IconName {
153 SettingsSection::Chats => IconName::MessageSquare,
166 SettingsSection::Chats => IconName::MessageSquare,
154 SettingsSection::Calls => IconName::Phone,
167 SettingsSection::Calls => IconName::Phone,
155 SettingsSection::Calendar => IconName::Calendar,
168 SettingsSection::Calendar => IconName::Calendar,
169 SettingsSection::CalendarAccounts => IconName::Calendar,
156 SettingsSection::Devices => IconName::Headphones,
170 SettingsSection::Devices => IconName::Headphones,
157 SettingsSection::Agents => IconName::Bot,
171 SettingsSection::Agents => IconName::Bot,
158 SettingsSection::Mcp => IconName::Plug,
172 SettingsSection::Mcp => IconName::Plug,
@@ -177,6 +191,7 @@ fn element_id(section: SettingsSection) -> &'static str {
177 SettingsSection::Chats => "settings-nav-chats",
191 SettingsSection::Chats => "settings-nav-chats",
178 SettingsSection::Calls => "settings-nav-calls",
192 SettingsSection::Calls => "settings-nav-calls",
179 SettingsSection::Calendar => "settings-nav-calendar",
193 SettingsSection::Calendar => "settings-nav-calendar",
194 SettingsSection::CalendarAccounts => "settings-nav-calendar-accounts",
180 SettingsSection::Devices => "settings-nav-devices",
195 SettingsSection::Devices => "settings-nav-devices",
181 SettingsSection::Agents => "settings-nav-agents",
196 SettingsSection::Agents => "settings-nav-agents",
182 SettingsSection::Mcp => "settings-nav-mcp",
197 SettingsSection::Mcp => "settings-nav-mcp",
@@ -424,7 +439,8 @@ mod tests {
424 "settings.chats.enter_to",
439 "settings.chats.enter_to",
425 "settings.chats.markdown",
440 "settings.chats.markdown",
426 ],
441 ],
427 SettingsSection::Calendar => &super::CALENDAR_TERMS,
442 SettingsSection::Calendar => &super::CALENDAR_VIEW_TERMS,
443 SettingsSection::CalendarAccounts => &super::CALENDAR_ACCOUNTS_TERMS,
428 _ => &[],
444 _ => &[],
429 }
445 }
430 }
446 }
@@ -433,6 +449,11 @@ mod tests {
433 fn every_search_term_names_a_setting_on_its_page() {
449 fn every_search_term_names_a_setting_on_its_page() {
434 let _guard = crate::i18n::locale_test_lock();
450 let _guard = crate::i18n::locale_test_lock();
435 apply_locale("en");
451 apply_locale("en");
452 let calendar_accounts_source = concat!(
453 include_str!("calendar.rs"),
454 "\n",
455 include_str!("caldav_form.rs"),
456 );
436 let pages = [
457 let pages = [
437 (SettingsSection::General, include_str!("general.rs")),
458 (SettingsSection::General, include_str!("general.rs")),
438 (
459 (
@@ -442,6 +463,7 @@ mod tests {
442 (SettingsSection::Appearance, include_str!("appearance.rs")),
463 (SettingsSection::Appearance, include_str!("appearance.rs")),
443 (SettingsSection::Devices, include_str!("devices.rs")),
464 (SettingsSection::Devices, include_str!("devices.rs")),
444 (SettingsSection::Calendar, include_str!("calendar.rs")),
465 (SettingsSection::Calendar, include_str!("calendar.rs")),
466 (SettingsSection::CalendarAccounts, calendar_accounts_source),
445 ];
467 ];
446 for (section, source) in pages {
468 for (section, source) in pages {
447 for key in search_term_keys(section) {
469 for key in search_term_keys(section) {
crates/app/src/settings/rows.rs +34 −0
@@ -116,6 +116,40 @@ pub fn control_row(
116 116 .child(control)
117 117 }
118 118
119 /// Label above a full-width control. Use for text inputs so `Input::size_full`
120 /// does not squeeze a horizontal title to zero width.
121 pub fn stacked_field(
122 title: impl Into<SharedString>,
123 detail: impl Into<SharedString>,
124 control: impl IntoElement,
125 ) -> Div {
126 let detail = detail.into();
127 v_flex()
128 .w_full()
129 .px(px(ROW_INSET))
130 .py(px(ROW_PADDING))
131 .gap(px(6.))
132 .rounded(px(ROW_RADIUS))
133 .child(
134 div()
135 .text_size(px(14.))
136 .line_height(px(20.))
137 .font_weight(FontWeight::SEMIBOLD)
138 .text_color(theme::text())
139 .child(title.into()),
140 )
141 .when(!detail.is_empty(), |column| {
142 column.child(
143 div()
144 .text_size(px(12.))
145 .line_height(px(16.))
146 .text_color(theme::text_muted())
147 .child(detail),
148 )
149 })
150 .child(div().w_full().child(control))
151 }
152
119 153 pub fn toggle_row(
120 154 id: impl Into<ElementId>,
121 155 title: impl Into<SharedString>,
@@ -116,6 +116,40 @@ pub fn control_row(
116 .child(control)
116 .child(control)
117}
117}
118
118
119/// Label above a full-width control. Use for text inputs so `Input::size_full`
120/// does not squeeze a horizontal title to zero width.
121pub fn stacked_field(
122 title: impl Into<SharedString>,
123 detail: impl Into<SharedString>,
124 control: impl IntoElement,
125) -> Div {
126 let detail = detail.into();
127 v_flex()
128 .w_full()
129 .px(px(ROW_INSET))
130 .py(px(ROW_PADDING))
131 .gap(px(6.))
132 .rounded(px(ROW_RADIUS))
133 .child(
134 div()
135 .text_size(px(14.))
136 .line_height(px(20.))
137 .font_weight(FontWeight::SEMIBOLD)
138 .text_color(theme::text())
139 .child(title.into()),
140 )
141 .when(!detail.is_empty(), |column| {
142 column.child(
143 div()
144 .text_size(px(12.))
145 .line_height(px(16.))
146 .text_color(theme::text_muted())
147 .child(detail),
148 )
149 })
150 .child(div().w_full().child(control))
151}
152
119pub fn toggle_row(
153pub fn toggle_row(
120 id: impl Into<ElementId>,
154 id: impl Into<ElementId>,
121 title: impl Into<SharedString>,
155 title: impl Into<SharedString>,
crates/app/src/views/calendar_picker.rs +87 −2
@@ -10,7 +10,7 @@ use gpui_kit::component::button::{Button, ButtonVariants as _};
10 10 use gpui_kit::component::{h_flex, v_flex};
11 11 use gpui_kit::prelude::FluentBuilder as _;
12 12 use gpui_kit::*;
13 use store::{CalendarAccounts, GoogleAccount};
13 use store::{CalDavAccount, CalendarAccounts, GoogleAccount, IcsSubscription};
14 14
15 15 use super::calendar_mini_month::mini_month_grid;
16 16 use crate::app_state::AppState;
@@ -68,6 +68,17 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
68 68 state.calendar_expanded_groups.contains(&account.id),
69 69 ));
70 70 }
71 for account in &accounts.caldav_accounts {
72 column = column.child(caldav_group(
73 app,
74 &accounts,
75 account,
76 prefs.group_collapsed(&account.id),
77 ));
78 }
79 for subscription in &accounts.ics_subscriptions {
80 column = column.child(ics_row(app, subscription));
81 }
71 82 column
72 83 }
73 84
@@ -151,7 +162,7 @@ fn add_calendar_row(app: &Entity<AppState>) -> Stateful<Div> {
151 162 .child(tr("calendar.view.add_calendar"))
152 163 .on_click(move |_, _, cx| {
153 164 app.update(cx, |state, cx| {
154 state.open_settings(SettingsSection::Calendar, cx)
165 state.open_settings(SettingsSection::CalendarAccounts, cx)
155 166 })
156 167 })
157 168 }
@@ -275,6 +286,80 @@ fn google_group(
275 286 body
276 287 }
277 288
289 fn caldav_group(
290 app: &Entity<AppState>,
291 accounts: &CalendarAccounts,
292 account: &CalDavAccount,
293 collapsed: bool,
294 ) -> Div {
295 let selected: Vec<bool> = account
296 .calendars
297 .iter()
298 .map(|calendar| calendar.selected)
299 .collect();
300 let check = group_check(&selected);
301 let (collapse, group_id) = (app.clone(), account.id.clone());
302 let mut body = group(
303 format!("calendar-group-caldav-{}", account.id),
304 format!("CalDAV · {}", account.display_name),
305 check,
306 collapsed,
307 |_| {},
308 move |cx| {
309 collapse.update(cx, |state, cx| {
310 state.update_calendar_prefs(|prefs| prefs.toggle_group(&group_id), cx)
311 })
312 },
313 );
314 if collapsed {
315 return body;
316 }
317 for calendar in &account.calendars {
318 let toggle = app.clone();
319 let (account_id, calendar_id) = (account.id.clone(), calendar.id.clone());
320 let color_index = accounts
321 .google_accounts
322 .iter()
323 .map(|account| account.calendars.len())
324 .sum::<usize>()
325 + 1
326 + accounts
327 .caldav_accounts
328 .iter()
329 .flat_map(|account| account.calendars.iter().map(|c| c.id.as_str()))
330 .position(|id| id == calendar.id)
331 .unwrap_or(0);
332 body = body.child(calendar_row(
333 format!("calendar-picker-caldav-{}", calendar.id),
334 calendar.summary.clone(),
335 calendar.selected,
336 theme::calendar_color(color_index),
337 move |cx| {
338 toggle.update(cx, |state, cx| {
339 state.toggle_caldav_calendar_selected(&account_id, &calendar_id, cx)
340 });
341 },
342 ));
343 }
344 body
345 }
346
347 fn ics_row(app: &Entity<AppState>, subscription: &IcsSubscription) -> Stateful<Div> {
348 let toggle = app.clone();
349 let id = subscription.id.clone();
350 calendar_row(
351 format!("calendar-picker-ics-{}", subscription.id),
352 subscription.summary.clone(),
353 subscription.selected,
354 theme::calendar_color(8),
355 move |cx| {
356 toggle.update(cx, |state, cx| {
357 state.toggle_ics_subscription_selected(&id, cx)
358 })
359 },
360 )
361 }
362
278 363 /// Group header: chevron to collapse, a check box for the whole group, the title.
279 364 fn group(
280 365 id: String,
@@ -10,7 +10,7 @@ use gpui_kit::component::button::{Button, ButtonVariants as _};
10use gpui_kit::component::{h_flex, v_flex};
10use gpui_kit::component::{h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
12use gpui_kit::*;
13use store::{CalendarAccounts, GoogleAccount};
13use store::{CalDavAccount, CalendarAccounts, GoogleAccount, IcsSubscription};
14
14
15use super::calendar_mini_month::mini_month_grid;
15use super::calendar_mini_month::mini_month_grid;
16use crate::app_state::AppState;
16use crate::app_state::AppState;
@@ -68,6 +68,17 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
68 state.calendar_expanded_groups.contains(&account.id),
68 state.calendar_expanded_groups.contains(&account.id),
69 ));
69 ));
70 }
70 }
71 for account in &accounts.caldav_accounts {
72 column = column.child(caldav_group(
73 app,
74 &accounts,
75 account,
76 prefs.group_collapsed(&account.id),
77 ));
78 }
79 for subscription in &accounts.ics_subscriptions {
80 column = column.child(ics_row(app, subscription));
81 }
71 column
82 column
72}
83}
73
84
@@ -151,7 +162,7 @@ fn add_calendar_row(app: &Entity<AppState>) -> Stateful<Div> {
151 .child(tr("calendar.view.add_calendar"))
162 .child(tr("calendar.view.add_calendar"))
152 .on_click(move |_, _, cx| {
163 .on_click(move |_, _, cx| {
153 app.update(cx, |state, cx| {
164 app.update(cx, |state, cx| {
154 state.open_settings(SettingsSection::Calendar, cx)
165 state.open_settings(SettingsSection::CalendarAccounts, cx)
155 })
166 })
156 })
167 })
157}
168}
@@ -275,6 +286,80 @@ fn google_group(
275 body
286 body
276}
287}
277
288
289fn caldav_group(
290 app: &Entity<AppState>,
291 accounts: &CalendarAccounts,
292 account: &CalDavAccount,
293 collapsed: bool,
294) -> Div {
295 let selected: Vec<bool> = account
296 .calendars
297 .iter()
298 .map(|calendar| calendar.selected)
299 .collect();
300 let check = group_check(&selected);
301 let (collapse, group_id) = (app.clone(), account.id.clone());
302 let mut body = group(
303 format!("calendar-group-caldav-{}", account.id),
304 format!("CalDAV · {}", account.display_name),
305 check,
306 collapsed,
307 |_| {},
308 move |cx| {
309 collapse.update(cx, |state, cx| {
310 state.update_calendar_prefs(|prefs| prefs.toggle_group(&group_id), cx)
311 })
312 },
313 );
314 if collapsed {
315 return body;
316 }
317 for calendar in &account.calendars {
318 let toggle = app.clone();
319 let (account_id, calendar_id) = (account.id.clone(), calendar.id.clone());
320 let color_index = accounts
321 .google_accounts
322 .iter()
323 .map(|account| account.calendars.len())
324 .sum::<usize>()
325 + 1
326 + accounts
327 .caldav_accounts
328 .iter()
329 .flat_map(|account| account.calendars.iter().map(|c| c.id.as_str()))
330 .position(|id| id == calendar.id)
331 .unwrap_or(0);
332 body = body.child(calendar_row(
333 format!("calendar-picker-caldav-{}", calendar.id),
334 calendar.summary.clone(),
335 calendar.selected,
336 theme::calendar_color(color_index),
337 move |cx| {
338 toggle.update(cx, |state, cx| {
339 state.toggle_caldav_calendar_selected(&account_id, &calendar_id, cx)
340 });
341 },
342 ));
343 }
344 body
345}
346
347fn ics_row(app: &Entity<AppState>, subscription: &IcsSubscription) -> Stateful<Div> {
348 let toggle = app.clone();
349 let id = subscription.id.clone();
350 calendar_row(
351 format!("calendar-picker-ics-{}", subscription.id),
352 subscription.summary.clone(),
353 subscription.selected,
354 theme::calendar_color(8),
355 move |cx| {
356 toggle.update(cx, |state, cx| {
357 state.toggle_ics_subscription_selected(&id, cx)
358 })
359 },
360 )
361}
362
278/// Group header: chevron to collapse, a check box for the whole group, the title.
363/// Group header: chevron to collapse, a check box for the whole group, the title.
279fn group(
364fn group(
280 id: String,
365 id: String,
crates/chatsvc/Cargo.toml +3 −0
@@ -8,11 +8,14 @@ publish.workspace = true
8 8 [dependencies]
9 9 base64.workspace = true
10 10 chrono.workspace = true
11 chrono-tz = "0.10"
11 12 iana-time-zone = "0.1"
12 13 futures-util.workspace = true
13 14 percent-encoding.workspace = true
15 quick-xml = "0.37"
14 16 rand = "0.9"
15 17 reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }
18 rrule = "0.14"
16 19 serde.workspace = true
17 20 serde_json.workspace = true
18 21 session.workspace = true
@@ -8,11 +8,14 @@ publish.workspace = true
8[dependencies]
8[dependencies]
9base64.workspace = true
9base64.workspace = true
10chrono.workspace = true
10chrono.workspace = true
11chrono-tz = "0.10"
11iana-time-zone = "0.1"
12iana-time-zone = "0.1"
12futures-util.workspace = true
13futures-util.workspace = true
13percent-encoding.workspace = true
14percent-encoding.workspace = true
15quick-xml = "0.37"
14rand = "0.9"
16rand = "0.9"
15reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }
17reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }
18rrule = "0.14"
16serde.workspace = true
19serde.workspace = true
17serde_json.workspace = true
20serde_json.workspace = true
18session.workspace = true
21session.workspace = true
crates/chatsvc/src/caldav/client.rs added +444 −0
@@ -0,0 +1,444 @@
1 use chrono::{DateTime, Utc};
2 use reqwest::{Client, Method, StatusCode, header};
3 use uuid::Uuid;
4
5 use crate::calendar::{
6 AttendeeResponseCounts, CalendarEvent, CalendarSource, EventAttendee, ResponseType, ShowAs,
7 };
8 use crate::error::{Error, Result};
9 use crate::ical::{CalDavEventDraft, expand_events, parse_calendar};
10
11 use super::discovery::{DiscoverResult, discover, reject_https_downgrade, resolve_url};
12 use super::xml::{
13 calendar_query_body, parse_calendar_query, parse_multistatus, propfind_body,
14 };
15
16 #[derive(Debug, Clone)]
17 pub struct ListedCalendar {
18 pub href: String,
19 pub summary: String,
20 pub color: Option<String>,
21 pub writable: bool,
22 }
23
24 #[derive(Debug, Clone)]
25 pub struct CalDavEvent {
26 pub event: CalendarEvent,
27 pub href: String,
28 pub etag: Option<String>,
29 }
30
31 pub struct CalDavClient {
32 http: Client,
33 username: String,
34 password: String,
35 }
36
37 impl CalDavClient {
38 pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
39 CalDavClient {
40 http: Client::builder()
41 .redirect(reqwest::redirect::Policy::custom(|attempt| {
42 let previous = attempt.previous().last().map(|u| u.as_str()).unwrap_or("");
43 let next = attempt.url().as_str();
44 if previous.starts_with("https://") && next.starts_with("http://") {
45 attempt.error(std::io::Error::other("https downgrade"))
46 } else if attempt.previous().len() > 10 {
47 attempt.stop()
48 } else {
49 attempt.follow()
50 }
51 }))
52 .build()
53 .unwrap_or_else(|_| Client::new()),
54 username: username.into(),
55 password: password.into(),
56 }
57 }
58
59 pub async fn discover(&self, url: &str) -> Result<DiscoverResult> {
60 discover(self, url).await
61 }
62
63 pub async fn list_calendars(&self, home_set: &str) -> Result<Vec<ListedCalendar>> {
64 let body = propfind_body(&[
65 "<d:displayname/>",
66 "<d:resourcetype/>",
67 "<d:current-user-privilege-set/>",
68 "<c:supported-calendar-component-set/>",
69 "<x:calendar-color/>",
70 ]);
71 let xml = self.propfind(home_set, "1", &body).await?;
72 let mut calendars = Vec::new();
73 for response in parse_multistatus(&xml) {
74 if !response.resource_type_calendar {
75 continue;
76 }
77 // Prefer VEVENT; if component set absent, still include calendar collections.
78 if !response.supports_vevent
79 && xml.contains("supported-calendar-component-set")
80 && response.href.contains("todo")
81 {
82 continue;
83 }
84 let href = resolve_url(home_set, &response.href)?;
85 calendars.push(ListedCalendar {
86 href,
87 summary: response
88 .displayname
89 .unwrap_or_else(|| "Calendar".to_owned()),
90 color: response.calendar_color,
91 writable: response.writable,
92 });
93 }
94 Ok(calendars)
95 }
96
97 pub async fn fetch_events(
98 &self,
99 calendar_href: &str,
100 account_id: &str,
101 calendar_name: Option<&str>,
102 from: DateTime<Utc>,
103 to: DateTime<Utc>,
104 ) -> Result<Vec<CalDavEvent>> {
105 let start = from.format("%Y%m%dT%H%M%SZ").to_string();
106 let end = to.format("%Y%m%dT%H%M%SZ").to_string();
107 let mut resources = self
108 .calendar_query(calendar_href, &start, &end, true)
109 .await;
110 if resources.is_err() {
111 resources = self.calendar_query(calendar_href, &start, &end, false).await;
112 }
113 let resources = resources?;
114 let mut out = Vec::new();
115 for (href, etag, data) in resources {
116 let absolute = resolve_url(calendar_href, &href).unwrap_or(href);
117 let parsed = parse_calendar(&data);
118 let expanded = expand_events(parsed, from, to);
119 for item in expanded {
120 let mut event = to_calendar_event(
121 &item,
122 account_id,
123 &absolute,
124 calendar_name,
125 );
126 out.push(CalDavEvent {
127 event: {
128 // Keep href in object_id for writes.
129 event.object_id = format!("{absolute}#{}", event.ical_uid.clone().unwrap_or_default());
130 event
131 },
132 href: absolute.clone(),
133 etag: etag.clone(),
134 });
135 }
136 }
137 Ok(out)
138 }
139
140 pub async fn put_event(
141 &self,
142 calendar_href: &str,
143 draft: &CalDavEventDraft,
144 stamp: DateTime<Utc>,
145 ) -> Result<String> {
146 let href = format!(
147 "{}{}.ics",
148 ensure_trailing_slash(calendar_href),
149 draft.uid
150 );
151 let body = crate::ical::build_vevent(draft, stamp);
152 let response = self
153 .http
154 .put(&href)
155 .basic_auth(&self.username, Some(&self.password))
156 .header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")
157 .header(header::IF_NONE_MATCH, "*")
158 .body(body)
159 .send()
160 .await
161 .map_err(map_reqwest)?;
162 ensure_auth(response.status())?;
163 if !response.status().is_success() {
164 return Err(Error::UnexpectedAnswer(format!(
165 "CalDAV PUT failed: {}",
166 response.status()
167 )));
168 }
169 Ok(href)
170 }
171
172 pub async fn delete(&self, href: &str, etag: Option<&str>) -> Result<()> {
173 let mut request = self
174 .http
175 .delete(href)
176 .basic_auth(&self.username, Some(&self.password));
177 if let Some(etag) = etag {
178 request = request.header(header::IF_MATCH, format!("\"{etag}\""));
179 }
180 let response = request.send().await.map_err(map_reqwest)?;
181 ensure_auth(response.status())?;
182 if response.status() == StatusCode::NOT_FOUND || response.status().is_success() {
183 return Ok(());
184 }
185 Err(Error::UnexpectedAnswer(format!(
186 "CalDAV DELETE failed: {}",
187 response.status()
188 )))
189 }
190
191 pub async fn update_partstat(
192 &self,
193 href: &str,
194 etag: Option<&str>,
195 mailto: &str,
196 partstat: &str,
197 ) -> Result<()> {
198 let response = self
199 .http
200 .get(href)
201 .basic_auth(&self.username, Some(&self.password))
202 .send()
203 .await
204 .map_err(map_reqwest)?;
205 ensure_auth(response.status())?;
206 let fresh_etag = response
207 .headers()
208 .get(header::ETAG)
209 .and_then(|v| v.to_str().ok())
210 .map(|v| v.trim_matches('"').to_owned());
211 let body = response.text().await.map_err(map_reqwest)?;
212 let updated = patch_partstat(&body, mailto, partstat);
213 let match_etag = etag.or(fresh_etag.as_deref());
214 let mut request = self
215 .http
216 .put(href)
217 .basic_auth(&self.username, Some(&self.password))
218 .header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")
219 .body(updated);
220 if let Some(etag) = match_etag {
221 request = request.header(header::IF_MATCH, format!("\"{etag}\""));
222 }
223 let response = request.send().await.map_err(map_reqwest)?;
224 if response.status() == StatusCode::PRECONDITION_FAILED {
225 return Err(Error::UnexpectedAnswer(
226 "CalDAV event changed on the server; reload and try again".into(),
227 ));
228 }
229 ensure_auth(response.status())?;
230 if !response.status().is_success() {
231 return Err(Error::UnexpectedAnswer(format!(
232 "CalDAV RSVP failed: {}",
233 response.status()
234 )));
235 }
236 Ok(())
237 }
238
239 pub async fn propfind(&self, url: &str, depth: &str, body: &str) -> Result<String> {
240 let method = Method::from_bytes(b"PROPFIND").unwrap();
241 let response = self
242 .http
243 .request(method, url)
244 .basic_auth(&self.username, Some(&self.password))
245 .header("Depth", depth)
246 .header(header::CONTENT_TYPE, "application/xml; charset=utf-8")
247 .body(body.to_owned())
248 .send()
249 .await
250 .map_err(map_reqwest)?;
251 reject_https_downgrade(url, response.url().as_str())?;
252 if response.status() == StatusCode::UNAUTHORIZED {
253 let www = response
254 .headers()
255 .get(header::WWW_AUTHENTICATE)
256 .and_then(|v| v.to_str().ok())
257 .unwrap_or("");
258 if www.to_ascii_lowercase().contains("digest") {
259 return Err(Error::UnexpectedAnswer(
260 "CalDAV Digest authentication is not supported; enable Basic auth or use an app password with Basic".into(),
261 ));
262 }
263 return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into()));
264 }
265 if !response.status().is_success() && response.status().as_u16() != 207 {
266 return Err(Error::UnexpectedAnswer(format!(
267 "CalDAV PROPFIND failed: {}",
268 response.status()
269 )));
270 }
271 response.text().await.map_err(map_reqwest)
272 }
273
274 async fn calendar_query(
275 &self,
276 url: &str,
277 start: &str,
278 end: &str,
279 expand: bool,
280 ) -> Result<Vec<(String, Option<String>, String)>> {
281 let method = Method::from_bytes(b"REPORT").unwrap();
282 let body = calendar_query_body(start, end, expand);
283 let response = self
284 .http
285 .request(method, url)
286 .basic_auth(&self.username, Some(&self.password))
287 .header("Depth", "1")
288 .header(header::CONTENT_TYPE, "application/xml; charset=utf-8")
289 .body(body)
290 .send()
291 .await
292 .map_err(map_reqwest)?;
293 ensure_auth(response.status())?;
294 if !response.status().is_success() && response.status().as_u16() != 207 {
295 return Err(Error::UnexpectedAnswer(format!(
296 "CalDAV REPORT failed: {}",
297 response.status()
298 )));
299 }
300 let text = response.text().await.map_err(map_reqwest)?;
301 Ok(parse_calendar_query(&text))
302 }
303 }
304
305 fn to_calendar_event(
306 parsed: &crate::ical::ParsedEvent,
307 account_id: &str,
308 calendar_id: &str,
309 calendar_name: Option<&str>,
310 ) -> CalendarEvent {
311 let response = own_response(parsed);
312 CalendarEvent {
313 object_id: parsed.uid.clone(),
314 subject: parsed.summary.clone(),
315 start: parsed.start,
316 end: parsed.end,
317 all_day: parsed.all_day,
318 cancelled: parsed.cancelled,
319 online: parsed.join_url.is_some(),
320 join_url: parsed.join_url.clone(),
321 thread_id: None,
322 organizer_name: parsed.organizer.as_ref().map(|(n, _)| n.clone()),
323 organizer_address: parsed
324 .organizer
325 .as_ref()
326 .and_then(|(_, a)| a.clone()),
327 ical_uid: Some(parsed.uid.clone()),
328 response,
329 show_as: if parsed.transparent {
330 ShowAs::Free
331 } else {
332 ShowAs::Busy
333 },
334 dial_in: None,
335 source: CalendarSource::CalDav,
336 account_id: Some(account_id.to_owned()),
337 calendar_id: Some(calendar_id.to_owned()),
338 sources: vec![CalendarSource::CalDav],
339 location: parsed.location.clone(),
340 body_preview: parsed.description.clone().map(|d| {
341 if d.chars().count() > 280 {
342 d.chars().take(280).collect()
343 } else {
344 d
345 }
346 }),
347 body_html: parsed.description.clone(),
348 series: parsed.rrule.is_some() || parsed.recurrence_id.is_some(),
349 series_master_id: None,
350 response_counts: None::<AttendeeResponseCounts>,
351 attendees: parsed
352 .attendees
353 .iter()
354 .map(|a| EventAttendee {
355 name: a.cn.clone().unwrap_or_else(|| a.mailto.clone()),
356 address: Some(a.mailto.clone()),
357 response: partstat_to_response(a.partstat.as_deref().unwrap_or("NEEDS-ACTION")),
358 required: a
359 .role
360 .as_deref()
361 .map(|r| !r.eq_ignore_ascii_case("OPT-PARTICIPANT"))
362 .unwrap_or(true),
363 })
364 .collect(),
365 reminders: parsed.reminders_minutes.clone(),
366 source_link: None,
367 web_link: None,
368 calendar_name: calendar_name.map(str::to_owned),
369 }
370 }
371
372 fn own_response(parsed: &crate::ical::ParsedEvent) -> ResponseType {
373 parsed
374 .attendees
375 .iter()
376 .find_map(|a| a.partstat.as_deref().map(partstat_to_response))
377 .unwrap_or(ResponseType::NotResponded)
378 }
379
380 fn partstat_to_response(partstat: &str) -> ResponseType {
381 match partstat.to_ascii_uppercase().as_str() {
382 "ACCEPTED" => ResponseType::Accepted,
383 "TENTATIVE" => ResponseType::Tentative,
384 "DECLINED" => ResponseType::Declined,
385 "DELEGATED" => ResponseType::NotResponded,
386 _ => ResponseType::NotResponded,
387 }
388 }
389
390 pub fn partstat_for_reply(reply: crate::calendar::Reply) -> &'static str {
391 match reply {
392 crate::calendar::Reply::Accept => "ACCEPTED",
393 crate::calendar::Reply::Tentative => "TENTATIVE",
394 crate::calendar::Reply::Decline => "DECLINED",
395 }
396 }
397
398 fn patch_partstat(ics: &str, mailto: &str, partstat: &str) -> String {
399 let target = mailto.trim_start_matches("mailto:").to_ascii_lowercase();
400 let mut out = String::with_capacity(ics.len() + 32);
401 for line in ics.lines() {
402 if line.to_ascii_uppercase().starts_with("ATTENDEE")
403 && line.to_ascii_lowercase().contains(&target)
404 {
405 let mut rewritten = line.to_owned();
406 if let Some(start) = rewritten.to_ascii_uppercase().find("PARTSTAT=") {
407 let rest = &rewritten[start + 9..];
408 let end = rest.find([';', ':']).unwrap_or(rest.len());
409 rewritten.replace_range(start + 9..start + 9 + end, partstat);
410 } else if let Some(idx) = rewritten.find(':') {
411 rewritten.insert_str(idx, &format!(";PARTSTAT={partstat}"));
412 }
413 out.push_str(&rewritten);
414 out.push_str("\r\n");
415 } else {
416 out.push_str(line);
417 out.push_str("\r\n");
418 }
419 }
420 out
421 }
422
423 fn ensure_trailing_slash(url: &str) -> String {
424 if url.ends_with('/') {
425 url.to_owned()
426 } else {
427 format!("{url}/")
428 }
429 }
430
431 fn ensure_auth(status: StatusCode) -> Result<()> {
432 if status == StatusCode::UNAUTHORIZED {
433 return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into()));
434 }
435 Ok(())
436 }
437
438 fn map_reqwest(error: reqwest::Error) -> Error {
439 Error::UnexpectedAnswer(error.to_string())
440 }
441
442 pub fn new_event_uid() -> String {
443 format!("{}@rusty-teams", Uuid::new_v4())
444 }
@@ -0,0 +1,444 @@
1use chrono::{DateTime, Utc};
2use reqwest::{Client, Method, StatusCode, header};
3use uuid::Uuid;
4
5use crate::calendar::{
6 AttendeeResponseCounts, CalendarEvent, CalendarSource, EventAttendee, ResponseType, ShowAs,
7};
8use crate::error::{Error, Result};
9use crate::ical::{CalDavEventDraft, expand_events, parse_calendar};
10
11use super::discovery::{DiscoverResult, discover, reject_https_downgrade, resolve_url};
12use super::xml::{
13 calendar_query_body, parse_calendar_query, parse_multistatus, propfind_body,
14};
15
16#[derive(Debug, Clone)]
17pub struct ListedCalendar {
18 pub href: String,
19 pub summary: String,
20 pub color: Option<String>,
21 pub writable: bool,
22}
23
24#[derive(Debug, Clone)]
25pub struct CalDavEvent {
26 pub event: CalendarEvent,
27 pub href: String,
28 pub etag: Option<String>,
29}
30
31pub struct CalDavClient {
32 http: Client,
33 username: String,
34 password: String,
35}
36
37impl CalDavClient {
38 pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
39 CalDavClient {
40 http: Client::builder()
41 .redirect(reqwest::redirect::Policy::custom(|attempt| {
42 let previous = attempt.previous().last().map(|u| u.as_str()).unwrap_or("");
43 let next = attempt.url().as_str();
44 if previous.starts_with("https://") && next.starts_with("http://") {
45 attempt.error(std::io::Error::other("https downgrade"))
46 } else if attempt.previous().len() > 10 {
47 attempt.stop()
48 } else {
49 attempt.follow()
50 }
51 }))
52 .build()
53 .unwrap_or_else(|_| Client::new()),
54 username: username.into(),
55 password: password.into(),
56 }
57 }
58
59 pub async fn discover(&self, url: &str) -> Result<DiscoverResult> {
60 discover(self, url).await
61 }
62
63 pub async fn list_calendars(&self, home_set: &str) -> Result<Vec<ListedCalendar>> {
64 let body = propfind_body(&[
65 "<d:displayname/>",
66 "<d:resourcetype/>",
67 "<d:current-user-privilege-set/>",
68 "<c:supported-calendar-component-set/>",
69 "<x:calendar-color/>",
70 ]);
71 let xml = self.propfind(home_set, "1", &body).await?;
72 let mut calendars = Vec::new();
73 for response in parse_multistatus(&xml) {
74 if !response.resource_type_calendar {
75 continue;
76 }
77 // Prefer VEVENT; if component set absent, still include calendar collections.
78 if !response.supports_vevent
79 && xml.contains("supported-calendar-component-set")
80 && response.href.contains("todo")
81 {
82 continue;
83 }
84 let href = resolve_url(home_set, &response.href)?;
85 calendars.push(ListedCalendar {
86 href,
87 summary: response
88 .displayname
89 .unwrap_or_else(|| "Calendar".to_owned()),
90 color: response.calendar_color,
91 writable: response.writable,
92 });
93 }
94 Ok(calendars)
95 }
96
97 pub async fn fetch_events(
98 &self,
99 calendar_href: &str,
100 account_id: &str,
101 calendar_name: Option<&str>,
102 from: DateTime<Utc>,
103 to: DateTime<Utc>,
104 ) -> Result<Vec<CalDavEvent>> {
105 let start = from.format("%Y%m%dT%H%M%SZ").to_string();
106 let end = to.format("%Y%m%dT%H%M%SZ").to_string();
107 let mut resources = self
108 .calendar_query(calendar_href, &start, &end, true)
109 .await;
110 if resources.is_err() {
111 resources = self.calendar_query(calendar_href, &start, &end, false).await;
112 }
113 let resources = resources?;
114 let mut out = Vec::new();
115 for (href, etag, data) in resources {
116 let absolute = resolve_url(calendar_href, &href).unwrap_or(href);
117 let parsed = parse_calendar(&data);
118 let expanded = expand_events(parsed, from, to);
119 for item in expanded {
120 let mut event = to_calendar_event(
121 &item,
122 account_id,
123 &absolute,
124 calendar_name,
125 );
126 out.push(CalDavEvent {
127 event: {
128 // Keep href in object_id for writes.
129 event.object_id = format!("{absolute}#{}", event.ical_uid.clone().unwrap_or_default());
130 event
131 },
132 href: absolute.clone(),
133 etag: etag.clone(),
134 });
135 }
136 }
137 Ok(out)
138 }
139
140 pub async fn put_event(
141 &self,
142 calendar_href: &str,
143 draft: &CalDavEventDraft,
144 stamp: DateTime<Utc>,
145 ) -> Result<String> {
146 let href = format!(
147 "{}{}.ics",
148 ensure_trailing_slash(calendar_href),
149 draft.uid
150 );
151 let body = crate::ical::build_vevent(draft, stamp);
152 let response = self
153 .http
154 .put(&href)
155 .basic_auth(&self.username, Some(&self.password))
156 .header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")
157 .header(header::IF_NONE_MATCH, "*")
158 .body(body)
159 .send()
160 .await
161 .map_err(map_reqwest)?;
162 ensure_auth(response.status())?;
163 if !response.status().is_success() {
164 return Err(Error::UnexpectedAnswer(format!(
165 "CalDAV PUT failed: {}",
166 response.status()
167 )));
168 }
169 Ok(href)
170 }
171
172 pub async fn delete(&self, href: &str, etag: Option<&str>) -> Result<()> {
173 let mut request = self
174 .http
175 .delete(href)
176 .basic_auth(&self.username, Some(&self.password));
177 if let Some(etag) = etag {
178 request = request.header(header::IF_MATCH, format!("\"{etag}\""));
179 }
180 let response = request.send().await.map_err(map_reqwest)?;
181 ensure_auth(response.status())?;
182 if response.status() == StatusCode::NOT_FOUND || response.status().is_success() {
183 return Ok(());
184 }
185 Err(Error::UnexpectedAnswer(format!(
186 "CalDAV DELETE failed: {}",
187 response.status()
188 )))
189 }
190
191 pub async fn update_partstat(
192 &self,
193 href: &str,
194 etag: Option<&str>,
195 mailto: &str,
196 partstat: &str,
197 ) -> Result<()> {
198 let response = self
199 .http
200 .get(href)
201 .basic_auth(&self.username, Some(&self.password))
202 .send()
203 .await
204 .map_err(map_reqwest)?;
205 ensure_auth(response.status())?;
206 let fresh_etag = response
207 .headers()
208 .get(header::ETAG)
209 .and_then(|v| v.to_str().ok())
210 .map(|v| v.trim_matches('"').to_owned());
211 let body = response.text().await.map_err(map_reqwest)?;
212 let updated = patch_partstat(&body, mailto, partstat);
213 let match_etag = etag.or(fresh_etag.as_deref());
214 let mut request = self
215 .http
216 .put(href)
217 .basic_auth(&self.username, Some(&self.password))
218 .header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")
219 .body(updated);
220 if let Some(etag) = match_etag {
221 request = request.header(header::IF_MATCH, format!("\"{etag}\""));
222 }
223 let response = request.send().await.map_err(map_reqwest)?;
224 if response.status() == StatusCode::PRECONDITION_FAILED {
225 return Err(Error::UnexpectedAnswer(
226 "CalDAV event changed on the server; reload and try again".into(),
227 ));
228 }
229 ensure_auth(response.status())?;
230 if !response.status().is_success() {
231 return Err(Error::UnexpectedAnswer(format!(
232 "CalDAV RSVP failed: {}",
233 response.status()
234 )));
235 }
236 Ok(())
237 }
238
239 pub async fn propfind(&self, url: &str, depth: &str, body: &str) -> Result<String> {
240 let method = Method::from_bytes(b"PROPFIND").unwrap();
241 let response = self
242 .http
243 .request(method, url)
244 .basic_auth(&self.username, Some(&self.password))
245 .header("Depth", depth)
246 .header(header::CONTENT_TYPE, "application/xml; charset=utf-8")
247 .body(body.to_owned())
248 .send()
249 .await
250 .map_err(map_reqwest)?;
251 reject_https_downgrade(url, response.url().as_str())?;
252 if response.status() == StatusCode::UNAUTHORIZED {
253 let www = response
254 .headers()
255 .get(header::WWW_AUTHENTICATE)
256 .and_then(|v| v.to_str().ok())
257 .unwrap_or("");
258 if www.to_ascii_lowercase().contains("digest") {
259 return Err(Error::UnexpectedAnswer(
260 "CalDAV Digest authentication is not supported; enable Basic auth or use an app password with Basic".into(),
261 ));
262 }
263 return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into()));
264 }
265 if !response.status().is_success() && response.status().as_u16() != 207 {
266 return Err(Error::UnexpectedAnswer(format!(
267 "CalDAV PROPFIND failed: {}",
268 response.status()
269 )));
270 }
271 response.text().await.map_err(map_reqwest)
272 }
273
274 async fn calendar_query(
275 &self,
276 url: &str,
277 start: &str,
278 end: &str,
279 expand: bool,
280 ) -> Result<Vec<(String, Option<String>, String)>> {
281 let method = Method::from_bytes(b"REPORT").unwrap();
282 let body = calendar_query_body(start, end, expand);
283 let response = self
284 .http
285 .request(method, url)
286 .basic_auth(&self.username, Some(&self.password))
287 .header("Depth", "1")
288 .header(header::CONTENT_TYPE, "application/xml; charset=utf-8")
289 .body(body)
290 .send()
291 .await
292 .map_err(map_reqwest)?;
293 ensure_auth(response.status())?;
294 if !response.status().is_success() && response.status().as_u16() != 207 {
295 return Err(Error::UnexpectedAnswer(format!(
296 "CalDAV REPORT failed: {}",
297 response.status()
298 )));
299 }
300 let text = response.text().await.map_err(map_reqwest)?;
301 Ok(parse_calendar_query(&text))
302 }
303}
304
305fn to_calendar_event(
306 parsed: &crate::ical::ParsedEvent,
307 account_id: &str,
308 calendar_id: &str,
309 calendar_name: Option<&str>,
310) -> CalendarEvent {
311 let response = own_response(parsed);
312 CalendarEvent {
313 object_id: parsed.uid.clone(),
314 subject: parsed.summary.clone(),
315 start: parsed.start,
316 end: parsed.end,
317 all_day: parsed.all_day,
318 cancelled: parsed.cancelled,
319 online: parsed.join_url.is_some(),
320 join_url: parsed.join_url.clone(),
321 thread_id: None,
322 organizer_name: parsed.organizer.as_ref().map(|(n, _)| n.clone()),
323 organizer_address: parsed
324 .organizer
325 .as_ref()
326 .and_then(|(_, a)| a.clone()),
327 ical_uid: Some(parsed.uid.clone()),
328 response,
329 show_as: if parsed.transparent {
330 ShowAs::Free
331 } else {
332 ShowAs::Busy
333 },
334 dial_in: None,
335 source: CalendarSource::CalDav,
336 account_id: Some(account_id.to_owned()),
337 calendar_id: Some(calendar_id.to_owned()),
338 sources: vec![CalendarSource::CalDav],
339 location: parsed.location.clone(),
340 body_preview: parsed.description.clone().map(|d| {
341 if d.chars().count() > 280 {
342 d.chars().take(280).collect()
343 } else {
344 d
345 }
346 }),
347 body_html: parsed.description.clone(),
348 series: parsed.rrule.is_some() || parsed.recurrence_id.is_some(),
349 series_master_id: None,
350 response_counts: None::<AttendeeResponseCounts>,
351 attendees: parsed
352 .attendees
353 .iter()
354 .map(|a| EventAttendee {
355 name: a.cn.clone().unwrap_or_else(|| a.mailto.clone()),
356 address: Some(a.mailto.clone()),
357 response: partstat_to_response(a.partstat.as_deref().unwrap_or("NEEDS-ACTION")),
358 required: a
359 .role
360 .as_deref()
361 .map(|r| !r.eq_ignore_ascii_case("OPT-PARTICIPANT"))
362 .unwrap_or(true),
363 })
364 .collect(),
365 reminders: parsed.reminders_minutes.clone(),
366 source_link: None,
367 web_link: None,
368 calendar_name: calendar_name.map(str::to_owned),
369 }
370}
371
372fn own_response(parsed: &crate::ical::ParsedEvent) -> ResponseType {
373 parsed
374 .attendees
375 .iter()
376 .find_map(|a| a.partstat.as_deref().map(partstat_to_response))
377 .unwrap_or(ResponseType::NotResponded)
378}
379
380fn partstat_to_response(partstat: &str) -> ResponseType {
381 match partstat.to_ascii_uppercase().as_str() {
382 "ACCEPTED" => ResponseType::Accepted,
383 "TENTATIVE" => ResponseType::Tentative,
384 "DECLINED" => ResponseType::Declined,
385 "DELEGATED" => ResponseType::NotResponded,
386 _ => ResponseType::NotResponded,
387 }
388}
389
390pub fn partstat_for_reply(reply: crate::calendar::Reply) -> &'static str {
391 match reply {
392 crate::calendar::Reply::Accept => "ACCEPTED",
393 crate::calendar::Reply::Tentative => "TENTATIVE",
394 crate::calendar::Reply::Decline => "DECLINED",
395 }
396}
397
398fn patch_partstat(ics: &str, mailto: &str, partstat: &str) -> String {
399 let target = mailto.trim_start_matches("mailto:").to_ascii_lowercase();
400 let mut out = String::with_capacity(ics.len() + 32);
401 for line in ics.lines() {
402 if line.to_ascii_uppercase().starts_with("ATTENDEE")
403 && line.to_ascii_lowercase().contains(&target)
404 {
405 let mut rewritten = line.to_owned();
406 if let Some(start) = rewritten.to_ascii_uppercase().find("PARTSTAT=") {
407 let rest = &rewritten[start + 9..];
408 let end = rest.find([';', ':']).unwrap_or(rest.len());
409 rewritten.replace_range(start + 9..start + 9 + end, partstat);
410 } else if let Some(idx) = rewritten.find(':') {
411 rewritten.insert_str(idx, &format!(";PARTSTAT={partstat}"));
412 }
413 out.push_str(&rewritten);
414 out.push_str("\r\n");
415 } else {
416 out.push_str(line);
417 out.push_str("\r\n");
418 }
419 }
420 out
421}
422
423fn ensure_trailing_slash(url: &str) -> String {
424 if url.ends_with('/') {
425 url.to_owned()
426 } else {
427 format!("{url}/")
428 }
429}
430
431fn ensure_auth(status: StatusCode) -> Result<()> {
432 if status == StatusCode::UNAUTHORIZED {
433 return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into()));
434 }
435 Ok(())
436}
437
438fn map_reqwest(error: reqwest::Error) -> Error {
439 Error::UnexpectedAnswer(error.to_string())
440}
441
442pub fn new_event_uid() -> String {
443 format!("{}@rusty-teams", Uuid::new_v4())
444}
crates/chatsvc/src/caldav/discovery.rs added +99 −0
@@ -0,0 +1,99 @@
1 use reqwest::Url;
2
3 use crate::error::{Error, Result};
4
5 use super::client::CalDavClient;
6 use super::xml::{parse_multistatus, propfind_body};
7
8 #[derive(Debug, Clone)]
9 pub struct DiscoverResult {
10 pub principal: String,
11 pub home_set: String,
12 pub user_addresses: Vec<String>,
13 pub schedule_outbox: Option<String>,
14 }
15
16 pub async fn discover(client: &CalDavClient, start_url: &str) -> Result<DiscoverResult> {
17 let well_known = join_well_known(start_url)?;
18 let principal_href = match current_user_principal(client, &well_known).await {
19 Ok(href) => href,
20 Err(_) => current_user_principal(client, start_url).await?,
21 };
22 let principal = resolve_url(start_url, &principal_href)?;
23 let home_href = calendar_home_set(client, &principal).await?;
24 let home_set = resolve_url(&principal, &home_href)?;
25 let (user_addresses, schedule_outbox) = user_scheduling(client, &principal).await?;
26 Ok(DiscoverResult {
27 principal,
28 home_set,
29 user_addresses,
30 schedule_outbox,
31 })
32 }
33
34 fn join_well_known(url: &str) -> Result<String> {
35 let parsed = Url::parse(url).map_err(|e| Error::UnexpectedAnswer(e.to_string()))?;
36 let mut base = parsed.clone();
37 base.set_path("/.well-known/caldav");
38 base.set_query(None);
39 base.set_fragment(None);
40 Ok(base.to_string())
41 }
42
43 async fn current_user_principal(client: &CalDavClient, url: &str) -> Result<String> {
44 let body = propfind_body(&["<d:current-user-principal/>"]);
45 let xml = client.propfind(url, "0", &body).await?;
46 parse_multistatus(&xml)
47 .into_iter()
48 .find_map(|r| r.current_user_principal)
49 .ok_or_else(|| Error::UnexpectedAnswer("CalDAV current-user-principal missing".into()))
50 }
51
52 async fn calendar_home_set(client: &CalDavClient, principal: &str) -> Result<String> {
53 let body = propfind_body(&["<c:calendar-home-set/>"]);
54 let xml = client.propfind(principal, "0", &body).await?;
55 parse_multistatus(&xml)
56 .into_iter()
57 .find_map(|r| r.calendar_home_set)
58 .ok_or_else(|| Error::UnexpectedAnswer("CalDAV calendar-home-set missing".into()))
59 }
60
61 async fn user_scheduling(
62 client: &CalDavClient,
63 principal: &str,
64 ) -> Result<(Vec<String>, Option<String>)> {
65 let body = propfind_body(&[
66 "<c:calendar-user-address-set/>",
67 "<c:schedule-outbox-URL/>",
68 ]);
69 let xml = client.propfind(principal, "0", &body).await?;
70 let mut addresses = Vec::new();
71 let mut outbox = None;
72 for response in parse_multistatus(&xml) {
73 addresses.extend(response.calendar_user_addresses);
74 if outbox.is_none() {
75 outbox = response.schedule_outbox;
76 }
77 }
78 Ok((addresses, outbox))
79 }
80
81 pub fn resolve_url(base: &str, href: &str) -> Result<String> {
82 if href.starts_with("http://") || href.starts_with("https://") {
83 return Ok(href.to_owned());
84 }
85 let base = Url::parse(base).map_err(|e| Error::UnexpectedAnswer(e.to_string()))?;
86 Ok(base
87 .join(href)
88 .map_err(|e| Error::UnexpectedAnswer(e.to_string()))?
89 .to_string())
90 }
91
92 pub fn reject_https_downgrade(from: &str, to: &str) -> Result<()> {
93 if from.starts_with("https://") && to.starts_with("http://") {
94 return Err(Error::UnexpectedAnswer(
95 "CalDAV refused HTTPS to HTTP redirect (credentials would be sent in cleartext)".into(),
96 ));
97 }
98 Ok(())
99 }
@@ -0,0 +1,99 @@
1use reqwest::Url;
2
3use crate::error::{Error, Result};
4
5use super::client::CalDavClient;
6use super::xml::{parse_multistatus, propfind_body};
7
8#[derive(Debug, Clone)]
9pub struct DiscoverResult {
10 pub principal: String,
11 pub home_set: String,
12 pub user_addresses: Vec<String>,
13 pub schedule_outbox: Option<String>,
14}
15
16pub async fn discover(client: &CalDavClient, start_url: &str) -> Result<DiscoverResult> {
17 let well_known = join_well_known(start_url)?;
18 let principal_href = match current_user_principal(client, &well_known).await {
19 Ok(href) => href,
20 Err(_) => current_user_principal(client, start_url).await?,
21 };
22 let principal = resolve_url(start_url, &principal_href)?;
23 let home_href = calendar_home_set(client, &principal).await?;
24 let home_set = resolve_url(&principal, &home_href)?;
25 let (user_addresses, schedule_outbox) = user_scheduling(client, &principal).await?;
26 Ok(DiscoverResult {
27 principal,
28 home_set,
29 user_addresses,
30 schedule_outbox,
31 })
32}
33
34fn join_well_known(url: &str) -> Result<String> {
35 let parsed = Url::parse(url).map_err(|e| Error::UnexpectedAnswer(e.to_string()))?;
36 let mut base = parsed.clone();
37 base.set_path("/.well-known/caldav");
38 base.set_query(None);
39 base.set_fragment(None);
40 Ok(base.to_string())
41}
42
43async fn current_user_principal(client: &CalDavClient, url: &str) -> Result<String> {
44 let body = propfind_body(&["<d:current-user-principal/>"]);
45 let xml = client.propfind(url, "0", &body).await?;
46 parse_multistatus(&xml)
47 .into_iter()
48 .find_map(|r| r.current_user_principal)
49 .ok_or_else(|| Error::UnexpectedAnswer("CalDAV current-user-principal missing".into()))
50}
51
52async fn calendar_home_set(client: &CalDavClient, principal: &str) -> Result<String> {
53 let body = propfind_body(&["<c:calendar-home-set/>"]);
54 let xml = client.propfind(principal, "0", &body).await?;
55 parse_multistatus(&xml)
56 .into_iter()
57 .find_map(|r| r.calendar_home_set)
58 .ok_or_else(|| Error::UnexpectedAnswer("CalDAV calendar-home-set missing".into()))
59}
60
61async fn user_scheduling(
62 client: &CalDavClient,
63 principal: &str,
64) -> Result<(Vec<String>, Option<String>)> {
65 let body = propfind_body(&[
66 "<c:calendar-user-address-set/>",
67 "<c:schedule-outbox-URL/>",
68 ]);
69 let xml = client.propfind(principal, "0", &body).await?;
70 let mut addresses = Vec::new();
71 let mut outbox = None;
72 for response in parse_multistatus(&xml) {
73 addresses.extend(response.calendar_user_addresses);
74 if outbox.is_none() {
75 outbox = response.schedule_outbox;
76 }
77 }
78 Ok((addresses, outbox))
79}
80
81pub fn resolve_url(base: &str, href: &str) -> Result<String> {
82 if href.starts_with("http://") || href.starts_with("https://") {
83 return Ok(href.to_owned());
84 }
85 let base = Url::parse(base).map_err(|e| Error::UnexpectedAnswer(e.to_string()))?;
86 Ok(base
87 .join(href)
88 .map_err(|e| Error::UnexpectedAnswer(e.to_string()))?
89 .to_string())
90}
91
92pub fn reject_https_downgrade(from: &str, to: &str) -> Result<()> {
93 if from.starts_with("https://") && to.starts_with("http://") {
94 return Err(Error::UnexpectedAnswer(
95 "CalDAV refused HTTPS to HTTP redirect (credentials would be sent in cleartext)".into(),
96 ));
97 }
98 Ok(())
99}
crates/chatsvc/src/caldav/mod.rs added +10 −0
@@ -0,0 +1,10 @@
1 //! CalDAV client: discovery, calendar-query, PUT/DELETE, RSVP.
2
3 mod client;
4 mod discovery;
5 mod xml;
6 #[cfg(test)]
7 mod xml_tests;
8
9 pub use client::{CalDavClient, CalDavEvent, ListedCalendar, new_event_uid, partstat_for_reply};
10 pub use discovery::{DiscoverResult, discover};
@@ -0,0 +1,10 @@
1//! CalDAV client: discovery, calendar-query, PUT/DELETE, RSVP.
2
3mod client;
4mod discovery;
5mod xml;
6#[cfg(test)]
7mod xml_tests;
8
9pub use client::{CalDavClient, CalDavEvent, ListedCalendar, new_event_uid, partstat_for_reply};
10pub use discovery::{DiscoverResult, discover};
crates/chatsvc/src/caldav/xml.rs added +227 −0
@@ -0,0 +1,227 @@
1 use quick_xml::Reader;
2 use quick_xml::events::Event;
3
4 #[derive(Debug, Clone, Default)]
5 pub struct PropfindResponse {
6 pub href: String,
7 pub displayname: Option<String>,
8 pub calendar_color: Option<String>,
9 pub resource_type_calendar: bool,
10 pub supports_vevent: bool,
11 pub writable: bool,
12 pub current_user_principal: Option<String>,
13 pub calendar_home_set: Option<String>,
14 pub calendar_user_addresses: Vec<String>,
15 pub schedule_outbox: Option<String>,
16 pub getctag: Option<String>,
17 }
18
19 pub fn parse_multistatus(xml: &str) -> Vec<PropfindResponse> {
20 let mut reader = Reader::from_str(xml);
21 reader.config_mut().trim_text(true);
22 let mut responses = Vec::new();
23 let mut current = PropfindResponse::default();
24 let mut in_response = false;
25 let mut buf = Vec::new();
26 let mut path: Vec<String> = Vec::new();
27 loop {
28 match reader.read_event_into(&mut buf) {
29 Ok(Event::Start(e)) => {
30 let local = local_name(&e.name().as_ref());
31 path.push(local.clone());
32 if local == "response" {
33 in_response = true;
34 current = PropfindResponse::default();
35 }
36 if local == "calendar" && path.iter().any(|p| p == "resourcetype") {
37 current.resource_type_calendar = true;
38 }
39 if local == "comp" {
40 for attr in e.attributes().flatten() {
41 if local_name(attr.key.as_ref()) == "name"
42 && attr.unescape_value().map(|v| v.eq_ignore_ascii_case("VEVENT")).unwrap_or(false)
43 {
44 current.supports_vevent = true;
45 }
46 }
47 }
48 }
49 Ok(Event::Empty(e)) => {
50 let local = local_name(&e.name().as_ref());
51 if local == "calendar" && path.iter().any(|p| p == "resourcetype") {
52 current.resource_type_calendar = true;
53 }
54 if local == "comp" {
55 for attr in e.attributes().flatten() {
56 if local_name(attr.key.as_ref()) == "name"
57 && attr
58 .unescape_value()
59 .map(|v| v.eq_ignore_ascii_case("VEVENT"))
60 .unwrap_or(false)
61 {
62 current.supports_vevent = true;
63 }
64 }
65 }
66 if local == "write" || local == "write-content" || local == "all" {
67 if path.iter().any(|p| p == "current-user-privilege-set") {
68 current.writable = true;
69 }
70 }
71 }
72 Ok(Event::Text(t)) => {
73 let text = t.unescape().unwrap_or_default().to_string();
74 let leaf = path.last().cloned().unwrap_or_default();
75 if !in_response {
76 continue;
77 }
78 match leaf.as_str() {
79 "href" => {
80 if path.iter().any(|p| p == "current-user-principal") {
81 current.current_user_principal = Some(text);
82 } else if path.iter().any(|p| p == "calendar-home-set") {
83 current.calendar_home_set = Some(text);
84 } else if path.iter().any(|p| p == "calendar-user-address-set") {
85 current.calendar_user_addresses.push(text);
86 } else if path.iter().any(|p| p == "schedule-outbox-URL") {
87 current.schedule_outbox = Some(text);
88 } else if current.href.is_empty() {
89 current.href = text;
90 }
91 }
92 "displayname" => current.displayname = Some(text),
93 "calendar-color" | "color" => current.calendar_color = Some(text),
94 "getctag" | "getetag" => current.getctag = Some(text.trim_matches('"').to_owned()),
95 _ => {}
96 }
97 }
98 Ok(Event::End(e)) => {
99 let local = local_name(&e.name().as_ref());
100 if local == "response" && in_response {
101 responses.push(std::mem::take(&mut current));
102 in_response = false;
103 }
104 path.pop();
105 }
106 Ok(Event::Eof) => break,
107 Err(_) => break,
108 _ => {}
109 }
110 buf.clear();
111 }
112 responses
113 }
114
115 pub fn parse_calendar_query(xml: &str) -> Vec<(String, Option<String>, String)> {
116 // href, etag, calendar-data
117 let mut reader = Reader::from_str(xml);
118 reader.config_mut().trim_text(true);
119 let mut out = Vec::new();
120 let mut href = String::new();
121 let mut etag = None;
122 let mut data = String::new();
123 let mut in_response = false;
124 let mut path: Vec<String> = Vec::new();
125 let mut buf = Vec::new();
126 loop {
127 match reader.read_event_into(&mut buf) {
128 Ok(Event::Start(e)) => {
129 let local = local_name(&e.name().as_ref());
130 path.push(local.clone());
131 if local == "response" {
132 in_response = true;
133 href.clear();
134 etag = None;
135 data.clear();
136 }
137 }
138 Ok(Event::Text(t)) => {
139 if !in_response {
140 continue;
141 }
142 let text = t.unescape().unwrap_or_default().to_string();
143 let leaf = path.last().cloned().unwrap_or_default();
144 match leaf.as_str() {
145 "href" if href.is_empty() => href = text,
146 "getetag" => etag = Some(text.trim_matches('"').to_owned()),
147 "calendar-data" => data.push_str(&text),
148 _ => {}
149 }
150 }
151 Ok(Event::CData(t)) => {
152 if path.last().map(|s| s.as_str()) == Some("calendar-data") {
153 data.push_str(&String::from_utf8_lossy(&t));
154 }
155 }
156 Ok(Event::End(e)) => {
157 let local = local_name(&e.name().as_ref());
158 if local == "response" && in_response {
159 if !data.is_empty() {
160 out.push((href.clone(), etag.clone(), data.clone()));
161 }
162 in_response = false;
163 }
164 path.pop();
165 }
166 Ok(Event::Eof) => break,
167 Err(_) => break,
168 _ => {}
169 }
170 buf.clear();
171 }
172 out
173 }
174
175 fn local_name(name: &[u8]) -> String {
176 let full = String::from_utf8_lossy(name);
177 let after_ns = full.rsplit('}').next().unwrap_or(&full);
178 after_ns
179 .rsplit(':')
180 .next()
181 .unwrap_or(after_ns)
182 .to_ascii_lowercase()
183 }
184
185 pub fn propfind_body(props: &[&str]) -> String {
186 let mut body = String::from(
187 r#"<?xml version="1.0" encoding="utf-8"?>
188 <d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:cs="http://calendarserver.org/ns/" xmlns:x="http://apple.com/ns/ical/">
189 <d:prop>
190 "#,
191 );
192 for prop in props {
193 body.push_str(" ");
194 body.push_str(prop);
195 body.push('\n');
196 }
197 body.push_str(" </d:prop>\n</d:propfind>");
198 body
199 }
200
201 pub fn calendar_query_body(start: &str, end: &str, expand: bool) -> String {
202 let expand_xml = if expand {
203 format!(
204 r#" <c:expand start="{start}" end="{end}"/>
205 "#
206 )
207 } else {
208 String::new()
209 };
210 format!(
211 r#"<?xml version="1.0" encoding="utf-8"?>
212 <c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
213 <d:prop>
214 <d:getetag/>
215 <c:calendar-data>
216 {expand_xml} </c:calendar-data>
217 </d:prop>
218 <c:filter>
219 <c:comp-filter name="VCALENDAR">
220 <c:comp-filter name="VEVENT">
221 <c:time-range start="{start}" end="{end}"/>
222 </c:comp-filter>
223 </c:comp-filter>
224 </c:filter>
225 </c:calendar-query>"#
226 )
227 }
@@ -0,0 +1,227 @@
1use quick_xml::Reader;
2use quick_xml::events::Event;
3
4#[derive(Debug, Clone, Default)]
5pub struct PropfindResponse {
6 pub href: String,
7 pub displayname: Option<String>,
8 pub calendar_color: Option<String>,
9 pub resource_type_calendar: bool,
10 pub supports_vevent: bool,
11 pub writable: bool,
12 pub current_user_principal: Option<String>,
13 pub calendar_home_set: Option<String>,
14 pub calendar_user_addresses: Vec<String>,
15 pub schedule_outbox: Option<String>,
16 pub getctag: Option<String>,
17}
18
19pub fn parse_multistatus(xml: &str) -> Vec<PropfindResponse> {
20 let mut reader = Reader::from_str(xml);
21 reader.config_mut().trim_text(true);
22 let mut responses = Vec::new();
23 let mut current = PropfindResponse::default();
24 let mut in_response = false;
25 let mut buf = Vec::new();
26 let mut path: Vec<String> = Vec::new();
27 loop {
28 match reader.read_event_into(&mut buf) {
29 Ok(Event::Start(e)) => {
30 let local = local_name(&e.name().as_ref());
31 path.push(local.clone());
32 if local == "response" {
33 in_response = true;
34 current = PropfindResponse::default();
35 }
36 if local == "calendar" && path.iter().any(|p| p == "resourcetype") {
37 current.resource_type_calendar = true;
38 }
39 if local == "comp" {
40 for attr in e.attributes().flatten() {
41 if local_name(attr.key.as_ref()) == "name"
42 && attr.unescape_value().map(|v| v.eq_ignore_ascii_case("VEVENT")).unwrap_or(false)
43 {
44 current.supports_vevent = true;
45 }
46 }
47 }
48 }
49 Ok(Event::Empty(e)) => {
50 let local = local_name(&e.name().as_ref());
51 if local == "calendar" && path.iter().any(|p| p == "resourcetype") {
52 current.resource_type_calendar = true;
53 }
54 if local == "comp" {
55 for attr in e.attributes().flatten() {
56 if local_name(attr.key.as_ref()) == "name"
57 && attr
58 .unescape_value()
59 .map(|v| v.eq_ignore_ascii_case("VEVENT"))
60 .unwrap_or(false)
61 {
62 current.supports_vevent = true;
63 }
64 }
65 }
66 if local == "write" || local == "write-content" || local == "all" {
67 if path.iter().any(|p| p == "current-user-privilege-set") {
68 current.writable = true;
69 }
70 }
71 }
72 Ok(Event::Text(t)) => {
73 let text = t.unescape().unwrap_or_default().to_string();
74 let leaf = path.last().cloned().unwrap_or_default();
75 if !in_response {
76 continue;
77 }
78 match leaf.as_str() {
79 "href" => {
80 if path.iter().any(|p| p == "current-user-principal") {
81 current.current_user_principal = Some(text);
82 } else if path.iter().any(|p| p == "calendar-home-set") {
83 current.calendar_home_set = Some(text);
84 } else if path.iter().any(|p| p == "calendar-user-address-set") {
85 current.calendar_user_addresses.push(text);
86 } else if path.iter().any(|p| p == "schedule-outbox-URL") {
87 current.schedule_outbox = Some(text);
88 } else if current.href.is_empty() {
89 current.href = text;
90 }
91 }
92 "displayname" => current.displayname = Some(text),
93 "calendar-color" | "color" => current.calendar_color = Some(text),
94 "getctag" | "getetag" => current.getctag = Some(text.trim_matches('"').to_owned()),
95 _ => {}
96 }
97 }
98 Ok(Event::End(e)) => {
99 let local = local_name(&e.name().as_ref());
100 if local == "response" && in_response {
101 responses.push(std::mem::take(&mut current));
102 in_response = false;
103 }
104 path.pop();
105 }
106 Ok(Event::Eof) => break,
107 Err(_) => break,
108 _ => {}
109 }
110 buf.clear();
111 }
112 responses
113}
114
115pub fn parse_calendar_query(xml: &str) -> Vec<(String, Option<String>, String)> {
116 // href, etag, calendar-data
117 let mut reader = Reader::from_str(xml);
118 reader.config_mut().trim_text(true);
119 let mut out = Vec::new();
120 let mut href = String::new();
121 let mut etag = None;
122 let mut data = String::new();
123 let mut in_response = false;
124 let mut path: Vec<String> = Vec::new();
125 let mut buf = Vec::new();
126 loop {
127 match reader.read_event_into(&mut buf) {
128 Ok(Event::Start(e)) => {
129 let local = local_name(&e.name().as_ref());
130 path.push(local.clone());
131 if local == "response" {
132 in_response = true;
133 href.clear();
134 etag = None;
135 data.clear();
136 }
137 }
138 Ok(Event::Text(t)) => {
139 if !in_response {
140 continue;
141 }
142 let text = t.unescape().unwrap_or_default().to_string();
143 let leaf = path.last().cloned().unwrap_or_default();
144 match leaf.as_str() {
145 "href" if href.is_empty() => href = text,
146 "getetag" => etag = Some(text.trim_matches('"').to_owned()),
147 "calendar-data" => data.push_str(&text),
148 _ => {}
149 }
150 }
151 Ok(Event::CData(t)) => {
152 if path.last().map(|s| s.as_str()) == Some("calendar-data") {
153 data.push_str(&String::from_utf8_lossy(&t));
154 }
155 }
156 Ok(Event::End(e)) => {
157 let local = local_name(&e.name().as_ref());
158 if local == "response" && in_response {
159 if !data.is_empty() {
160 out.push((href.clone(), etag.clone(), data.clone()));
161 }
162 in_response = false;
163 }
164 path.pop();
165 }
166 Ok(Event::Eof) => break,
167 Err(_) => break,
168 _ => {}
169 }
170 buf.clear();
171 }
172 out
173}
174
175fn local_name(name: &[u8]) -> String {
176 let full = String::from_utf8_lossy(name);
177 let after_ns = full.rsplit('}').next().unwrap_or(&full);
178 after_ns
179 .rsplit(':')
180 .next()
181 .unwrap_or(after_ns)
182 .to_ascii_lowercase()
183}
184
185pub fn propfind_body(props: &[&str]) -> String {
186 let mut body = String::from(
187 r#"<?xml version="1.0" encoding="utf-8"?>
188<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:cs="http://calendarserver.org/ns/" xmlns:x="http://apple.com/ns/ical/">
189 <d:prop>
190"#,
191 );
192 for prop in props {
193 body.push_str(" ");
194 body.push_str(prop);
195 body.push('\n');
196 }
197 body.push_str(" </d:prop>\n</d:propfind>");
198 body
199}
200
201pub fn calendar_query_body(start: &str, end: &str, expand: bool) -> String {
202 let expand_xml = if expand {
203 format!(
204 r#" <c:expand start="{start}" end="{end}"/>
205"#
206 )
207 } else {
208 String::new()
209 };
210 format!(
211 r#"<?xml version="1.0" encoding="utf-8"?>
212<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
213 <d:prop>
214 <d:getetag/>
215 <c:calendar-data>
216{expand_xml} </c:calendar-data>
217 </d:prop>
218 <c:filter>
219 <c:comp-filter name="VCALENDAR">
220 <c:comp-filter name="VEVENT">
221 <c:time-range start="{start}" end="{end}"/>
222 </c:comp-filter>
223 </c:comp-filter>
224 </c:filter>
225</c:calendar-query>"#
226 )
227}
crates/chatsvc/src/caldav/xml_tests.rs added +59 −0
@@ -0,0 +1,59 @@
1 #[cfg(test)]
2 mod tests {
3 use super::super::xml::{parse_calendar_query, parse_multistatus};
4
5 #[test]
6 fn parses_propfind_calendar_collection() {
7 let xml = r#"<?xml version="1.0"?>
8 <d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
9 <d:response>
10 <d:href>/calendars/joe/personal/</d:href>
11 <d:propstat>
12 <d:prop>
13 <d:displayname>Personal</d:displayname>
14 <d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
15 <c:supported-calendar-component-set>
16 <c:comp name="VEVENT"/>
17 </c:supported-calendar-component-set>
18 <d:current-user-privilege-set>
19 <d:privilege><d:write/></d:privilege>
20 </d:current-user-privilege-set>
21 </d:prop>
22 </d:propstat>
23 </d:response>
24 </d:multistatus>"#;
25 let responses = parse_multistatus(xml);
26 assert_eq!(responses.len(), 1);
27 assert!(responses[0].resource_type_calendar);
28 assert!(responses[0].supports_vevent);
29 assert!(responses[0].writable);
30 assert_eq!(responses[0].displayname.as_deref(), Some("Personal"));
31 }
32
33 #[test]
34 fn parses_calendar_query_data() {
35 let xml = r#"<?xml version="1.0"?>
36 <d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
37 <d:response>
38 <d:href>/calendars/joe/personal/abc.ics</d:href>
39 <d:propstat>
40 <d:prop>
41 <d:getetag>"etag1"</d:getetag>
42 <c:calendar-data>BEGIN:VCALENDAR
43 BEGIN:VEVENT
44 UID:1
45 SUMMARY:Hi
46 DTSTART:20260101T100000Z
47 DTEND:20260101T110000Z
48 END:VEVENT
49 END:VCALENDAR</c:calendar-data>
50 </d:prop>
51 </d:propstat>
52 </d:response>
53 </d:multistatus>"#;
54 let items = parse_calendar_query(xml);
55 assert_eq!(items.len(), 1);
56 assert!(items[0].2.contains("UID:1"));
57 assert_eq!(items[0].1.as_deref(), Some("etag1"));
58 }
59 }
@@ -0,0 +1,59 @@
1#[cfg(test)]
2mod tests {
3 use super::super::xml::{parse_calendar_query, parse_multistatus};
4
5 #[test]
6 fn parses_propfind_calendar_collection() {
7 let xml = r#"<?xml version="1.0"?>
8<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
9 <d:response>
10 <d:href>/calendars/joe/personal/</d:href>
11 <d:propstat>
12 <d:prop>
13 <d:displayname>Personal</d:displayname>
14 <d:resourcetype><d:collection/><c:calendar/></d:resourcetype>
15 <c:supported-calendar-component-set>
16 <c:comp name="VEVENT"/>
17 </c:supported-calendar-component-set>
18 <d:current-user-privilege-set>
19 <d:privilege><d:write/></d:privilege>
20 </d:current-user-privilege-set>
21 </d:prop>
22 </d:propstat>
23 </d:response>
24</d:multistatus>"#;
25 let responses = parse_multistatus(xml);
26 assert_eq!(responses.len(), 1);
27 assert!(responses[0].resource_type_calendar);
28 assert!(responses[0].supports_vevent);
29 assert!(responses[0].writable);
30 assert_eq!(responses[0].displayname.as_deref(), Some("Personal"));
31 }
32
33 #[test]
34 fn parses_calendar_query_data() {
35 let xml = r#"<?xml version="1.0"?>
36<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
37 <d:response>
38 <d:href>/calendars/joe/personal/abc.ics</d:href>
39 <d:propstat>
40 <d:prop>
41 <d:getetag>"etag1"</d:getetag>
42 <c:calendar-data>BEGIN:VCALENDAR
43BEGIN:VEVENT
44UID:1
45SUMMARY:Hi
46DTSTART:20260101T100000Z
47DTEND:20260101T110000Z
48END:VEVENT
49END:VCALENDAR</c:calendar-data>
50 </d:prop>
51 </d:propstat>
52 </d:response>
53</d:multistatus>"#;
54 let items = parse_calendar_query(xml);
55 assert_eq!(items.len(), 1);
56 assert!(items[0].2.contains("UID:1"));
57 assert_eq!(items[0].1.as_deref(), Some("etag1"));
58 }
59}
crates/chatsvc/src/calendar.rs +11 −1
@@ -6,11 +6,12 @@ use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, space
6 6 use crate::error::{Error, Result};
7 7
8 8 mod availability;
9 mod merge;
9 10 mod reminders;
10 11 mod schedule;
11 12
12 13 pub use availability::{BusyTime, PersonSchedule, parse_schedules};
13
14 pub use merge::{HomeCalendar, merge_calendar_events, normalize_join_url};
14 15 pub use reminders::{Reminder, parse_reminders};
15 16 pub use schedule::{
16 17 Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, new_event_body_with_join,
@@ -45,6 +46,9 @@ pub enum CalendarSource {
45 46 #[default]
46 47 Outlook,
47 48 Google,
49 CalDav,
50 /// Read-only ICS subscription (holidays, shared links).
51 Ics,
48 52 }
49 53
50 54 impl CalendarSource {
@@ -52,8 +56,14 @@ impl CalendarSource {
52 56 match self {
53 57 CalendarSource::Outlook => "Outlook",
54 58 CalendarSource::Google => "Google",
59 CalendarSource::CalDav => "CalDAV",
60 CalendarSource::Ics => "ICS",
55 61 }
56 62 }
63
64 pub fn is_outlook(self) -> bool {
65 matches!(self, CalendarSource::Outlook)
66 }
57 67 }
58 68
59 69 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -6,11 +6,12 @@ use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, space
6use crate::error::{Error, Result};
6use crate::error::{Error, Result};
7
7
8mod availability;
8mod availability;
9mod merge;
9mod reminders;
10mod reminders;
10mod schedule;
11mod schedule;
11
12
12pub use availability::{BusyTime, PersonSchedule, parse_schedules};
13pub use availability::{BusyTime, PersonSchedule, parse_schedules};
13
14pub use merge::{HomeCalendar, merge_calendar_events, normalize_join_url};
14pub use reminders::{Reminder, parse_reminders};
15pub use reminders::{Reminder, parse_reminders};
15pub use schedule::{
16pub use schedule::{
16 Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, new_event_body_with_join,
17 Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, new_event_body_with_join,
@@ -45,6 +46,9 @@ pub enum CalendarSource {
45 #[default]
46 #[default]
46 Outlook,
47 Outlook,
47 Google,
48 Google,
49 CalDav,
50 /// Read-only ICS subscription (holidays, shared links).
51 Ics,
48}
52}
49
53
50impl CalendarSource {
54impl CalendarSource {
@@ -52,8 +56,14 @@ impl CalendarSource {
52 match self {
56 match self {
53 CalendarSource::Outlook => "Outlook",
57 CalendarSource::Outlook => "Outlook",
54 CalendarSource::Google => "Google",
58 CalendarSource::Google => "Google",
59 CalendarSource::CalDav => "CalDAV",
60 CalendarSource::Ics => "ICS",
55 }
61 }
56 }
62 }
63
64 pub fn is_outlook(self) -> bool {
65 matches!(self, CalendarSource::Outlook)
66 }
57}
67}
58
68
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
crates/chatsvc/src/calendar/merge.rs added +264 −0
@@ -0,0 +1,264 @@
1 use crate::calendar::{CalendarEvent, CalendarSource};
2
3 /// Identity of the home calendar used when Outlook is not among merge contributors.
4 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5 pub struct HomeCalendar<'a> {
6 pub source: CalendarSource,
7 pub account_id: &'a str,
8 pub calendar_id: &'a str,
9 }
10
11 /// Collapse duplicate meetings that share an iCal UID or the same Teams join URL.
12 ///
13 /// Preference when both sides contribute: Outlook wins; else the home calendar's copy; else keep
14 /// the first.
15 pub fn merge_calendar_events(
16 events: Vec<CalendarEvent>,
17 home: Option<HomeCalendar<'_>>,
18 ) -> Vec<CalendarEvent> {
19 let mut merged: Vec<CalendarEvent> = Vec::new();
20 for event in events {
21 if let Some(existing) = merged
22 .iter_mut()
23 .find(|candidate| same_meeting(candidate, &event))
24 {
25 if !existing.sources.contains(&event.source) {
26 existing.sources.push(event.source);
27 }
28 if existing.join_url.is_none() {
29 existing.join_url = event.join_url.clone();
30 existing.online = existing.online || event.online;
31 }
32 if existing.thread_id.is_none() {
33 existing.thread_id = event.thread_id.clone();
34 }
35 if existing.location.is_none() {
36 existing.location = event.location.clone();
37 }
38 if existing.body_preview.is_none() {
39 existing.body_preview = event.body_preview.clone();
40 }
41 if existing.body_html.is_none() {
42 existing.body_html = event.body_html.clone();
43 }
44 if existing.response_counts.is_none() {
45 existing.response_counts = event.response_counts;
46 }
47 if existing.attendees.is_empty() {
48 existing.attendees = event.attendees.clone();
49 }
50 if existing.reminders.is_empty() {
51 existing.reminders = event.reminders.clone();
52 }
53 if existing.source_link.is_none() {
54 existing.source_link = event.source_link.clone();
55 }
56 if existing.web_link.is_none() {
57 existing.web_link = event.web_link.clone();
58 }
59 if existing.calendar_name.is_none() {
60 existing.calendar_name = event.calendar_name.clone();
61 }
62 if event.series {
63 existing.series = true;
64 }
65 if existing.series_master_id.is_none() {
66 existing.series_master_id = event.series_master_id.clone();
67 }
68 if prefers_incoming(existing, &event, home) {
69 take_identity(existing, &event);
70 }
71 continue;
72 }
73 merged.push(event);
74 }
75 merged.sort_by_key(|event| (event.start, event.end));
76 merged
77 }
78
79 fn prefers_incoming(
80 existing: &CalendarEvent,
81 incoming: &CalendarEvent,
82 home: Option<HomeCalendar<'_>>,
83 ) -> bool {
84 if incoming.source.is_outlook() && !existing.source.is_outlook() {
85 return true;
86 }
87 if existing.source.is_outlook() {
88 return false;
89 }
90 if let Some(home) = home {
91 let incoming_home = matches_home(incoming, home);
92 let existing_home = matches_home(existing, home);
93 if incoming_home && !existing_home {
94 return true;
95 }
96 }
97 false
98 }
99
100 fn matches_home(event: &CalendarEvent, home: HomeCalendar<'_>) -> bool {
101 if event.source != home.source {
102 return false;
103 }
104 if home.source.is_outlook() {
105 return true;
106 }
107 event.account_id.as_deref() == Some(home.account_id)
108 && event.calendar_id.as_deref() == Some(home.calendar_id)
109 }
110
111 fn take_identity(existing: &mut CalendarEvent, incoming: &CalendarEvent) {
112 existing.object_id = incoming.object_id.clone();
113 existing.source = incoming.source;
114 existing.account_id = incoming.account_id.clone();
115 existing.calendar_id = incoming.calendar_id.clone();
116 existing.response = incoming.response;
117 existing.show_as = incoming.show_as;
118 }
119
120 fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
121 let same_all_day = left.all_day
122 && right.all_day
123 && (left.start - right.start).abs() < chrono::Duration::days(1);
124 if left.start != right.start && !same_all_day {
125 return false;
126 }
127 if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
128 if !a.is_empty() && a == b {
129 return true;
130 }
131 }
132 match (
133 left.join_url.as_deref().map(normalize_join_url),
134 right.join_url.as_deref().map(normalize_join_url),
135 ) {
136 (Some(a), Some(b)) if !a.is_empty() && a == b => true,
137 _ => false,
138 }
139 }
140
141 pub fn normalize_join_url(url: &str) -> String {
142 let trimmed = url.trim().trim_end_matches('/');
143 let without_query = trimmed.split('?').next().unwrap_or(trimmed);
144 without_query.to_ascii_lowercase()
145 }
146
147 #[cfg(test)]
148 mod tests {
149 use chrono::TimeZone;
150
151 use super::*;
152
153 fn event(
154 id: &str,
155 source: CalendarSource,
156 ical: Option<&str>,
157 join: Option<&str>,
158 ) -> CalendarEvent {
159 CalendarEvent {
160 object_id: id.into(),
161 subject: "Sync".into(),
162 start: chrono::Utc
163 .with_ymd_and_hms(2026, 11, 11, 10, 0, 0)
164 .unwrap(),
165 end: chrono::Utc
166 .with_ymd_and_hms(2026, 11, 11, 10, 30, 0)
167 .unwrap(),
168 ical_uid: ical.map(str::to_owned),
169 join_url: join.map(str::to_owned),
170 online: join.is_some(),
171 source,
172 sources: vec![source],
173 account_id: match source {
174 CalendarSource::Google => Some("g1".into()),
175 CalendarSource::CalDav => Some("c1".into()),
176 _ => None,
177 },
178 calendar_id: match source {
179 CalendarSource::Google => Some("primary".into()),
180 CalendarSource::CalDav => Some("/cal/".into()),
181 _ => None,
182 },
183 ..Default::default()
184 }
185 }
186
187 #[test]
188 fn merges_on_ical_uid_and_prefers_outlook() {
189 let merged = merge_calendar_events(
190 vec![
191 event("o1", CalendarSource::Outlook, Some("uid"), None),
192 event(
193 "g1",
194 CalendarSource::Google,
195 Some("uid"),
196 Some("https://teams.microsoft.com/l/meetup-join/x"),
197 ),
198 ],
199 None,
200 );
201 assert_eq!(merged.len(), 1);
202 assert_eq!(merged[0].sources.len(), 2);
203 assert_eq!(merged[0].object_id, "o1");
204 assert!(merged[0].join_url.is_some());
205 }
206
207 #[test]
208 fn prefers_home_when_outlook_absent() {
209 let home = HomeCalendar {
210 source: CalendarSource::CalDav,
211 account_id: "c1",
212 calendar_id: "/cal/",
213 };
214 let google_first = event("g1", CalendarSource::Google, Some("uid"), None);
215 let caldav = event("c1", CalendarSource::CalDav, Some("uid"), None);
216 let merged = merge_calendar_events(vec![google_first, caldav], Some(home));
217 assert_eq!(merged.len(), 1);
218 assert_eq!(merged[0].source, CalendarSource::CalDav);
219 assert_eq!(merged[0].object_id, "c1");
220 }
221
222 #[test]
223 fn occurrences_of_one_series_stay_separate() {
224 let join = Some("https://teams.microsoft.com/l/meetup-join/x");
225 let mut next_day = event("o2", CalendarSource::Outlook, Some("uid"), join);
226 next_day.start += chrono::Duration::days(1);
227 next_day.end += chrono::Duration::days(1);
228 let merged = merge_calendar_events(
229 vec![event("o1", CalendarSource::Outlook, Some("uid"), join), next_day],
230 None,
231 );
232 assert_eq!(merged.len(), 2);
233 }
234
235 #[test]
236 fn merges_on_normalized_join_url() {
237 let merged = merge_calendar_events(
238 vec![
239 event(
240 "o1",
241 CalendarSource::Outlook,
242 None,
243 Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),
244 ),
245 event(
246 "g1",
247 CalendarSource::Google,
248 None,
249 Some("https://teams.microsoft.com/l/meetup-join/x/"),
250 ),
251 ],
252 None,
253 );
254 assert_eq!(merged.len(), 1);
255 }
256
257 #[test]
258 fn does_not_merge_on_title_and_time_alone() {
259 let a = event("a", CalendarSource::Outlook, Some("a"), None);
260 let mut b = event("b", CalendarSource::Google, Some("b"), None);
261 b.subject = a.subject.clone();
262 assert_eq!(merge_calendar_events(vec![a, b], None).len(), 2);
263 }
264 }
@@ -0,0 +1,264 @@
1use crate::calendar::{CalendarEvent, CalendarSource};
2
3/// Identity of the home calendar used when Outlook is not among merge contributors.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub struct HomeCalendar<'a> {
6 pub source: CalendarSource,
7 pub account_id: &'a str,
8 pub calendar_id: &'a str,
9}
10
11/// Collapse duplicate meetings that share an iCal UID or the same Teams join URL.
12///
13/// Preference when both sides contribute: Outlook wins; else the home calendar's copy; else keep
14/// the first.
15pub fn merge_calendar_events(
16 events: Vec<CalendarEvent>,
17 home: Option<HomeCalendar<'_>>,
18) -> Vec<CalendarEvent> {
19 let mut merged: Vec<CalendarEvent> = Vec::new();
20 for event in events {
21 if let Some(existing) = merged
22 .iter_mut()
23 .find(|candidate| same_meeting(candidate, &event))
24 {
25 if !existing.sources.contains(&event.source) {
26 existing.sources.push(event.source);
27 }
28 if existing.join_url.is_none() {
29 existing.join_url = event.join_url.clone();
30 existing.online = existing.online || event.online;
31 }
32 if existing.thread_id.is_none() {
33 existing.thread_id = event.thread_id.clone();
34 }
35 if existing.location.is_none() {
36 existing.location = event.location.clone();
37 }
38 if existing.body_preview.is_none() {
39 existing.body_preview = event.body_preview.clone();
40 }
41 if existing.body_html.is_none() {
42 existing.body_html = event.body_html.clone();
43 }
44 if existing.response_counts.is_none() {
45 existing.response_counts = event.response_counts;
46 }
47 if existing.attendees.is_empty() {
48 existing.attendees = event.attendees.clone();
49 }
50 if existing.reminders.is_empty() {
51 existing.reminders = event.reminders.clone();
52 }
53 if existing.source_link.is_none() {
54 existing.source_link = event.source_link.clone();
55 }
56 if existing.web_link.is_none() {
57 existing.web_link = event.web_link.clone();
58 }
59 if existing.calendar_name.is_none() {
60 existing.calendar_name = event.calendar_name.clone();
61 }
62 if event.series {
63 existing.series = true;
64 }
65 if existing.series_master_id.is_none() {
66 existing.series_master_id = event.series_master_id.clone();
67 }
68 if prefers_incoming(existing, &event, home) {
69 take_identity(existing, &event);
70 }
71 continue;
72 }
73 merged.push(event);
74 }
75 merged.sort_by_key(|event| (event.start, event.end));
76 merged
77}
78
79fn prefers_incoming(
80 existing: &CalendarEvent,
81 incoming: &CalendarEvent,
82 home: Option<HomeCalendar<'_>>,
83) -> bool {
84 if incoming.source.is_outlook() && !existing.source.is_outlook() {
85 return true;
86 }
87 if existing.source.is_outlook() {
88 return false;
89 }
90 if let Some(home) = home {
91 let incoming_home = matches_home(incoming, home);
92 let existing_home = matches_home(existing, home);
93 if incoming_home && !existing_home {
94 return true;
95 }
96 }
97 false
98}
99
100fn matches_home(event: &CalendarEvent, home: HomeCalendar<'_>) -> bool {
101 if event.source != home.source {
102 return false;
103 }
104 if home.source.is_outlook() {
105 return true;
106 }
107 event.account_id.as_deref() == Some(home.account_id)
108 && event.calendar_id.as_deref() == Some(home.calendar_id)
109}
110
111fn take_identity(existing: &mut CalendarEvent, incoming: &CalendarEvent) {
112 existing.object_id = incoming.object_id.clone();
113 existing.source = incoming.source;
114 existing.account_id = incoming.account_id.clone();
115 existing.calendar_id = incoming.calendar_id.clone();
116 existing.response = incoming.response;
117 existing.show_as = incoming.show_as;
118}
119
120fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
121 let same_all_day = left.all_day
122 && right.all_day
123 && (left.start - right.start).abs() < chrono::Duration::days(1);
124 if left.start != right.start && !same_all_day {
125 return false;
126 }
127 if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
128 if !a.is_empty() && a == b {
129 return true;
130 }
131 }
132 match (
133 left.join_url.as_deref().map(normalize_join_url),
134 right.join_url.as_deref().map(normalize_join_url),
135 ) {
136 (Some(a), Some(b)) if !a.is_empty() && a == b => true,
137 _ => false,
138 }
139}
140
141pub fn normalize_join_url(url: &str) -> String {
142 let trimmed = url.trim().trim_end_matches('/');
143 let without_query = trimmed.split('?').next().unwrap_or(trimmed);
144 without_query.to_ascii_lowercase()
145}
146
147#[cfg(test)]
148mod tests {
149 use chrono::TimeZone;
150
151 use super::*;
152
153 fn event(
154 id: &str,
155 source: CalendarSource,
156 ical: Option<&str>,
157 join: Option<&str>,
158 ) -> CalendarEvent {
159 CalendarEvent {
160 object_id: id.into(),
161 subject: "Sync".into(),
162 start: chrono::Utc
163 .with_ymd_and_hms(2026, 11, 11, 10, 0, 0)
164 .unwrap(),
165 end: chrono::Utc
166 .with_ymd_and_hms(2026, 11, 11, 10, 30, 0)
167 .unwrap(),
168 ical_uid: ical.map(str::to_owned),
169 join_url: join.map(str::to_owned),
170 online: join.is_some(),
171 source,
172 sources: vec![source],
173 account_id: match source {
174 CalendarSource::Google => Some("g1".into()),
175 CalendarSource::CalDav => Some("c1".into()),
176 _ => None,
177 },
178 calendar_id: match source {
179 CalendarSource::Google => Some("primary".into()),
180 CalendarSource::CalDav => Some("/cal/".into()),
181 _ => None,
182 },
183 ..Default::default()
184 }
185 }
186
187 #[test]
188 fn merges_on_ical_uid_and_prefers_outlook() {
189 let merged = merge_calendar_events(
190 vec![
191 event("o1", CalendarSource::Outlook, Some("uid"), None),
192 event(
193 "g1",
194 CalendarSource::Google,
195 Some("uid"),
196 Some("https://teams.microsoft.com/l/meetup-join/x"),
197 ),
198 ],
199 None,
200 );
201 assert_eq!(merged.len(), 1);
202 assert_eq!(merged[0].sources.len(), 2);
203 assert_eq!(merged[0].object_id, "o1");
204 assert!(merged[0].join_url.is_some());
205 }
206
207 #[test]
208 fn prefers_home_when_outlook_absent() {
209 let home = HomeCalendar {
210 source: CalendarSource::CalDav,
211 account_id: "c1",
212 calendar_id: "/cal/",
213 };
214 let google_first = event("g1", CalendarSource::Google, Some("uid"), None);
215 let caldav = event("c1", CalendarSource::CalDav, Some("uid"), None);
216 let merged = merge_calendar_events(vec![google_first, caldav], Some(home));
217 assert_eq!(merged.len(), 1);
218 assert_eq!(merged[0].source, CalendarSource::CalDav);
219 assert_eq!(merged[0].object_id, "c1");
220 }
221
222 #[test]
223 fn occurrences_of_one_series_stay_separate() {
224 let join = Some("https://teams.microsoft.com/l/meetup-join/x");
225 let mut next_day = event("o2", CalendarSource::Outlook, Some("uid"), join);
226 next_day.start += chrono::Duration::days(1);
227 next_day.end += chrono::Duration::days(1);
228 let merged = merge_calendar_events(
229 vec![event("o1", CalendarSource::Outlook, Some("uid"), join), next_day],
230 None,
231 );
232 assert_eq!(merged.len(), 2);
233 }
234
235 #[test]
236 fn merges_on_normalized_join_url() {
237 let merged = merge_calendar_events(
238 vec![
239 event(
240 "o1",
241 CalendarSource::Outlook,
242 None,
243 Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),
244 ),
245 event(
246 "g1",
247 CalendarSource::Google,
248 None,
249 Some("https://teams.microsoft.com/l/meetup-join/x/"),
250 ),
251 ],
252 None,
253 );
254 assert_eq!(merged.len(), 1);
255 }
256
257 #[test]
258 fn does_not_merge_on_title_and_time_alone() {
259 let a = event("a", CalendarSource::Outlook, Some("a"), None);
260 let mut b = event("b", CalendarSource::Google, Some("b"), None);
261 b.subject = a.subject.clone();
262 assert_eq!(merge_calendar_events(vec![a, b], None).len(), 2);
263 }
264}
crates/chatsvc/src/google_calendar/merge.rs +2 −184
@@ -1,185 +1,3 @@
1 use crate::calendar::{CalendarEvent, CalendarSource};
1 //! Re-exports calendar merge so existing `google_calendar::merge_*` paths keep compiling.
2 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 if existing.location.is_none() {
22 existing.location = event.location.clone();
23 }
24 if existing.body_preview.is_none() {
25 existing.body_preview = event.body_preview.clone();
26 }
27 if existing.body_html.is_none() {
28 existing.body_html = event.body_html.clone();
29 }
30 if existing.response_counts.is_none() {
31 existing.response_counts = event.response_counts;
32 }
33 if existing.attendees.is_empty() {
34 existing.attendees = event.attendees.clone();
35 }
36 if existing.reminders.is_empty() {
37 existing.reminders = event.reminders.clone();
38 }
39 if existing.source_link.is_none() {
40 existing.source_link = event.source_link.clone();
41 }
42 if existing.web_link.is_none() {
43 existing.web_link = event.web_link.clone();
44 }
45 if existing.calendar_name.is_none() {
46 existing.calendar_name = event.calendar_name.clone();
47 }
48 if event.series {
49 existing.series = true;
50 }
51 if existing.series_master_id.is_none() {
52 existing.series_master_id = event.series_master_id.clone();
53 }
54 // Prefer Outlook object id when both sides contribute.
55 if existing.source == CalendarSource::Google && event.source == CalendarSource::Outlook
56 {
57 existing.object_id = event.object_id.clone();
58 existing.source = CalendarSource::Outlook;
59 existing.account_id = event.account_id.clone();
60 existing.calendar_id = event.calendar_id.clone();
61 existing.response = event.response;
62 existing.show_as = event.show_as;
63 }
64 continue;
65 }
66 merged.push(event);
67 }
68 merged.sort_by_key(|event| (event.start, event.end));
69 merged
70 }
71
72 fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
73 let same_all_day = left.all_day
74 && right.all_day
75 && (left.start - right.start).abs() < chrono::Duration::days(1);
76 if left.start != right.start && !same_all_day {
77 return false;
78 }
79 if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
80 if !a.is_empty() && a == b {
81 return true;
82 }
83 }
84 match (
85 left.join_url.as_deref().map(normalize_join_url),
86 right.join_url.as_deref().map(normalize_join_url),
87 ) {
88 (Some(a), Some(b)) if !a.is_empty() && a == b => true,
89 _ => false,
90 }
91 }
92
93 pub fn normalize_join_url(url: &str) -> String {
94 let trimmed = url.trim().trim_end_matches('/');
95 let without_query = trimmed.split('?').next().unwrap_or(trimmed);
96 without_query.to_ascii_lowercase()
97 }
98
99 #[cfg(test)]
100 mod tests {
101 use chrono::TimeZone;
102
103 use super::*;
104
105 fn event(
106 id: &str,
107 source: CalendarSource,
108 ical: Option<&str>,
109 join: Option<&str>,
110 ) -> CalendarEvent {
111 CalendarEvent {
112 object_id: id.into(),
113 subject: "Sync".into(),
114 start: chrono::Utc
115 .with_ymd_and_hms(2026, 11, 11, 10, 0, 0)
116 .unwrap(),
117 end: chrono::Utc
118 .with_ymd_and_hms(2026, 11, 11, 10, 30, 0)
119 .unwrap(),
120 ical_uid: ical.map(str::to_owned),
121 join_url: join.map(str::to_owned),
122 online: join.is_some(),
123 source,
124 sources: vec![source],
125 ..Default::default()
126 }
127 }
128
129 #[test]
130 fn merges_on_ical_uid_and_keeps_both_sources() {
131 let merged = merge_calendar_events(vec![
132 event("o1", CalendarSource::Outlook, Some("uid"), None),
133 event(
134 "g1",
135 CalendarSource::Google,
136 Some("uid"),
137 Some("https://teams.microsoft.com/l/meetup-join/x"),
138 ),
139 ]);
140 assert_eq!(merged.len(), 1);
141 assert_eq!(merged[0].sources.len(), 2);
142 assert_eq!(merged[0].object_id, "o1");
143 assert!(merged[0].join_url.is_some());
144 }
145
146 #[test]
147 fn occurrences_of_one_series_stay_separate() {
148 let join = Some("https://teams.microsoft.com/l/meetup-join/x");
149 let mut next_day = event("o2", CalendarSource::Outlook, Some("uid"), join);
150 next_day.start += chrono::Duration::days(1);
151 next_day.end += chrono::Duration::days(1);
152 let merged = merge_calendar_events(vec![
153 event("o1", CalendarSource::Outlook, Some("uid"), join),
154 next_day,
155 ]);
156 assert_eq!(merged.len(), 2);
157 }
158
159 #[test]
160 fn merges_on_normalized_join_url() {
161 let merged = merge_calendar_events(vec![
162 event(
163 "o1",
164 CalendarSource::Outlook,
165 None,
166 Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),
167 ),
168 event(
169 "g1",
170 CalendarSource::Google,
171 None,
172 Some("https://teams.microsoft.com/l/meetup-join/x/"),
173 ),
174 ]);
175 assert_eq!(merged.len(), 1);
176 }
177
178 #[test]
179 fn does_not_merge_on_title_and_time_alone() {
180 let a = event("a", CalendarSource::Outlook, Some("a"), None);
181 let mut b = event("b", CalendarSource::Google, Some("b"), None);
182 b.subject = a.subject.clone();
183 assert_eq!(merge_calendar_events(vec![a, b]).len(), 2);
184 }
185 }
3 pub use crate::{merge_calendar_events, normalize_join_url};
@@ -1,185 +1,3 @@
1use crate::calendar::{CalendarEvent, CalendarSource};
1//! Re-exports calendar merge so existing `google_calendar::merge_*` paths keep compiling.
2
2
3/// Collapse duplicate meetings that share an iCal UID or the same Teams join URL.
3pub use crate::{merge_calendar_events, normalize_join_url};
4pub 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 if existing.location.is_none() {
22 existing.location = event.location.clone();
23 }
24 if existing.body_preview.is_none() {
25 existing.body_preview = event.body_preview.clone();
26 }
27 if existing.body_html.is_none() {
28 existing.body_html = event.body_html.clone();
29 }
30 if existing.response_counts.is_none() {
31 existing.response_counts = event.response_counts;
32 }
33 if existing.attendees.is_empty() {
34 existing.attendees = event.attendees.clone();
35 }
36 if existing.reminders.is_empty() {
37 existing.reminders = event.reminders.clone();
38 }
39 if existing.source_link.is_none() {
40 existing.source_link = event.source_link.clone();
41 }
42 if existing.web_link.is_none() {
43 existing.web_link = event.web_link.clone();
44 }
45 if existing.calendar_name.is_none() {
46 existing.calendar_name = event.calendar_name.clone();
47 }
48 if event.series {
49 existing.series = true;
50 }
51 if existing.series_master_id.is_none() {
52 existing.series_master_id = event.series_master_id.clone();
53 }
54 // Prefer Outlook object id when both sides contribute.
55 if existing.source == CalendarSource::Google && event.source == CalendarSource::Outlook
56 {
57 existing.object_id = event.object_id.clone();
58 existing.source = CalendarSource::Outlook;
59 existing.account_id = event.account_id.clone();
60 existing.calendar_id = event.calendar_id.clone();
61 existing.response = event.response;
62 existing.show_as = event.show_as;
63 }
64 continue;
65 }
66 merged.push(event);
67 }
68 merged.sort_by_key(|event| (event.start, event.end));
69 merged
70}
71
72fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
73 let same_all_day = left.all_day
74 && right.all_day
75 && (left.start - right.start).abs() < chrono::Duration::days(1);
76 if left.start != right.start && !same_all_day {
77 return false;
78 }
79 if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
80 if !a.is_empty() && a == b {
81 return true;
82 }
83 }
84 match (
85 left.join_url.as_deref().map(normalize_join_url),
86 right.join_url.as_deref().map(normalize_join_url),
87 ) {
88 (Some(a), Some(b)) if !a.is_empty() && a == b => true,
89 _ => false,
90 }
91}
92
93pub fn normalize_join_url(url: &str) -> String {
94 let trimmed = url.trim().trim_end_matches('/');
95 let without_query = trimmed.split('?').next().unwrap_or(trimmed);
96 without_query.to_ascii_lowercase()
97}
98
99#[cfg(test)]
100mod tests {
101 use chrono::TimeZone;
102
103 use super::*;
104
105 fn event(
106 id: &str,
107 source: CalendarSource,
108 ical: Option<&str>,
109 join: Option<&str>,
110 ) -> CalendarEvent {
111 CalendarEvent {
112 object_id: id.into(),
113 subject: "Sync".into(),
114 start: chrono::Utc
115 .with_ymd_and_hms(2026, 11, 11, 10, 0, 0)
116 .unwrap(),
117 end: chrono::Utc
118 .with_ymd_and_hms(2026, 11, 11, 10, 30, 0)
119 .unwrap(),
120 ical_uid: ical.map(str::to_owned),
121 join_url: join.map(str::to_owned),
122 online: join.is_some(),
123 source,
124 sources: vec![source],
125 ..Default::default()
126 }
127 }
128
129 #[test]
130 fn merges_on_ical_uid_and_keeps_both_sources() {
131 let merged = merge_calendar_events(vec![
132 event("o1", CalendarSource::Outlook, Some("uid"), None),
133 event(
134 "g1",
135 CalendarSource::Google,
136 Some("uid"),
137 Some("https://teams.microsoft.com/l/meetup-join/x"),
138 ),
139 ]);
140 assert_eq!(merged.len(), 1);
141 assert_eq!(merged[0].sources.len(), 2);
142 assert_eq!(merged[0].object_id, "o1");
143 assert!(merged[0].join_url.is_some());
144 }
145
146 #[test]
147 fn occurrences_of_one_series_stay_separate() {
148 let join = Some("https://teams.microsoft.com/l/meetup-join/x");
149 let mut next_day = event("o2", CalendarSource::Outlook, Some("uid"), join);
150 next_day.start += chrono::Duration::days(1);
151 next_day.end += chrono::Duration::days(1);
152 let merged = merge_calendar_events(vec![
153 event("o1", CalendarSource::Outlook, Some("uid"), join),
154 next_day,
155 ]);
156 assert_eq!(merged.len(), 2);
157 }
158
159 #[test]
160 fn merges_on_normalized_join_url() {
161 let merged = merge_calendar_events(vec![
162 event(
163 "o1",
164 CalendarSource::Outlook,
165 None,
166 Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),
167 ),
168 event(
169 "g1",
170 CalendarSource::Google,
171 None,
172 Some("https://teams.microsoft.com/l/meetup-join/x/"),
173 ),
174 ]);
175 assert_eq!(merged.len(), 1);
176 }
177
178 #[test]
179 fn does_not_merge_on_title_and_time_alone() {
180 let a = event("a", CalendarSource::Outlook, Some("a"), None);
181 let mut b = event("b", CalendarSource::Google, Some("b"), None);
182 b.subject = a.subject.clone();
183 assert_eq!(merge_calendar_events(vec![a, b]).len(), 2);
184 }
185}
crates/chatsvc/src/ical/expand.rs added +158 −0
@@ -0,0 +1,158 @@
1 use chrono::{DateTime, TimeZone, Utc};
2 use rrule::{RRuleSet, Tz};
3
4 use super::parse::ParsedEvent;
5
6 /// Expand masters with RRULE into the window; apply EXDATE and RECURRENCE-ID overrides.
7 pub fn expand_events(
8 events: Vec<ParsedEvent>,
9 window_start: DateTime<Utc>,
10 window_end: DateTime<Utc>,
11 ) -> Vec<ParsedEvent> {
12 let mut overrides: Vec<ParsedEvent> = Vec::new();
13 let mut masters: Vec<ParsedEvent> = Vec::new();
14 for event in events {
15 if event.recurrence_id.is_some() {
16 overrides.push(event);
17 } else if event.rrule.is_some() || !event.rdates.is_empty() {
18 masters.push(event);
19 } else if event.start < window_end && event.end > window_start {
20 masters.push(event);
21 }
22 }
23
24 let mut out = Vec::new();
25 for master in masters {
26 if master.rrule.is_none() && master.rdates.is_empty() {
27 out.push(master);
28 continue;
29 }
30 let duration = master.end - master.start;
31 let occurrences = occurrence_starts(&master, window_start, window_end);
32 for start in occurrences {
33 if overrides.iter().any(|over| {
34 over.uid == master.uid
35 && over
36 .recurrence_id
37 .is_some_and(|id| (id - start).num_seconds().abs() < 60)
38 }) {
39 continue;
40 }
41 let mut occurrence = master.clone();
42 occurrence.start = start;
43 occurrence.end = start + duration;
44 occurrence.rrule = None;
45 occurrence.rdates.clear();
46 occurrence.exdates.clear();
47 out.push(occurrence);
48 }
49 }
50 for over in overrides {
51 if over.start < window_end && over.end > window_start && !over.cancelled {
52 out.push(over);
53 }
54 }
55 out.sort_by_key(|event| (event.start, event.end, event.uid.clone()));
56 out
57 }
58
59 fn occurrence_starts(
60 master: &ParsedEvent,
61 window_start: DateTime<Utc>,
62 window_end: DateTime<Utc>,
63 ) -> Vec<DateTime<Utc>> {
64 let mut starts = Vec::new();
65 if let Some(rrule) = &master.rrule {
66 let dtstart = master.start.format("%Y%m%dT%H%M%SZ").to_string();
67 let set_text = format!("DTSTART:{dtstart}\nRRULE:{rrule}");
68 if let Ok(set) = set_text.parse::<RRuleSet>() {
69 let after = Tz::UTC
70 .from_utc_datetime(&(window_start - chrono::Duration::seconds(1)).naive_utc());
71 let before = Tz::UTC.from_utc_datetime(&window_end.naive_utc());
72 let limited = set.after(after).before(before);
73 for dt in limited.all(512).dates {
74 starts.push(Utc.from_utc_datetime(&dt.naive_utc()));
75 }
76 }
77 } else if master.start < window_end && master.end > window_start {
78 starts.push(master.start);
79 }
80 for rdate in &master.rdates {
81 if *rdate >= window_start && *rdate < window_end {
82 starts.push(*rdate);
83 }
84 }
85 starts.retain(|start| {
86 !master
87 .exdates
88 .iter()
89 .any(|ex| (*ex - *start).num_seconds().abs() < 60)
90 });
91 starts.sort();
92 starts.dedup();
93 starts
94 }
95
96 #[cfg(test)]
97 mod tests {
98 use super::*;
99
100 fn master_weekly() -> ParsedEvent {
101 ParsedEvent {
102 uid: "series".into(),
103 href_hint: None,
104 summary: "Standup".into(),
105 start: Utc.with_ymd_and_hms(2025, 12, 1, 9, 0, 0).unwrap(),
106 end: Utc.with_ymd_and_hms(2025, 12, 1, 9, 30, 0).unwrap(),
107 all_day: false,
108 cancelled: false,
109 transparent: false,
110 description: None,
111 location: None,
112 join_url: None,
113 organizer: None,
114 attendees: Vec::new(),
115 reminders_minutes: Vec::new(),
116 rrule: Some("FREQ=WEEKLY;BYDAY=MO".into()),
117 rdates: Vec::new(),
118 exdates: vec![Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap()],
119 recurrence_id: None,
120 sequence: 0,
121 status: None,
122 }
123 }
124
125 #[test]
126 fn expands_series_older_than_window_and_honours_exdate() {
127 let window_start = Utc.with_ymd_and_hms(2026, 1, 5, 0, 0, 0).unwrap();
128 let window_end = Utc.with_ymd_and_hms(2026, 1, 19, 0, 0, 0).unwrap();
129 let expanded = expand_events(vec![master_weekly()], window_start, window_end);
130 let starts: Vec<_> = expanded.iter().map(|e| e.start).collect();
131 assert!(starts.contains(&Utc.with_ymd_and_hms(2026, 1, 5, 9, 0, 0).unwrap()));
132 assert!(!starts.contains(&Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap()));
133 }
134
135 #[test]
136 fn override_replaces_occurrence() {
137 let mut master = master_weekly();
138 master.rrule = Some("FREQ=WEEKLY;COUNT=3".into());
139 master.start = Utc.with_ymd_and_hms(2026, 1, 5, 9, 0, 0).unwrap();
140 master.end = Utc.with_ymd_and_hms(2026, 1, 5, 9, 30, 0).unwrap();
141 let over = ParsedEvent {
142 uid: "series".into(),
143 summary: "Moved".into(),
144 start: Utc.with_ymd_and_hms(2026, 1, 12, 10, 0, 0).unwrap(),
145 end: Utc.with_ymd_and_hms(2026, 1, 12, 10, 30, 0).unwrap(),
146 recurrence_id: Some(Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap()),
147 rrule: None,
148 ..master.clone()
149 };
150 let window_start = Utc.with_ymd_and_hms(2026, 1, 5, 0, 0, 0).unwrap();
151 let window_end = Utc.with_ymd_and_hms(2026, 1, 20, 0, 0, 0).unwrap();
152 let expanded = expand_events(vec![master, over], window_start, window_end);
153 assert!(expanded.iter().any(|e| e.summary == "Moved"));
154 assert!(!expanded.iter().any(|e| {
155 e.summary == "Standup" && e.start == Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap()
156 }));
157 }
158 }
@@ -0,0 +1,158 @@
1use chrono::{DateTime, TimeZone, Utc};
2use rrule::{RRuleSet, Tz};
3
4use super::parse::ParsedEvent;
5
6/// Expand masters with RRULE into the window; apply EXDATE and RECURRENCE-ID overrides.
7pub fn expand_events(
8 events: Vec<ParsedEvent>,
9 window_start: DateTime<Utc>,
10 window_end: DateTime<Utc>,
11) -> Vec<ParsedEvent> {
12 let mut overrides: Vec<ParsedEvent> = Vec::new();
13 let mut masters: Vec<ParsedEvent> = Vec::new();
14 for event in events {
15 if event.recurrence_id.is_some() {
16 overrides.push(event);
17 } else if event.rrule.is_some() || !event.rdates.is_empty() {
18 masters.push(event);
19 } else if event.start < window_end && event.end > window_start {
20 masters.push(event);
21 }
22 }
23
24 let mut out = Vec::new();
25 for master in masters {
26 if master.rrule.is_none() && master.rdates.is_empty() {
27 out.push(master);
28 continue;
29 }
30 let duration = master.end - master.start;
31 let occurrences = occurrence_starts(&master, window_start, window_end);
32 for start in occurrences {
33 if overrides.iter().any(|over| {
34 over.uid == master.uid
35 && over
36 .recurrence_id
37 .is_some_and(|id| (id - start).num_seconds().abs() < 60)
38 }) {
39 continue;
40 }
41 let mut occurrence = master.clone();
42 occurrence.start = start;
43 occurrence.end = start + duration;
44 occurrence.rrule = None;
45 occurrence.rdates.clear();
46 occurrence.exdates.clear();
47 out.push(occurrence);
48 }
49 }
50 for over in overrides {
51 if over.start < window_end && over.end > window_start && !over.cancelled {
52 out.push(over);
53 }
54 }
55 out.sort_by_key(|event| (event.start, event.end, event.uid.clone()));
56 out
57}
58
59fn occurrence_starts(
60 master: &ParsedEvent,
61 window_start: DateTime<Utc>,
62 window_end: DateTime<Utc>,
63) -> Vec<DateTime<Utc>> {
64 let mut starts = Vec::new();
65 if let Some(rrule) = &master.rrule {
66 let dtstart = master.start.format("%Y%m%dT%H%M%SZ").to_string();
67 let set_text = format!("DTSTART:{dtstart}\nRRULE:{rrule}");
68 if let Ok(set) = set_text.parse::<RRuleSet>() {
69 let after = Tz::UTC
70 .from_utc_datetime(&(window_start - chrono::Duration::seconds(1)).naive_utc());
71 let before = Tz::UTC.from_utc_datetime(&window_end.naive_utc());
72 let limited = set.after(after).before(before);
73 for dt in limited.all(512).dates {
74 starts.push(Utc.from_utc_datetime(&dt.naive_utc()));
75 }
76 }
77 } else if master.start < window_end && master.end > window_start {
78 starts.push(master.start);
79 }
80 for rdate in &master.rdates {
81 if *rdate >= window_start && *rdate < window_end {
82 starts.push(*rdate);
83 }
84 }
85 starts.retain(|start| {
86 !master
87 .exdates
88 .iter()
89 .any(|ex| (*ex - *start).num_seconds().abs() < 60)
90 });
91 starts.sort();
92 starts.dedup();
93 starts
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 fn master_weekly() -> ParsedEvent {
101 ParsedEvent {
102 uid: "series".into(),
103 href_hint: None,
104 summary: "Standup".into(),
105 start: Utc.with_ymd_and_hms(2025, 12, 1, 9, 0, 0).unwrap(),
106 end: Utc.with_ymd_and_hms(2025, 12, 1, 9, 30, 0).unwrap(),
107 all_day: false,
108 cancelled: false,
109 transparent: false,
110 description: None,
111 location: None,
112 join_url: None,
113 organizer: None,
114 attendees: Vec::new(),
115 reminders_minutes: Vec::new(),
116 rrule: Some("FREQ=WEEKLY;BYDAY=MO".into()),
117 rdates: Vec::new(),
118 exdates: vec![Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap()],
119 recurrence_id: None,
120 sequence: 0,
121 status: None,
122 }
123 }
124
125 #[test]
126 fn expands_series_older_than_window_and_honours_exdate() {
127 let window_start = Utc.with_ymd_and_hms(2026, 1, 5, 0, 0, 0).unwrap();
128 let window_end = Utc.with_ymd_and_hms(2026, 1, 19, 0, 0, 0).unwrap();
129 let expanded = expand_events(vec![master_weekly()], window_start, window_end);
130 let starts: Vec<_> = expanded.iter().map(|e| e.start).collect();
131 assert!(starts.contains(&Utc.with_ymd_and_hms(2026, 1, 5, 9, 0, 0).unwrap()));
132 assert!(!starts.contains(&Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap()));
133 }
134
135 #[test]
136 fn override_replaces_occurrence() {
137 let mut master = master_weekly();
138 master.rrule = Some("FREQ=WEEKLY;COUNT=3".into());
139 master.start = Utc.with_ymd_and_hms(2026, 1, 5, 9, 0, 0).unwrap();
140 master.end = Utc.with_ymd_and_hms(2026, 1, 5, 9, 30, 0).unwrap();
141 let over = ParsedEvent {
142 uid: "series".into(),
143 summary: "Moved".into(),
144 start: Utc.with_ymd_and_hms(2026, 1, 12, 10, 0, 0).unwrap(),
145 end: Utc.with_ymd_and_hms(2026, 1, 12, 10, 30, 0).unwrap(),
146 recurrence_id: Some(Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap()),
147 rrule: None,
148 ..master.clone()
149 };
150 let window_start = Utc.with_ymd_and_hms(2026, 1, 5, 0, 0, 0).unwrap();
151 let window_end = Utc.with_ymd_and_hms(2026, 1, 20, 0, 0, 0).unwrap();
152 let expanded = expand_events(vec![master, over], window_start, window_end);
153 assert!(expanded.iter().any(|e| e.summary == "Moved"));
154 assert!(!expanded.iter().any(|e| {
155 e.summary == "Standup" && e.start == Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap()
156 }));
157 }
158}
crates/chatsvc/src/ical/join.rs added +65 −0
@@ -0,0 +1,65 @@
1 /// Extract a Teams join URL from iCalendar fields (priority order from the CalDAV plan).
2 pub fn teams_join_url(
3 skype_url: Option<&str>,
4 url: Option<&str>,
5 location: Option<&str>,
6 description: Option<&str>,
7 ) -> Option<String> {
8 skype_url
9 .filter(|value| looks_like_teams(value))
10 .map(str::to_owned)
11 .or_else(|| url.filter(|value| looks_like_teams(value)).map(str::to_owned))
12 .or_else(|| {
13 location
14 .filter(|value| looks_like_teams(value))
15 .map(str::to_owned)
16 })
17 .or_else(|| description.and_then(find_in_text))
18 }
19
20 fn looks_like_teams(value: &str) -> bool {
21 value.contains("teams.microsoft.com") || value.contains("teams.live.com")
22 }
23
24 fn find_in_text(text: &str) -> Option<String> {
25 text.split_whitespace()
26 .find(|token| looks_like_teams(token))
27 .map(|token| {
28 token
29 .trim_end_matches(|c: char| matches!(c, '.' | ',' | ')' | ']' | '>' | '"'))
30 .to_owned()
31 })
32 }
33
34 #[cfg(test)]
35 mod tests {
36 use super::*;
37
38 #[test]
39 fn prefers_skype_property() {
40 let url = teams_join_url(
41 Some("https://teams.microsoft.com/l/meetup-join/a"),
42 Some("https://example.com"),
43 None,
44 Some("https://teams.microsoft.com/l/meetup-join/b"),
45 );
46 assert_eq!(
47 url.as_deref(),
48 Some("https://teams.microsoft.com/l/meetup-join/a")
49 );
50 }
51
52 #[test]
53 fn finds_link_in_description() {
54 let url = teams_join_url(
55 None,
56 None,
57 None,
58 Some("Join: https://teams.microsoft.com/l/meetup-join/x?a=1."),
59 );
60 assert_eq!(
61 url.as_deref(),
62 Some("https://teams.microsoft.com/l/meetup-join/x?a=1")
63 );
64 }
65 }
@@ -0,0 +1,65 @@
1/// Extract a Teams join URL from iCalendar fields (priority order from the CalDAV plan).
2pub fn teams_join_url(
3 skype_url: Option<&str>,
4 url: Option<&str>,
5 location: Option<&str>,
6 description: Option<&str>,
7) -> Option<String> {
8 skype_url
9 .filter(|value| looks_like_teams(value))
10 .map(str::to_owned)
11 .or_else(|| url.filter(|value| looks_like_teams(value)).map(str::to_owned))
12 .or_else(|| {
13 location
14 .filter(|value| looks_like_teams(value))
15 .map(str::to_owned)
16 })
17 .or_else(|| description.and_then(find_in_text))
18}
19
20fn looks_like_teams(value: &str) -> bool {
21 value.contains("teams.microsoft.com") || value.contains("teams.live.com")
22}
23
24fn find_in_text(text: &str) -> Option<String> {
25 text.split_whitespace()
26 .find(|token| looks_like_teams(token))
27 .map(|token| {
28 token
29 .trim_end_matches(|c: char| matches!(c, '.' | ',' | ')' | ']' | '>' | '"'))
30 .to_owned()
31 })
32}
33
34#[cfg(test)]
35mod tests {
36 use super::*;
37
38 #[test]
39 fn prefers_skype_property() {
40 let url = teams_join_url(
41 Some("https://teams.microsoft.com/l/meetup-join/a"),
42 Some("https://example.com"),
43 None,
44 Some("https://teams.microsoft.com/l/meetup-join/b"),
45 );
46 assert_eq!(
47 url.as_deref(),
48 Some("https://teams.microsoft.com/l/meetup-join/a")
49 );
50 }
51
52 #[test]
53 fn finds_link_in_description() {
54 let url = teams_join_url(
55 None,
56 None,
57 None,
58 Some("Join: https://teams.microsoft.com/l/meetup-join/x?a=1."),
59 );
60 assert_eq!(
61 url.as_deref(),
62 Some("https://teams.microsoft.com/l/meetup-join/x?a=1")
63 );
64 }
65}
crates/chatsvc/src/ical/mod.rs added +13 −0
@@ -0,0 +1,13 @@
1 //! Shared iCalendar parse / expand / write helpers for CalDAV and ICS subscriptions.
2
3 mod expand;
4 mod join;
5 mod parse;
6 mod timezone;
7 mod write;
8
9 pub use expand::expand_events;
10 pub use join::teams_join_url;
11 pub use parse::{ParsedEvent, parse_calendar};
12 pub use timezone::resolve_tzid;
13 pub use write::{CalDavEventDraft, build_vevent};
@@ -0,0 +1,13 @@
1//! Shared iCalendar parse / expand / write helpers for CalDAV and ICS subscriptions.
2
3mod expand;
4mod join;
5mod parse;
6mod timezone;
7mod write;
8
9pub use expand::expand_events;
10pub use join::teams_join_url;
11pub use parse::{ParsedEvent, parse_calendar};
12pub use timezone::resolve_tzid;
13pub use write::{CalDavEventDraft, build_vevent};
crates/chatsvc/src/ical/parse.rs added +421 −0
@@ -0,0 +1,421 @@
1 use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, TimeZone, Utc};
2
3 use super::join::teams_join_url;
4 use super::timezone::resolve_tzid;
5
6 #[derive(Debug, Clone, PartialEq, Eq)]
7 pub struct ParsedEvent {
8 pub uid: String,
9 pub href_hint: Option<String>,
10 pub summary: String,
11 pub start: DateTime<Utc>,
12 pub end: DateTime<Utc>,
13 pub all_day: bool,
14 pub cancelled: bool,
15 pub transparent: bool,
16 pub description: Option<String>,
17 pub location: Option<String>,
18 pub join_url: Option<String>,
19 pub organizer: Option<(String, Option<String>)>,
20 pub attendees: Vec<ParsedAttendee>,
21 pub reminders_minutes: Vec<u32>,
22 pub rrule: Option<String>,
23 pub rdates: Vec<DateTime<Utc>>,
24 pub exdates: Vec<DateTime<Utc>>,
25 pub recurrence_id: Option<DateTime<Utc>>,
26 pub sequence: u32,
27 pub status: Option<String>,
28 }
29
30 #[derive(Debug, Clone, PartialEq, Eq)]
31 pub struct ParsedAttendee {
32 pub cn: Option<String>,
33 pub mailto: String,
34 pub partstat: Option<String>,
35 pub role: Option<String>,
36 }
37
38 /// Parse one or more VEVENT components from an iCalendar document.
39 pub fn parse_calendar(ics: &str) -> Vec<ParsedEvent> {
40 let unfolded = unfold(ics);
41 let mut events = Vec::new();
42 let mut lines = unfolded.lines().peekable();
43 while let Some(line) = lines.next() {
44 if line.eq_ignore_ascii_case("BEGIN:VEVENT") {
45 let mut body = Vec::new();
46 for next in lines.by_ref() {
47 if next.eq_ignore_ascii_case("END:VEVENT") {
48 break;
49 }
50 body.push(next.to_owned());
51 }
52 if let Some(event) = parse_vevent(&body) {
53 events.push(event);
54 }
55 }
56 }
57 events
58 }
59
60 fn unfold(ics: &str) -> String {
61 let mut out = String::with_capacity(ics.len());
62 let mut chars = ics.chars().peekable();
63 while let Some(ch) = chars.next() {
64 if ch == '\r' {
65 continue;
66 }
67 if ch == '\n' {
68 if matches!(chars.peek(), Some(' ') | Some('\t')) {
69 chars.next();
70 continue;
71 }
72 out.push('\n');
73 continue;
74 }
75 out.push(ch);
76 }
77 out
78 }
79
80 fn parse_vevent(lines: &[String]) -> Option<ParsedEvent> {
81 let mut uid = String::new();
82 let mut summary = String::new();
83 let mut description = None;
84 let mut location = None;
85 let mut url = None;
86 let mut skype = None;
87 let mut start = None;
88 let mut end = None;
89 let mut duration = None;
90 let mut all_day = false;
91 let mut cancelled = false;
92 let mut transparent = false;
93 let mut organizer = None;
94 let mut attendees = Vec::new();
95 let mut reminders = Vec::new();
96 let mut rrule = None;
97 let mut rdates = Vec::new();
98 let mut exdates = Vec::new();
99 let mut recurrence_id = None;
100 let mut sequence = 0u32;
101 let mut status = None;
102 let mut in_alarm = false;
103 let mut alarm_trigger = None;
104
105 for line in lines {
106 let (name, params, value) = split_property(line);
107 let name_upper = name.to_ascii_uppercase();
108 if in_alarm {
109 if name_upper == "END" && value.eq_ignore_ascii_case("VALARM") {
110 if let Some(minutes) = alarm_trigger {
111 reminders.push(minutes);
112 }
113 alarm_trigger = None;
114 in_alarm = false;
115 } else if name_upper == "TRIGGER" {
116 alarm_trigger = parse_trigger_minutes(&value);
117 }
118 continue;
119 }
120 match name_upper.as_str() {
121 "BEGIN" if value.eq_ignore_ascii_case("VALARM") => in_alarm = true,
122 "UID" => uid = unescape(&value),
123 "SUMMARY" => summary = unescape(&value),
124 "DESCRIPTION" => description = Some(unescape(&value)),
125 "LOCATION" => location = Some(unescape(&value)),
126 "URL" => url = Some(unescape(&value)),
127 "X-MICROSOFT-SKYPETEAMSMEETINGURL" => skype = Some(unescape(&value)),
128 "DTSTART" => {
129 let (dt, day) = parse_date_value(&params, &value)?;
130 start = Some(dt);
131 all_day = day;
132 }
133 "DTEND" => {
134 let (dt, day) = parse_date_value(&params, &value)?;
135 // All-day DTEND is exclusive.
136 end = Some(if day { dt } else { dt });
137 if day {
138 all_day = true;
139 }
140 }
141 "DURATION" => duration = parse_duration(&value),
142 "STATUS" => {
143 status = Some(value.clone());
144 if value.eq_ignore_ascii_case("CANCELLED") {
145 cancelled = true;
146 }
147 }
148 "TRANSP" => transparent = value.eq_ignore_ascii_case("TRANSPARENT"),
149 "RRULE" => rrule = Some(value),
150 "RDATE" => rdates.extend(parse_multi_dates(&params, &value)),
151 "EXDATE" => exdates.extend(parse_multi_dates(&params, &value)),
152 "RECURRENCE-ID" => {
153 if let Some((dt, _)) = parse_date_value(&params, &value) {
154 recurrence_id = Some(dt);
155 }
156 }
157 "SEQUENCE" => sequence = value.parse().unwrap_or(0),
158 "ORGANIZER" => organizer = Some(parse_cal_address(&params, &value)),
159 "ATTENDEE" => attendees.push(parse_attendee(&params, &value)),
160 _ => {}
161 }
162 }
163
164 let start = start?;
165 let end = end.or_else(|| duration.map(|d| start + d)).unwrap_or_else(|| {
166 if all_day {
167 start + Duration::days(1)
168 } else {
169 start + Duration::hours(1)
170 }
171 });
172 let join = teams_join_url(
173 skype.as_deref(),
174 url.as_deref(),
175 location.as_deref(),
176 description.as_deref(),
177 );
178 Some(ParsedEvent {
179 uid,
180 href_hint: None,
181 summary,
182 start,
183 end,
184 all_day,
185 cancelled,
186 transparent,
187 description,
188 location: location.filter(|value| {
189 !value.contains("teams.microsoft.com") && !value.contains("teams.live.com")
190 }),
191 join_url: join,
192 organizer,
193 attendees,
194 reminders_minutes: reminders,
195 rrule,
196 rdates,
197 exdates,
198 recurrence_id,
199 sequence,
200 status,
201 })
202 }
203
204 fn split_property(line: &str) -> (String, Vec<(String, String)>, String) {
205 let (left, value) = match line.split_once(':') {
206 Some((l, v)) => (l, v.to_owned()),
207 None => (line, String::new()),
208 };
209 let mut parts = left.split(';');
210 let name = parts.next().unwrap_or("").to_owned();
211 let mut params = Vec::new();
212 for part in parts {
213 if let Some((k, v)) = part.split_once('=') {
214 params.push((k.to_ascii_uppercase(), v.trim_matches('"').to_owned()));
215 }
216 }
217 (name, params, value)
218 }
219
220 fn param<'a>(params: &'a [(String, String)], key: &str) -> Option<&'a str> {
221 params
222 .iter()
223 .find(|(k, _)| k.eq_ignore_ascii_case(key))
224 .map(|(_, v)| v.as_str())
225 }
226
227 fn parse_date_value(params: &[(String, String)], value: &str) -> Option<(DateTime<Utc>, bool)> {
228 let value_param = param(params, "VALUE").unwrap_or("");
229 let tzid = param(params, "TZID");
230 if value_param.eq_ignore_ascii_case("DATE") || (value.len() == 8 && !value.contains('T')) {
231 let date = NaiveDate::parse_from_str(value, "%Y%m%d").ok()?;
232 let start = date.and_hms_opt(0, 0, 0)?;
233 return Some((Utc.from_utc_datetime(&start), true));
234 }
235 let floating = !value.ends_with('Z') && tzid.is_none();
236 let naive = if value.ends_with('Z') {
237 NaiveDateTime::parse_from_str(value.trim_end_matches('Z'), "%Y%m%dT%H%M%S").ok()?
238 } else {
239 NaiveDateTime::parse_from_str(value, "%Y%m%dT%H%M%S")
240 .or_else(|_| NaiveDateTime::parse_from_str(value, "%Y%m%dT%H%M%S%.f"))
241 .ok()?
242 };
243 if value.ends_with('Z') {
244 return Some((Utc.from_utc_datetime(&naive), false));
245 }
246 if let Some(tzid) = tzid
247 && let Some(tz) = resolve_tzid(tzid)
248 {
249 return Some((
250 tz.from_local_datetime(&naive)
251 .single()
252 .or_else(|| tz.from_local_datetime(&naive).earliest())?
253 .with_timezone(&Utc),
254 false,
255 ));
256 }
257 if floating {
258 // Treat floating as local wall time interpreted via host offset later; store as UTC naive.
259 return Some((Utc.from_utc_datetime(&naive), false));
260 }
261 Some((Utc.from_utc_datetime(&naive), false))
262 }
263
264 fn parse_multi_dates(params: &[(String, String)], value: &str) -> Vec<DateTime<Utc>> {
265 value
266 .split(',')
267 .filter_map(|part| parse_date_value(params, part.trim()).map(|(dt, _)| dt))
268 .collect()
269 }
270
271 fn parse_duration(value: &str) -> Option<Duration> {
272 // PTnHnMnS / PnD subset
273 let mut rest = value.trim().trim_start_matches('+');
274 let negative = rest.starts_with('-');
275 if negative {
276 rest = &rest[1..];
277 }
278 if !rest.starts_with('P') {
279 return None;
280 }
281 rest = &rest[1..];
282 let mut total = Duration::zero();
283 if let Some((date, time)) = rest.split_once('T') {
284 total += parse_duration_date(date)?;
285 total += parse_duration_time(time)?;
286 } else if rest.contains('T') {
287 total += parse_duration_time(rest.trim_start_matches('T'))?;
288 } else {
289 total += parse_duration_date(rest)?;
290 }
291 Some(if negative { -total } else { total })
292 }
293
294 fn parse_duration_date(value: &str) -> Option<Duration> {
295 if value.is_empty() {
296 return Some(Duration::zero());
297 }
298 let mut num = String::new();
299 let mut total = Duration::zero();
300 for ch in value.chars() {
301 if ch.is_ascii_digit() {
302 num.push(ch);
303 continue;
304 }
305 let n: i64 = num.parse().ok()?;
306 num.clear();
307 total += match ch {
308 'D' => Duration::days(n),
309 'W' => Duration::weeks(n),
310 _ => return None,
311 };
312 }
313 Some(total)
314 }
315
316 fn parse_duration_time(value: &str) -> Option<Duration> {
317 let mut num = String::new();
318 let mut total = Duration::zero();
319 for ch in value.chars() {
320 if ch.is_ascii_digit() {
321 num.push(ch);
322 continue;
323 }
324 let n: i64 = num.parse().ok()?;
325 num.clear();
326 total += match ch {
327 'H' => Duration::hours(n),
328 'M' => Duration::minutes(n),
329 'S' => Duration::seconds(n),
330 _ => return None,
331 };
332 }
333 Some(total)
334 }
335
336 fn parse_trigger_minutes(value: &str) -> Option<u32> {
337 let duration = parse_duration(value)?;
338 let minutes = duration.num_minutes().unsigned_abs() as u32;
339 Some(minutes)
340 }
341
342 fn parse_cal_address(params: &[(String, String)], value: &str) -> (String, Option<String>) {
343 let mailto = value
344 .trim()
345 .trim_start_matches("mailto:")
346 .trim_start_matches("MAILTO:")
347 .to_owned();
348 let cn = param(params, "CN").map(str::to_owned);
349 (cn.unwrap_or_else(|| mailto.clone()), Some(mailto))
350 }
351
352 fn parse_attendee(params: &[(String, String)], value: &str) -> ParsedAttendee {
353 let mailto = value
354 .trim()
355 .trim_start_matches("mailto:")
356 .trim_start_matches("MAILTO:")
357 .to_owned();
358 ParsedAttendee {
359 cn: param(params, "CN").map(str::to_owned),
360 mailto,
361 partstat: param(params, "PARTSTAT").map(str::to_owned),
362 role: param(params, "ROLE").map(str::to_owned),
363 }
364 }
365
366 fn unescape(value: &str) -> String {
367 let mut out = String::with_capacity(value.len());
368 let mut chars = value.chars();
369 while let Some(ch) = chars.next() {
370 if ch == '\\' {
371 match chars.next() {
372 Some('n') | Some('N') => out.push('\n'),
373 Some(',') => out.push(','),
374 Some(';') => out.push(';'),
375 Some('\\') => out.push('\\'),
376 Some(other) => out.push(other),
377 None => out.push('\\'),
378 }
379 } else {
380 out.push(ch);
381 }
382 }
383 out
384 }
385
386 #[cfg(test)]
387 mod tests {
388 use super::*;
389
390 #[test]
391 fn unfolds_and_parses_all_day_exclusive_end() {
392 let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:1\r\nSUMMARY:Holiday\r\nDTSTART;VALUE=DATE:20260101\r\nDTEND;VALUE=DATE:20260102\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
393 let events = parse_calendar(ics);
394 assert_eq!(events.len(), 1);
395 assert!(events[0].all_day);
396 assert_eq!(
397 events[0].start,
398 Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap()
399 );
400 assert_eq!(
401 events[0].end,
402 Utc.with_ymd_and_hms(2026, 1, 2, 0, 0, 0).unwrap()
403 );
404 }
405
406 #[test]
407 fn folds_long_summary() {
408 let ics = "BEGIN:VEVENT\nUID:1\nSUMMARY:Hello\n world\nDTSTART:20260101T100000Z\nDTEND:20260101T110000Z\nEND:VEVENT\n";
409 let events = parse_calendar(ics);
410 assert_eq!(events[0].summary, "Hello world");
411 }
412
413 #[test]
414 fn groups_override_separately() {
415 let ics = "BEGIN:VCALENDAR\nBEGIN:VEVENT\nUID:series\nSUMMARY:Master\nDTSTART:20260105T100000Z\nDTEND:20260105T110000Z\nRRULE:FREQ=WEEKLY\nEND:VEVENT\nBEGIN:VEVENT\nUID:series\nSUMMARY:Changed\nDTSTART:20260112T100000Z\nDTEND:20260112T110000Z\nRECURRENCE-ID:20260112T100000Z\nEND:VEVENT\nEND:VCALENDAR\n";
416 let events = parse_calendar(ics);
417 assert_eq!(events.len(), 2);
418 assert!(events[0].rrule.is_some());
419 assert!(events[1].recurrence_id.is_some());
420 }
421 }
@@ -0,0 +1,421 @@
1use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, TimeZone, Utc};
2
3use super::join::teams_join_url;
4use super::timezone::resolve_tzid;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct ParsedEvent {
8 pub uid: String,
9 pub href_hint: Option<String>,
10 pub summary: String,
11 pub start: DateTime<Utc>,
12 pub end: DateTime<Utc>,
13 pub all_day: bool,
14 pub cancelled: bool,
15 pub transparent: bool,
16 pub description: Option<String>,
17 pub location: Option<String>,
18 pub join_url: Option<String>,
19 pub organizer: Option<(String, Option<String>)>,
20 pub attendees: Vec<ParsedAttendee>,
21 pub reminders_minutes: Vec<u32>,
22 pub rrule: Option<String>,
23 pub rdates: Vec<DateTime<Utc>>,
24 pub exdates: Vec<DateTime<Utc>>,
25 pub recurrence_id: Option<DateTime<Utc>>,
26 pub sequence: u32,
27 pub status: Option<String>,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct ParsedAttendee {
32 pub cn: Option<String>,
33 pub mailto: String,
34 pub partstat: Option<String>,
35 pub role: Option<String>,
36}
37
38/// Parse one or more VEVENT components from an iCalendar document.
39pub fn parse_calendar(ics: &str) -> Vec<ParsedEvent> {
40 let unfolded = unfold(ics);
41 let mut events = Vec::new();
42 let mut lines = unfolded.lines().peekable();
43 while let Some(line) = lines.next() {
44 if line.eq_ignore_ascii_case("BEGIN:VEVENT") {
45 let mut body = Vec::new();
46 for next in lines.by_ref() {
47 if next.eq_ignore_ascii_case("END:VEVENT") {
48 break;
49 }
50 body.push(next.to_owned());
51 }
52 if let Some(event) = parse_vevent(&body) {
53 events.push(event);
54 }
55 }
56 }
57 events
58}
59
60fn unfold(ics: &str) -> String {
61 let mut out = String::with_capacity(ics.len());
62 let mut chars = ics.chars().peekable();
63 while let Some(ch) = chars.next() {
64 if ch == '\r' {
65 continue;
66 }
67 if ch == '\n' {
68 if matches!(chars.peek(), Some(' ') | Some('\t')) {
69 chars.next();
70 continue;
71 }
72 out.push('\n');
73 continue;
74 }
75 out.push(ch);
76 }
77 out
78}
79
80fn parse_vevent(lines: &[String]) -> Option<ParsedEvent> {
81 let mut uid = String::new();
82 let mut summary = String::new();
83 let mut description = None;
84 let mut location = None;
85 let mut url = None;
86 let mut skype = None;
87 let mut start = None;
88 let mut end = None;
89 let mut duration = None;
90 let mut all_day = false;
91 let mut cancelled = false;
92 let mut transparent = false;
93 let mut organizer = None;
94 let mut attendees = Vec::new();
95 let mut reminders = Vec::new();
96 let mut rrule = None;
97 let mut rdates = Vec::new();
98 let mut exdates = Vec::new();
99 let mut recurrence_id = None;
100 let mut sequence = 0u32;
101 let mut status = None;
102 let mut in_alarm = false;
103 let mut alarm_trigger = None;
104
105 for line in lines {
106 let (name, params, value) = split_property(line);
107 let name_upper = name.to_ascii_uppercase();
108 if in_alarm {
109 if name_upper == "END" && value.eq_ignore_ascii_case("VALARM") {
110 if let Some(minutes) = alarm_trigger {
111 reminders.push(minutes);
112 }
113 alarm_trigger = None;
114 in_alarm = false;
115 } else if name_upper == "TRIGGER" {
116 alarm_trigger = parse_trigger_minutes(&value);
117 }
118 continue;
119 }
120 match name_upper.as_str() {
121 "BEGIN" if value.eq_ignore_ascii_case("VALARM") => in_alarm = true,
122 "UID" => uid = unescape(&value),
123 "SUMMARY" => summary = unescape(&value),
124 "DESCRIPTION" => description = Some(unescape(&value)),
125 "LOCATION" => location = Some(unescape(&value)),
126 "URL" => url = Some(unescape(&value)),
127 "X-MICROSOFT-SKYPETEAMSMEETINGURL" => skype = Some(unescape(&value)),
128 "DTSTART" => {
129 let (dt, day) = parse_date_value(&params, &value)?;
130 start = Some(dt);
131 all_day = day;
132 }
133 "DTEND" => {
134 let (dt, day) = parse_date_value(&params, &value)?;
135 // All-day DTEND is exclusive.
136 end = Some(if day { dt } else { dt });
137 if day {
138 all_day = true;
139 }
140 }
141 "DURATION" => duration = parse_duration(&value),
142 "STATUS" => {
143 status = Some(value.clone());
144 if value.eq_ignore_ascii_case("CANCELLED") {
145 cancelled = true;
146 }
147 }
148 "TRANSP" => transparent = value.eq_ignore_ascii_case("TRANSPARENT"),
149 "RRULE" => rrule = Some(value),
150 "RDATE" => rdates.extend(parse_multi_dates(&params, &value)),
151 "EXDATE" => exdates.extend(parse_multi_dates(&params, &value)),
152 "RECURRENCE-ID" => {
153 if let Some((dt, _)) = parse_date_value(&params, &value) {
154 recurrence_id = Some(dt);
155 }
156 }
157 "SEQUENCE" => sequence = value.parse().unwrap_or(0),
158 "ORGANIZER" => organizer = Some(parse_cal_address(&params, &value)),
159 "ATTENDEE" => attendees.push(parse_attendee(&params, &value)),
160 _ => {}
161 }
162 }
163
164 let start = start?;
165 let end = end.or_else(|| duration.map(|d| start + d)).unwrap_or_else(|| {
166 if all_day {
167 start + Duration::days(1)
168 } else {
169 start + Duration::hours(1)
170 }
171 });
172 let join = teams_join_url(
173 skype.as_deref(),
174 url.as_deref(),
175 location.as_deref(),
176 description.as_deref(),
177 );
178 Some(ParsedEvent {
179 uid,
180 href_hint: None,
181 summary,
182 start,
183 end,
184 all_day,
185 cancelled,
186 transparent,
187 description,
188 location: location.filter(|value| {
189 !value.contains("teams.microsoft.com") && !value.contains("teams.live.com")
190 }),
191 join_url: join,
192 organizer,
193 attendees,
194 reminders_minutes: reminders,
195 rrule,
196 rdates,
197 exdates,
198 recurrence_id,
199 sequence,
200 status,
201 })
202}
203
204fn split_property(line: &str) -> (String, Vec<(String, String)>, String) {
205 let (left, value) = match line.split_once(':') {
206 Some((l, v)) => (l, v.to_owned()),
207 None => (line, String::new()),
208 };
209 let mut parts = left.split(';');
210 let name = parts.next().unwrap_or("").to_owned();
211 let mut params = Vec::new();
212 for part in parts {
213 if let Some((k, v)) = part.split_once('=') {
214 params.push((k.to_ascii_uppercase(), v.trim_matches('"').to_owned()));
215 }
216 }
217 (name, params, value)
218}
219
220fn param<'a>(params: &'a [(String, String)], key: &str) -> Option<&'a str> {
221 params
222 .iter()
223 .find(|(k, _)| k.eq_ignore_ascii_case(key))
224 .map(|(_, v)| v.as_str())
225}
226
227fn parse_date_value(params: &[(String, String)], value: &str) -> Option<(DateTime<Utc>, bool)> {
228 let value_param = param(params, "VALUE").unwrap_or("");
229 let tzid = param(params, "TZID");
230 if value_param.eq_ignore_ascii_case("DATE") || (value.len() == 8 && !value.contains('T')) {
231 let date = NaiveDate::parse_from_str(value, "%Y%m%d").ok()?;
232 let start = date.and_hms_opt(0, 0, 0)?;
233 return Some((Utc.from_utc_datetime(&start), true));
234 }
235 let floating = !value.ends_with('Z') && tzid.is_none();
236 let naive = if value.ends_with('Z') {
237 NaiveDateTime::parse_from_str(value.trim_end_matches('Z'), "%Y%m%dT%H%M%S").ok()?
238 } else {
239 NaiveDateTime::parse_from_str(value, "%Y%m%dT%H%M%S")
240 .or_else(|_| NaiveDateTime::parse_from_str(value, "%Y%m%dT%H%M%S%.f"))
241 .ok()?
242 };
243 if value.ends_with('Z') {
244 return Some((Utc.from_utc_datetime(&naive), false));
245 }
246 if let Some(tzid) = tzid
247 && let Some(tz) = resolve_tzid(tzid)
248 {
249 return Some((
250 tz.from_local_datetime(&naive)
251 .single()
252 .or_else(|| tz.from_local_datetime(&naive).earliest())?
253 .with_timezone(&Utc),
254 false,
255 ));
256 }
257 if floating {
258 // Treat floating as local wall time interpreted via host offset later; store as UTC naive.
259 return Some((Utc.from_utc_datetime(&naive), false));
260 }
261 Some((Utc.from_utc_datetime(&naive), false))
262}
263
264fn parse_multi_dates(params: &[(String, String)], value: &str) -> Vec<DateTime<Utc>> {
265 value
266 .split(',')
267 .filter_map(|part| parse_date_value(params, part.trim()).map(|(dt, _)| dt))
268 .collect()
269}
270
271fn parse_duration(value: &str) -> Option<Duration> {
272 // PTnHnMnS / PnD subset
273 let mut rest = value.trim().trim_start_matches('+');
274 let negative = rest.starts_with('-');
275 if negative {
276 rest = &rest[1..];
277 }
278 if !rest.starts_with('P') {
279 return None;
280 }
281 rest = &rest[1..];
282 let mut total = Duration::zero();
283 if let Some((date, time)) = rest.split_once('T') {
284 total += parse_duration_date(date)?;
285 total += parse_duration_time(time)?;
286 } else if rest.contains('T') {
287 total += parse_duration_time(rest.trim_start_matches('T'))?;
288 } else {
289 total += parse_duration_date(rest)?;
290 }
291 Some(if negative { -total } else { total })
292}
293
294fn parse_duration_date(value: &str) -> Option<Duration> {
295 if value.is_empty() {
296 return Some(Duration::zero());
297 }
298 let mut num = String::new();
299 let mut total = Duration::zero();
300 for ch in value.chars() {
301 if ch.is_ascii_digit() {
302 num.push(ch);
303 continue;
304 }
305 let n: i64 = num.parse().ok()?;
306 num.clear();
307 total += match ch {
308 'D' => Duration::days(n),
309 'W' => Duration::weeks(n),
310 _ => return None,
311 };
312 }
313 Some(total)
314}
315
316fn parse_duration_time(value: &str) -> Option<Duration> {
317 let mut num = String::new();
318 let mut total = Duration::zero();
319 for ch in value.chars() {
320 if ch.is_ascii_digit() {
321 num.push(ch);
322 continue;
323 }
324 let n: i64 = num.parse().ok()?;
325 num.clear();
326 total += match ch {
327 'H' => Duration::hours(n),
328 'M' => Duration::minutes(n),
329 'S' => Duration::seconds(n),
330 _ => return None,
331 };
332 }
333 Some(total)
334}
335
336fn parse_trigger_minutes(value: &str) -> Option<u32> {
337 let duration = parse_duration(value)?;
338 let minutes = duration.num_minutes().unsigned_abs() as u32;
339 Some(minutes)
340}
341
342fn parse_cal_address(params: &[(String, String)], value: &str) -> (String, Option<String>) {
343 let mailto = value
344 .trim()
345 .trim_start_matches("mailto:")
346 .trim_start_matches("MAILTO:")
347 .to_owned();
348 let cn = param(params, "CN").map(str::to_owned);
349 (cn.unwrap_or_else(|| mailto.clone()), Some(mailto))
350}
351
352fn parse_attendee(params: &[(String, String)], value: &str) -> ParsedAttendee {
353 let mailto = value
354 .trim()
355 .trim_start_matches("mailto:")
356 .trim_start_matches("MAILTO:")
357 .to_owned();
358 ParsedAttendee {
359 cn: param(params, "CN").map(str::to_owned),
360 mailto,
361 partstat: param(params, "PARTSTAT").map(str::to_owned),
362 role: param(params, "ROLE").map(str::to_owned),
363 }
364}
365
366fn unescape(value: &str) -> String {
367 let mut out = String::with_capacity(value.len());
368 let mut chars = value.chars();
369 while let Some(ch) = chars.next() {
370 if ch == '\\' {
371 match chars.next() {
372 Some('n') | Some('N') => out.push('\n'),
373 Some(',') => out.push(','),
374 Some(';') => out.push(';'),
375 Some('\\') => out.push('\\'),
376 Some(other) => out.push(other),
377 None => out.push('\\'),
378 }
379 } else {
380 out.push(ch);
381 }
382 }
383 out
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 #[test]
391 fn unfolds_and_parses_all_day_exclusive_end() {
392 let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:1\r\nSUMMARY:Holiday\r\nDTSTART;VALUE=DATE:20260101\r\nDTEND;VALUE=DATE:20260102\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
393 let events = parse_calendar(ics);
394 assert_eq!(events.len(), 1);
395 assert!(events[0].all_day);
396 assert_eq!(
397 events[0].start,
398 Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap()
399 );
400 assert_eq!(
401 events[0].end,
402 Utc.with_ymd_and_hms(2026, 1, 2, 0, 0, 0).unwrap()
403 );
404 }
405
406 #[test]
407 fn folds_long_summary() {
408 let ics = "BEGIN:VEVENT\nUID:1\nSUMMARY:Hello\n world\nDTSTART:20260101T100000Z\nDTEND:20260101T110000Z\nEND:VEVENT\n";
409 let events = parse_calendar(ics);
410 assert_eq!(events[0].summary, "Hello world");
411 }
412
413 #[test]
414 fn groups_override_separately() {
415 let ics = "BEGIN:VCALENDAR\nBEGIN:VEVENT\nUID:series\nSUMMARY:Master\nDTSTART:20260105T100000Z\nDTEND:20260105T110000Z\nRRULE:FREQ=WEEKLY\nEND:VEVENT\nBEGIN:VEVENT\nUID:series\nSUMMARY:Changed\nDTSTART:20260112T100000Z\nDTEND:20260112T110000Z\nRECURRENCE-ID:20260112T100000Z\nEND:VEVENT\nEND:VCALENDAR\n";
416 let events = parse_calendar(ics);
417 assert_eq!(events.len(), 2);
418 assert!(events[0].rrule.is_some());
419 assert!(events[1].recurrence_id.is_some());
420 }
421}
crates/chatsvc/src/ical/timezone.rs added +51 −0
@@ -0,0 +1,51 @@
1 use chrono_tz::Tz;
2
3 /// Resolve a TZID to chrono-tz, including common Windows zone names from Outlook iMIP.
4 pub fn resolve_tzid(tzid: &str) -> Option<Tz> {
5 let trimmed = tzid.trim().trim_matches('"');
6 if trimmed.is_empty() {
7 return None;
8 }
9 if let Ok(tz) = trimmed.parse::<Tz>() {
10 return Some(tz);
11 }
12 windows_to_iana(trimmed).and_then(|iana| iana.parse().ok())
13 }
14
15 fn windows_to_iana(name: &str) -> Option<&'static str> {
16 Some(match name {
17 "W. Europe Standard Time" => "Europe/Berlin",
18 "Central European Standard Time" => "Europe/Warsaw",
19 "Romance Standard Time" => "Europe/Paris",
20 "GMT Standard Time" => "Europe/London",
21 "UTC" | "Coordinated Universal Time" => "UTC",
22 "Pacific Standard Time" => "America/Los_Angeles",
23 "Mountain Standard Time" => "America/Denver",
24 "Central Standard Time" => "America/Chicago",
25 "Eastern Standard Time" => "America/New_York",
26 "Tokyo Standard Time" => "Asia/Tokyo",
27 "China Standard Time" => "Asia/Shanghai",
28 "AUS Eastern Standard Time" => "Australia/Sydney",
29 "Russian Standard Time" => "Europe/Moscow",
30 "India Standard Time" => "Asia/Kolkata",
31 _ => return None,
32 })
33 }
34
35 #[cfg(test)]
36 mod tests {
37 use super::*;
38
39 #[test]
40 fn maps_windows_w_europe() {
41 assert_eq!(
42 resolve_tzid("W. Europe Standard Time"),
43 Some(chrono_tz::Europe::Berlin)
44 );
45 }
46
47 #[test]
48 fn parses_iana() {
49 assert_eq!(resolve_tzid("Europe/Zurich"), Some(chrono_tz::Europe::Zurich));
50 }
51 }
@@ -0,0 +1,51 @@
1use chrono_tz::Tz;
2
3/// Resolve a TZID to chrono-tz, including common Windows zone names from Outlook iMIP.
4pub fn resolve_tzid(tzid: &str) -> Option<Tz> {
5 let trimmed = tzid.trim().trim_matches('"');
6 if trimmed.is_empty() {
7 return None;
8 }
9 if let Ok(tz) = trimmed.parse::<Tz>() {
10 return Some(tz);
11 }
12 windows_to_iana(trimmed).and_then(|iana| iana.parse().ok())
13}
14
15fn windows_to_iana(name: &str) -> Option<&'static str> {
16 Some(match name {
17 "W. Europe Standard Time" => "Europe/Berlin",
18 "Central European Standard Time" => "Europe/Warsaw",
19 "Romance Standard Time" => "Europe/Paris",
20 "GMT Standard Time" => "Europe/London",
21 "UTC" | "Coordinated Universal Time" => "UTC",
22 "Pacific Standard Time" => "America/Los_Angeles",
23 "Mountain Standard Time" => "America/Denver",
24 "Central Standard Time" => "America/Chicago",
25 "Eastern Standard Time" => "America/New_York",
26 "Tokyo Standard Time" => "Asia/Tokyo",
27 "China Standard Time" => "Asia/Shanghai",
28 "AUS Eastern Standard Time" => "Australia/Sydney",
29 "Russian Standard Time" => "Europe/Moscow",
30 "India Standard Time" => "Asia/Kolkata",
31 _ => return None,
32 })
33}
34
35#[cfg(test)]
36mod tests {
37 use super::*;
38
39 #[test]
40 fn maps_windows_w_europe() {
41 assert_eq!(
42 resolve_tzid("W. Europe Standard Time"),
43 Some(chrono_tz::Europe::Berlin)
44 );
45 }
46
47 #[test]
48 fn parses_iana() {
49 assert_eq!(resolve_tzid("Europe/Zurich"), Some(chrono_tz::Europe::Zurich));
50 }
51}
crates/chatsvc/src/ical/write.rs added +110 −0
@@ -0,0 +1,110 @@
1 use chrono::{DateTime, Utc};
2
3 use crate::calendar::Repeat;
4 use crate::google_calendar::rrule_for_repeat;
5
6 #[derive(Debug, Clone)]
7 pub struct CalDavEventDraft {
8 pub uid: String,
9 pub summary: String,
10 pub start: DateTime<Utc>,
11 pub end: DateTime<Utc>,
12 pub all_day: bool,
13 pub description: Option<String>,
14 pub location: Option<String>,
15 pub join_url: Option<String>,
16 pub attendees: Vec<String>,
17 pub repeat: Repeat,
18 pub sequence: u32,
19 }
20
21 /// Build a VCALENDAR 2.0 document containing one VEVENT (no METHOD).
22 pub fn build_vevent(draft: &CalDavEventDraft, stamp: DateTime<Utc>) -> String {
23 let mut lines = vec![
24 "BEGIN:VCALENDAR".to_owned(),
25 "VERSION:2.0".to_owned(),
26 "PRODID:-//rusty-teams//CalDAV//EN".to_owned(),
27 "CALSCALE:GREGORIAN".to_owned(),
28 "BEGIN:VEVENT".to_owned(),
29 format!("UID:{}", draft.uid),
30 format!("DTSTAMP:{}", format_utc(stamp)),
31 format!("SEQUENCE:{}", draft.sequence),
32 format!("SUMMARY:{}", escape(&draft.summary)),
33 ];
34 if draft.all_day {
35 lines.push(format!(
36 "DTSTART;VALUE=DATE:{}",
37 draft.start.format("%Y%m%d")
38 ));
39 lines.push(format!("DTEND;VALUE=DATE:{}", draft.end.format("%Y%m%d")));
40 } else {
41 lines.push(format!("DTSTART:{}", format_utc(draft.start)));
42 lines.push(format!("DTEND:{}", format_utc(draft.end)));
43 }
44 let mut description = draft.description.clone().unwrap_or_default();
45 if let Some(join) = &draft.join_url {
46 if !description.is_empty() {
47 description.push_str("\n\n");
48 }
49 description.push_str(join);
50 lines.push(format!("URL:{join}"));
51 }
52 if !description.is_empty() {
53 lines.push(format!("DESCRIPTION:{}", escape(&description)));
54 }
55 if let Some(location) = &draft.location {
56 lines.push(format!("LOCATION:{}", escape(location)));
57 }
58 if let Some(rrule) = rrule_for_repeat(draft.repeat, draft.start.naive_utc()) {
59 let rule = rrule.trim_start_matches("RRULE:");
60 lines.push(format!("RRULE:{rule}"));
61 }
62 for attendee in &draft.attendees {
63 lines.push(format!("ATTENDEE:mailto:{attendee}"));
64 }
65 lines.push("END:VEVENT".to_owned());
66 lines.push("END:VCALENDAR".to_owned());
67 lines.join("\r\n") + "\r\n"
68 }
69
70 fn format_utc(dt: DateTime<Utc>) -> String {
71 dt.format("%Y%m%dT%H%M%SZ").to_string()
72 }
73
74 fn escape(value: &str) -> String {
75 value
76 .replace('\\', "\\\\")
77 .replace('\n', "\\n")
78 .replace(',', "\\,")
79 .replace(';', "\\;")
80 }
81
82 #[cfg(test)]
83 mod tests {
84 use super::*;
85 use chrono::TimeZone;
86
87 #[test]
88 fn builds_without_method() {
89 let ics = build_vevent(
90 &CalDavEventDraft {
91 uid: "u1".into(),
92 summary: "Meet".into(),
93 start: Utc.with_ymd_and_hms(2026, 1, 1, 10, 0, 0).unwrap(),
94 end: Utc.with_ymd_and_hms(2026, 1, 1, 11, 0, 0).unwrap(),
95 all_day: false,
96 description: None,
97 location: None,
98 join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
99 attendees: vec!["a@b.c".into()],
100 repeat: Repeat::Never,
101 sequence: 0,
102 },
103 Utc.with_ymd_and_hms(2026, 1, 1, 9, 0, 0).unwrap(),
104 );
105 assert!(ics.contains("BEGIN:VCALENDAR"));
106 assert!(!ics.contains("METHOD:"));
107 assert!(ics.contains("URL:https://teams.microsoft.com/l/meetup-join/x"));
108 assert!(ics.contains("ATTENDEE:mailto:a@b.c"));
109 }
110 }
@@ -0,0 +1,110 @@
1use chrono::{DateTime, Utc};
2
3use crate::calendar::Repeat;
4use crate::google_calendar::rrule_for_repeat;
5
6#[derive(Debug, Clone)]
7pub struct CalDavEventDraft {
8 pub uid: String,
9 pub summary: String,
10 pub start: DateTime<Utc>,
11 pub end: DateTime<Utc>,
12 pub all_day: bool,
13 pub description: Option<String>,
14 pub location: Option<String>,
15 pub join_url: Option<String>,
16 pub attendees: Vec<String>,
17 pub repeat: Repeat,
18 pub sequence: u32,
19}
20
21/// Build a VCALENDAR 2.0 document containing one VEVENT (no METHOD).
22pub fn build_vevent(draft: &CalDavEventDraft, stamp: DateTime<Utc>) -> String {
23 let mut lines = vec![
24 "BEGIN:VCALENDAR".to_owned(),
25 "VERSION:2.0".to_owned(),
26 "PRODID:-//rusty-teams//CalDAV//EN".to_owned(),
27 "CALSCALE:GREGORIAN".to_owned(),
28 "BEGIN:VEVENT".to_owned(),
29 format!("UID:{}", draft.uid),
30 format!("DTSTAMP:{}", format_utc(stamp)),
31 format!("SEQUENCE:{}", draft.sequence),
32 format!("SUMMARY:{}", escape(&draft.summary)),
33 ];
34 if draft.all_day {
35 lines.push(format!(
36 "DTSTART;VALUE=DATE:{}",
37 draft.start.format("%Y%m%d")
38 ));
39 lines.push(format!("DTEND;VALUE=DATE:{}", draft.end.format("%Y%m%d")));
40 } else {
41 lines.push(format!("DTSTART:{}", format_utc(draft.start)));
42 lines.push(format!("DTEND:{}", format_utc(draft.end)));
43 }
44 let mut description = draft.description.clone().unwrap_or_default();
45 if let Some(join) = &draft.join_url {
46 if !description.is_empty() {
47 description.push_str("\n\n");
48 }
49 description.push_str(join);
50 lines.push(format!("URL:{join}"));
51 }
52 if !description.is_empty() {
53 lines.push(format!("DESCRIPTION:{}", escape(&description)));
54 }
55 if let Some(location) = &draft.location {
56 lines.push(format!("LOCATION:{}", escape(location)));
57 }
58 if let Some(rrule) = rrule_for_repeat(draft.repeat, draft.start.naive_utc()) {
59 let rule = rrule.trim_start_matches("RRULE:");
60 lines.push(format!("RRULE:{rule}"));
61 }
62 for attendee in &draft.attendees {
63 lines.push(format!("ATTENDEE:mailto:{attendee}"));
64 }
65 lines.push("END:VEVENT".to_owned());
66 lines.push("END:VCALENDAR".to_owned());
67 lines.join("\r\n") + "\r\n"
68}
69
70fn format_utc(dt: DateTime<Utc>) -> String {
71 dt.format("%Y%m%dT%H%M%SZ").to_string()
72}
73
74fn escape(value: &str) -> String {
75 value
76 .replace('\\', "\\\\")
77 .replace('\n', "\\n")
78 .replace(',', "\\,")
79 .replace(';', "\\;")
80}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85 use chrono::TimeZone;
86
87 #[test]
88 fn builds_without_method() {
89 let ics = build_vevent(
90 &CalDavEventDraft {
91 uid: "u1".into(),
92 summary: "Meet".into(),
93 start: Utc.with_ymd_and_hms(2026, 1, 1, 10, 0, 0).unwrap(),
94 end: Utc.with_ymd_and_hms(2026, 1, 1, 11, 0, 0).unwrap(),
95 all_day: false,
96 description: None,
97 location: None,
98 join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
99 attendees: vec!["a@b.c".into()],
100 repeat: Repeat::Never,
101 sequence: 0,
102 },
103 Utc.with_ymd_and_hms(2026, 1, 1, 9, 0, 0).unwrap(),
104 );
105 assert!(ics.contains("BEGIN:VCALENDAR"));
106 assert!(!ics.contains("METHOD:"));
107 assert!(ics.contains("URL:https://teams.microsoft.com/l/meetup-join/x"));
108 assert!(ics.contains("ATTENDEE:mailto:a@b.c"));
109 }
110}
crates/chatsvc/src/lib.rs +12 −6
@@ -3,8 +3,10 @@ pub mod activity_mentions;
3 3 pub mod ams;
4 4 pub mod bot_profiles;
5 5 pub mod calendar;
6 pub mod caldav;
6 7 pub mod calllog;
7 8 pub mod cards;
9 pub mod ical;
8 10 pub mod channel_notifications;
9 11 pub mod channel_visibility;
10 12 pub mod chat_listing;
@@ -58,11 +60,16 @@ pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};
58 60 pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
59 61 pub use calendar::{
60 62 Attendee, AttendeeResponseCounts, BusyTime, Calendar, CalendarEvent, CalendarSource,
61 CreatedEvent, DialIn, EventAttendee, NewEvent, PersonSchedule, Reminder, Repeat, Reply,
62 ResponseType, ShowAs, apply_event_details, join_info_text, meet_now_join_url, new_event_body,
63 new_event_body_with_join, parse_calendar_events, parse_created_event, strip_html,
64 truncate_preview,
63 CreatedEvent, DialIn, EventAttendee, HomeCalendar, NewEvent, PersonSchedule, Reminder, Repeat,
64 Reply, ResponseType, ShowAs, apply_event_details, join_info_text, meet_now_join_url,
65 merge_calendar_events, new_event_body, new_event_body_with_join, normalize_join_url,
66 parse_calendar_events, parse_created_event, strip_html, truncate_preview,
65 67 };
68 pub use caldav::{
69 CalDavClient, CalDavEvent, ListedCalendar, discover as discover_caldav, new_event_uid,
70 partstat_for_reply,
71 };
72 pub use ical::{CalDavEventDraft, build_vevent, expand_events, parse_calendar, teams_join_url};
66 73 pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
67 74 pub use cards::{
68 75 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
@@ -85,8 +92,7 @@ pub use gifs::{Gif, Gifs};
85 92 pub use google_calendar::{
86 93 AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
87 94 client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,
88 merge_calendar_events, normalize_join_url, parse_calendar_list, parse_google_events,
89 refresh_access_token, rrule_for_repeat, wait_for_code,
95 parse_calendar_list, parse_google_events, refresh_access_token, rrule_for_repeat, wait_for_code,
90 96 };
91 97 pub use language_settings::{
92 98 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
@@ -3,8 +3,10 @@ pub mod activity_mentions;
3pub mod ams;
3pub mod ams;
4pub mod bot_profiles;
4pub mod bot_profiles;
5pub mod calendar;
5pub mod calendar;
6pub mod caldav;
6pub mod calllog;
7pub mod calllog;
7pub mod cards;
8pub mod cards;
9pub mod ical;
8pub mod channel_notifications;
10pub mod channel_notifications;
9pub mod channel_visibility;
11pub mod channel_visibility;
10pub mod chat_listing;
12pub mod chat_listing;
@@ -58,11 +60,16 @@ pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};
58pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
60pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
59pub use calendar::{
61pub use calendar::{
60 Attendee, AttendeeResponseCounts, BusyTime, Calendar, CalendarEvent, CalendarSource,
62 Attendee, AttendeeResponseCounts, BusyTime, Calendar, CalendarEvent, CalendarSource,
61 CreatedEvent, DialIn, EventAttendee, NewEvent, PersonSchedule, Reminder, Repeat, Reply,
63 CreatedEvent, DialIn, EventAttendee, HomeCalendar, NewEvent, PersonSchedule, Reminder, Repeat,
62 ResponseType, ShowAs, apply_event_details, join_info_text, meet_now_join_url, new_event_body,
64 Reply, ResponseType, ShowAs, apply_event_details, join_info_text, meet_now_join_url,
63 new_event_body_with_join, parse_calendar_events, parse_created_event, strip_html,
65 merge_calendar_events, new_event_body, new_event_body_with_join, normalize_join_url,
64 truncate_preview,
66 parse_calendar_events, parse_created_event, strip_html, truncate_preview,
65};
67};
68pub use caldav::{
69 CalDavClient, CalDavEvent, ListedCalendar, discover as discover_caldav, new_event_uid,
70 partstat_for_reply,
71};
72pub use ical::{CalDavEventDraft, build_vevent, expand_events, parse_calendar, teams_join_url};
66pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
73pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
67pub use cards::{
74pub use cards::{
68 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
75 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
@@ -85,8 +92,7 @@ pub use gifs::{Gif, Gifs};
85pub use google_calendar::{
92pub use google_calendar::{
86 AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
93 AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
87 client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,
94 client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,
88 merge_calendar_events, normalize_join_url, parse_calendar_list, parse_google_events,
95 parse_calendar_list, parse_google_events, refresh_access_token, rrule_for_repeat, wait_for_code,
89 refresh_access_token, rrule_for_repeat, wait_for_code,
90};
96};
91pub use language_settings::{
97pub use language_settings::{
92 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
98 LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
crates/store/src/calendar_accounts.rs +171 −9
@@ -12,6 +12,7 @@ pub enum CalendarProvider {
12 12 #[default]
13 13 Outlook,
14 14 Google,
15 CalDav,
15 16 }
16 17
17 18 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -20,7 +21,7 @@ pub struct CalendarRef {
20 21 /// Stable account id (empty for the single Outlook mailbox).
21 22 #[serde(default)]
22 23 pub account_id: String,
23 /// Provider calendar id (`primary` for Google default, empty for Outlook).
24 /// Provider calendar id (`primary` for Google default, empty for Outlook, href for CalDAV).
24 25 #[serde(default)]
25 26 pub calendar_id: String,
26 27 }
@@ -42,12 +43,21 @@ impl CalendarRef {
42 43 }
43 44 }
44 45
46 pub fn caldav(account_id: impl Into<String>, calendar_id: impl Into<String>) -> Self {
47 CalendarRef {
48 provider: CalendarProvider::CalDav,
49 account_id: account_id.into(),
50 calendar_id: calendar_id.into(),
51 }
52 }
53
45 54 pub fn key(&self) -> String {
46 55 format!(
47 56 "{}:{}:{}",
48 57 match self.provider {
49 58 CalendarProvider::Outlook => "outlook",
50 59 CalendarProvider::Google => "google",
60 CalendarProvider::CalDav => "caldav",
51 61 },
52 62 self.account_id,
53 63 self.calendar_id
@@ -91,11 +101,50 @@ pub struct GoogleAccount {
91 101 pub tokens: GoogleTokenSet,
92 102 }
93 103
104 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105 pub struct CalDavCalendarInfo {
106 /// Collection href (calendar id).
107 pub id: String,
108 pub summary: String,
109 #[serde(default = "default_true")]
110 pub selected: bool,
111 #[serde(default)]
112 pub writable: bool,
113 #[serde(default)]
114 pub color: Option<String>,
115 }
116
117 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118 pub struct CalDavAccount {
119 pub id: String,
120 /// Normalized base URL without userinfo.
121 pub url: String,
122 pub username: String,
123 #[serde(default)]
124 pub display_name: String,
125 #[serde(default)]
126 pub calendars: Vec<CalDavCalendarInfo>,
127 /// mailto: addresses from calendar-user-address-set.
128 #[serde(default)]
129 pub user_addresses: Vec<String>,
130 #[serde(default)]
131 pub schedule_outbox: Option<String>,
132 }
133
134 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135 pub struct IcsSubscription {
136 pub id: String,
137 pub url: String,
138 pub summary: String,
139 #[serde(default = "default_true")]
140 pub selected: bool,
141 }
142
94 143 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95 144 pub struct CalendarAccounts {
96 145 #[serde(default = "CalendarRef::outlook")]
97 146 pub home: CalendarRef,
98 /// Extra write targets beyond home (may include Google calendars).
147 /// Extra write targets beyond home (may include Google / CalDAV calendars).
99 148 #[serde(default)]
100 149 pub write_targets: Vec<CalendarRef>,
101 150 /// Show Outlook mailbox events in the calendar grid.
@@ -103,6 +152,10 @@ pub struct CalendarAccounts {
103 152 pub outlook_selected: bool,
104 153 #[serde(default)]
105 154 pub google_accounts: Vec<GoogleAccount>,
155 #[serde(default)]
156 pub caldav_accounts: Vec<CalDavAccount>,
157 #[serde(default)]
158 pub ics_subscriptions: Vec<IcsSubscription>,
106 159 }
107 160
108 161 impl Default for CalendarAccounts {
@@ -112,6 +165,8 @@ impl Default for CalendarAccounts {
112 165 write_targets: Vec::new(),
113 166 outlook_selected: true,
114 167 google_accounts: Vec::new(),
168 caldav_accounts: Vec::new(),
169 ics_subscriptions: Vec::new(),
115 170 }
116 171 }
117 172 }
@@ -129,6 +184,14 @@ impl CalendarAccounts {
129 184 !self.google_accounts.is_empty()
130 185 }
131 186
187 pub fn has_caldav(&self) -> bool {
188 !self.caldav_accounts.is_empty()
189 }
190
191 pub fn has_ics(&self) -> bool {
192 !self.ics_subscriptions.is_empty()
193 }
194
132 195 pub fn google_account(&self, id: &str) -> Option<&GoogleAccount> {
133 196 self.google_accounts.iter().find(|account| account.id == id)
134 197 }
@@ -139,15 +202,39 @@ impl CalendarAccounts {
139 202 .find(|account| account.id == id)
140 203 }
141 204
205 pub fn caldav_account(&self, id: &str) -> Option<&CalDavAccount> {
206 self.caldav_accounts.iter().find(|account| account.id == id)
207 }
208
209 pub fn caldav_account_mut(&mut self, id: &str) -> Option<&mut CalDavAccount> {
210 self.caldav_accounts
211 .iter_mut()
212 .find(|account| account.id == id)
213 }
214
142 215 pub fn disconnect_google(&mut self, account_id: &str) {
143 216 self.google_accounts
144 217 .retain(|account| account.id != account_id);
145 if self.home.provider == CalendarProvider::Google && self.home.account_id == account_id {
218 self.clear_refs_for(CalendarProvider::Google, account_id);
219 }
220
221 pub fn disconnect_caldav(&mut self, account_id: &str) {
222 self.caldav_accounts
223 .retain(|account| account.id != account_id);
224 self.clear_refs_for(CalendarProvider::CalDav, account_id);
225 }
226
227 pub fn disconnect_ics(&mut self, subscription_id: &str) {
228 self.ics_subscriptions
229 .retain(|subscription| subscription.id != subscription_id);
230 }
231
232 fn clear_refs_for(&mut self, provider: CalendarProvider, account_id: &str) {
233 if self.home.provider == provider && self.home.account_id == account_id {
146 234 self.home = CalendarRef::outlook();
147 235 }
148 self.write_targets.retain(|target| {
149 !(target.provider == CalendarProvider::Google && target.account_id == account_id)
150 });
236 self.write_targets
237 .retain(|target| !(target.provider == provider && target.account_id == account_id));
151 238 }
152 239
153 240 /// Home plus extra write targets, de-duplicated by key.
@@ -200,6 +287,40 @@ pub fn merge_google_tokens(store: &Store, fetched: &CalendarAccounts) -> Result<
200 287 Ok(())
201 288 }
202 289
290 /// Keep CalDAV metadata that a fetch refreshed without clobbering toggles.
291 pub fn merge_caldav_metadata(store: &Store, fetched: &CalendarAccounts) -> Result<()> {
292 let mut current = load_calendar_accounts(store);
293 let mut changed = false;
294 for account in &mut current.caldav_accounts {
295 if let Some(fresh) = fetched.caldav_account(&account.id) {
296 if fresh.user_addresses != account.user_addresses {
297 account.user_addresses = fresh.user_addresses.clone();
298 changed = true;
299 }
300 if fresh.schedule_outbox != account.schedule_outbox {
301 account.schedule_outbox = fresh.schedule_outbox.clone();
302 changed = true;
303 }
304 for calendar in &mut account.calendars {
305 if let Some(fresh_cal) = fresh.calendars.iter().find(|c| c.id == calendar.id)
306 && (fresh_cal.summary != calendar.summary
307 || fresh_cal.writable != calendar.writable
308 || fresh_cal.color != calendar.color)
309 {
310 calendar.summary = fresh_cal.summary.clone();
311 calendar.writable = fresh_cal.writable;
312 calendar.color = fresh_cal.color.clone();
313 changed = true;
314 }
315 }
316 }
317 }
318 if changed {
319 save_calendar_accounts(store, &current)?;
320 }
321 Ok(())
322 }
323
203 324 #[cfg(test)]
204 325 mod tests {
205 326 use super::*;
@@ -212,6 +333,7 @@ mod tests {
212 333 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
213 334 assert!(accounts.write_targets.is_empty());
214 335 assert!(!accounts.has_google());
336 assert!(!accounts.has_caldav());
215 337 }
216 338
217 339 #[test]
@@ -234,12 +356,28 @@ mod tests {
234 356 expires_at: 1,
235 357 },
236 358 });
237 accounts.home = CalendarRef::google("g1", "primary");
359 accounts.caldav_accounts.push(CalDavAccount {
360 id: "c1".into(),
361 url: "https://cloud.example/remote.php/dav/".into(),
362 username: "joe".into(),
363 display_name: "Nextcloud".into(),
364 calendars: vec![CalDavCalendarInfo {
365 id: "/calendars/joe/personal/".into(),
366 summary: "Personal".into(),
367 selected: true,
368 writable: true,
369 color: None,
370 }],
371 user_addresses: vec!["mailto:joe@example.com".into()],
372 schedule_outbox: None,
373 });
374 accounts.home = CalendarRef::caldav("c1", "/calendars/joe/personal/");
238 375 accounts.write_targets.push(CalendarRef::outlook());
239 376 save_calendar_accounts(&store, &accounts).unwrap();
240 377 let loaded = load_calendar_accounts(&store);
241 378 assert_eq!(loaded.home, accounts.home);
242 379 assert_eq!(loaded.google_accounts[0].email, "joe@example.com");
380 assert_eq!(loaded.caldav_accounts[0].username, "joe");
243 381 assert_eq!(loaded.resolved_write_targets().len(), 2);
244 382 }
245 383
@@ -255,6 +393,8 @@ mod tests {
255 393 calendars: Vec::new(),
256 394 tokens: GoogleTokenSet::default(),
257 395 }],
396 caldav_accounts: Vec::new(),
397 ics_subscriptions: Vec::new(),
258 398 };
259 399 accounts.disconnect_google("g1");
260 400 assert!(!accounts.has_google());
@@ -262,6 +402,30 @@ mod tests {
262 402 assert!(accounts.write_targets.is_empty());
263 403 }
264 404
405 #[test]
406 fn disconnect_caldav_clears_refs() {
407 let mut accounts = CalendarAccounts {
408 home: CalendarRef::caldav("c1", "/cal/"),
409 write_targets: vec![CalendarRef::caldav("c1", "/cal/")],
410 outlook_selected: true,
411 google_accounts: Vec::new(),
412 caldav_accounts: vec![CalDavAccount {
413 id: "c1".into(),
414 url: "https://example/dav/".into(),
415 username: "u".into(),
416 display_name: String::new(),
417 calendars: Vec::new(),
418 user_addresses: Vec::new(),
419 schedule_outbox: None,
420 }],
421 ics_subscriptions: Vec::new(),
422 };
423 accounts.disconnect_caldav("c1");
424 assert!(!accounts.has_caldav());
425 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
426 assert!(accounts.write_targets.is_empty());
427 }
428
265 429 #[test]
266 430 fn token_merge_keeps_a_toggle_made_during_the_fetch() {
267 431 let directory = tempdir().unwrap();
@@ -279,10 +443,8 @@ mod tests {
279 443 tokens: GoogleTokenSet::default(),
280 444 });
281 445 save_calendar_accounts(&store, &stored).unwrap();
282 // The fetch starts from this copy and refreshes the token.
283 446 let mut fetched = load_calendar_accounts(&store);
284 447 fetched.google_accounts[0].tokens.access_token = "fresh".into();
285 // Meanwhile the user turns the calendar off and Outlook off.
286 448 stored.google_accounts[0].calendars[0].selected = false;
287 449 stored.outlook_selected = false;
288 450 save_calendar_accounts(&store, &stored).unwrap();
@@ -12,6 +12,7 @@ pub enum CalendarProvider {
12 #[default]
12 #[default]
13 Outlook,
13 Outlook,
14 Google,
14 Google,
15 CalDav,
15}
16}
16
17
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -20,7 +21,7 @@ pub struct CalendarRef {
20 /// Stable account id (empty for the single Outlook mailbox).
21 /// Stable account id (empty for the single Outlook mailbox).
21 #[serde(default)]
22 #[serde(default)]
22 pub account_id: String,
23 pub account_id: String,
23 /// Provider calendar id (`primary` for Google default, empty for Outlook).
24 /// Provider calendar id (`primary` for Google default, empty for Outlook, href for CalDAV).
24 #[serde(default)]
25 #[serde(default)]
25 pub calendar_id: String,
26 pub calendar_id: String,
26}
27}
@@ -42,12 +43,21 @@ impl CalendarRef {
42 }
43 }
43 }
44 }
44
45
46 pub fn caldav(account_id: impl Into<String>, calendar_id: impl Into<String>) -> Self {
47 CalendarRef {
48 provider: CalendarProvider::CalDav,
49 account_id: account_id.into(),
50 calendar_id: calendar_id.into(),
51 }
52 }
53
45 pub fn key(&self) -> String {
54 pub fn key(&self) -> String {
46 format!(
55 format!(
47 "{}:{}:{}",
56 "{}:{}:{}",
48 match self.provider {
57 match self.provider {
49 CalendarProvider::Outlook => "outlook",
58 CalendarProvider::Outlook => "outlook",
50 CalendarProvider::Google => "google",
59 CalendarProvider::Google => "google",
60 CalendarProvider::CalDav => "caldav",
51 },
61 },
52 self.account_id,
62 self.account_id,
53 self.calendar_id
63 self.calendar_id
@@ -91,11 +101,50 @@ pub struct GoogleAccount {
91 pub tokens: GoogleTokenSet,
101 pub tokens: GoogleTokenSet,
92}
102}
93
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105pub struct CalDavCalendarInfo {
106 /// Collection href (calendar id).
107 pub id: String,
108 pub summary: String,
109 #[serde(default = "default_true")]
110 pub selected: bool,
111 #[serde(default)]
112 pub writable: bool,
113 #[serde(default)]
114 pub color: Option<String>,
115}
116
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118pub struct CalDavAccount {
119 pub id: String,
120 /// Normalized base URL without userinfo.
121 pub url: String,
122 pub username: String,
123 #[serde(default)]
124 pub display_name: String,
125 #[serde(default)]
126 pub calendars: Vec<CalDavCalendarInfo>,
127 /// mailto: addresses from calendar-user-address-set.
128 #[serde(default)]
129 pub user_addresses: Vec<String>,
130 #[serde(default)]
131 pub schedule_outbox: Option<String>,
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135pub struct IcsSubscription {
136 pub id: String,
137 pub url: String,
138 pub summary: String,
139 #[serde(default = "default_true")]
140 pub selected: bool,
141}
142
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct CalendarAccounts {
144pub struct CalendarAccounts {
96 #[serde(default = "CalendarRef::outlook")]
145 #[serde(default = "CalendarRef::outlook")]
97 pub home: CalendarRef,
146 pub home: CalendarRef,
98 /// Extra write targets beyond home (may include Google calendars).
147 /// Extra write targets beyond home (may include Google / CalDAV calendars).
99 #[serde(default)]
148 #[serde(default)]
100 pub write_targets: Vec<CalendarRef>,
149 pub write_targets: Vec<CalendarRef>,
101 /// Show Outlook mailbox events in the calendar grid.
150 /// Show Outlook mailbox events in the calendar grid.
@@ -103,6 +152,10 @@ pub struct CalendarAccounts {
103 pub outlook_selected: bool,
152 pub outlook_selected: bool,
104 #[serde(default)]
153 #[serde(default)]
105 pub google_accounts: Vec<GoogleAccount>,
154 pub google_accounts: Vec<GoogleAccount>,
155 #[serde(default)]
156 pub caldav_accounts: Vec<CalDavAccount>,
157 #[serde(default)]
158 pub ics_subscriptions: Vec<IcsSubscription>,
106}
159}
107
160
108impl Default for CalendarAccounts {
161impl Default for CalendarAccounts {
@@ -112,6 +165,8 @@ impl Default for CalendarAccounts {
112 write_targets: Vec::new(),
165 write_targets: Vec::new(),
113 outlook_selected: true,
166 outlook_selected: true,
114 google_accounts: Vec::new(),
167 google_accounts: Vec::new(),
168 caldav_accounts: Vec::new(),
169 ics_subscriptions: Vec::new(),
115 }
170 }
116 }
171 }
117}
172}
@@ -129,6 +184,14 @@ impl CalendarAccounts {
129 !self.google_accounts.is_empty()
184 !self.google_accounts.is_empty()
130 }
185 }
131
186
187 pub fn has_caldav(&self) -> bool {
188 !self.caldav_accounts.is_empty()
189 }
190
191 pub fn has_ics(&self) -> bool {
192 !self.ics_subscriptions.is_empty()
193 }
194
132 pub fn google_account(&self, id: &str) -> Option<&GoogleAccount> {
195 pub fn google_account(&self, id: &str) -> Option<&GoogleAccount> {
133 self.google_accounts.iter().find(|account| account.id == id)
196 self.google_accounts.iter().find(|account| account.id == id)
134 }
197 }
@@ -139,15 +202,39 @@ impl CalendarAccounts {
139 .find(|account| account.id == id)
202 .find(|account| account.id == id)
140 }
203 }
141
204
205 pub fn caldav_account(&self, id: &str) -> Option<&CalDavAccount> {
206 self.caldav_accounts.iter().find(|account| account.id == id)
207 }
208
209 pub fn caldav_account_mut(&mut self, id: &str) -> Option<&mut CalDavAccount> {
210 self.caldav_accounts
211 .iter_mut()
212 .find(|account| account.id == id)
213 }
214
142 pub fn disconnect_google(&mut self, account_id: &str) {
215 pub fn disconnect_google(&mut self, account_id: &str) {
143 self.google_accounts
216 self.google_accounts
144 .retain(|account| account.id != account_id);
217 .retain(|account| account.id != account_id);
145 if self.home.provider == CalendarProvider::Google && self.home.account_id == account_id {
218 self.clear_refs_for(CalendarProvider::Google, account_id);
219 }
220
221 pub fn disconnect_caldav(&mut self, account_id: &str) {
222 self.caldav_accounts
223 .retain(|account| account.id != account_id);
224 self.clear_refs_for(CalendarProvider::CalDav, account_id);
225 }
226
227 pub fn disconnect_ics(&mut self, subscription_id: &str) {
228 self.ics_subscriptions
229 .retain(|subscription| subscription.id != subscription_id);
230 }
231
232 fn clear_refs_for(&mut self, provider: CalendarProvider, account_id: &str) {
233 if self.home.provider == provider && self.home.account_id == account_id {
146 self.home = CalendarRef::outlook();
234 self.home = CalendarRef::outlook();
147 }
235 }
148 self.write_targets.retain(|target| {
236 self.write_targets
149 !(target.provider == CalendarProvider::Google && target.account_id == account_id)
237 .retain(|target| !(target.provider == provider && target.account_id == account_id));
150 });
151 }
238 }
152
239
153 /// Home plus extra write targets, de-duplicated by key.
240 /// Home plus extra write targets, de-duplicated by key.
@@ -200,6 +287,40 @@ pub fn merge_google_tokens(store: &Store, fetched: &CalendarAccounts) -> Result<
200 Ok(())
287 Ok(())
201}
288}
202
289
290/// Keep CalDAV metadata that a fetch refreshed without clobbering toggles.
291pub fn merge_caldav_metadata(store: &Store, fetched: &CalendarAccounts) -> Result<()> {
292 let mut current = load_calendar_accounts(store);
293 let mut changed = false;
294 for account in &mut current.caldav_accounts {
295 if let Some(fresh) = fetched.caldav_account(&account.id) {
296 if fresh.user_addresses != account.user_addresses {
297 account.user_addresses = fresh.user_addresses.clone();
298 changed = true;
299 }
300 if fresh.schedule_outbox != account.schedule_outbox {
301 account.schedule_outbox = fresh.schedule_outbox.clone();
302 changed = true;
303 }
304 for calendar in &mut account.calendars {
305 if let Some(fresh_cal) = fresh.calendars.iter().find(|c| c.id == calendar.id)
306 && (fresh_cal.summary != calendar.summary
307 || fresh_cal.writable != calendar.writable
308 || fresh_cal.color != calendar.color)
309 {
310 calendar.summary = fresh_cal.summary.clone();
311 calendar.writable = fresh_cal.writable;
312 calendar.color = fresh_cal.color.clone();
313 changed = true;
314 }
315 }
316 }
317 }
318 if changed {
319 save_calendar_accounts(store, &current)?;
320 }
321 Ok(())
322}
323
203#[cfg(test)]
324#[cfg(test)]
204mod tests {
325mod tests {
205 use super::*;
326 use super::*;
@@ -212,6 +333,7 @@ mod tests {
212 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
333 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
213 assert!(accounts.write_targets.is_empty());
334 assert!(accounts.write_targets.is_empty());
214 assert!(!accounts.has_google());
335 assert!(!accounts.has_google());
336 assert!(!accounts.has_caldav());
215 }
337 }
216
338
217 #[test]
339 #[test]
@@ -234,12 +356,28 @@ mod tests {
234 expires_at: 1,
356 expires_at: 1,
235 },
357 },
236 });
358 });
237 accounts.home = CalendarRef::google("g1", "primary");
359 accounts.caldav_accounts.push(CalDavAccount {
360 id: "c1".into(),
361 url: "https://cloud.example/remote.php/dav/".into(),
362 username: "joe".into(),
363 display_name: "Nextcloud".into(),
364 calendars: vec![CalDavCalendarInfo {
365 id: "/calendars/joe/personal/".into(),
366 summary: "Personal".into(),
367 selected: true,
368 writable: true,
369 color: None,
370 }],
371 user_addresses: vec!["mailto:joe@example.com".into()],
372 schedule_outbox: None,
373 });
374 accounts.home = CalendarRef::caldav("c1", "/calendars/joe/personal/");
238 accounts.write_targets.push(CalendarRef::outlook());
375 accounts.write_targets.push(CalendarRef::outlook());
239 save_calendar_accounts(&store, &accounts).unwrap();
376 save_calendar_accounts(&store, &accounts).unwrap();
240 let loaded = load_calendar_accounts(&store);
377 let loaded = load_calendar_accounts(&store);
241 assert_eq!(loaded.home, accounts.home);
378 assert_eq!(loaded.home, accounts.home);
242 assert_eq!(loaded.google_accounts[0].email, "joe@example.com");
379 assert_eq!(loaded.google_accounts[0].email, "joe@example.com");
380 assert_eq!(loaded.caldav_accounts[0].username, "joe");
243 assert_eq!(loaded.resolved_write_targets().len(), 2);
381 assert_eq!(loaded.resolved_write_targets().len(), 2);
244 }
382 }
245
383
@@ -255,6 +393,8 @@ mod tests {
255 calendars: Vec::new(),
393 calendars: Vec::new(),
256 tokens: GoogleTokenSet::default(),
394 tokens: GoogleTokenSet::default(),
257 }],
395 }],
396 caldav_accounts: Vec::new(),
397 ics_subscriptions: Vec::new(),
258 };
398 };
259 accounts.disconnect_google("g1");
399 accounts.disconnect_google("g1");
260 assert!(!accounts.has_google());
400 assert!(!accounts.has_google());
@@ -262,6 +402,30 @@ mod tests {
262 assert!(accounts.write_targets.is_empty());
402 assert!(accounts.write_targets.is_empty());
263 }
403 }
264
404
405 #[test]
406 fn disconnect_caldav_clears_refs() {
407 let mut accounts = CalendarAccounts {
408 home: CalendarRef::caldav("c1", "/cal/"),
409 write_targets: vec![CalendarRef::caldav("c1", "/cal/")],
410 outlook_selected: true,
411 google_accounts: Vec::new(),
412 caldav_accounts: vec![CalDavAccount {
413 id: "c1".into(),
414 url: "https://example/dav/".into(),
415 username: "u".into(),
416 display_name: String::new(),
417 calendars: Vec::new(),
418 user_addresses: Vec::new(),
419 schedule_outbox: None,
420 }],
421 ics_subscriptions: Vec::new(),
422 };
423 accounts.disconnect_caldav("c1");
424 assert!(!accounts.has_caldav());
425 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
426 assert!(accounts.write_targets.is_empty());
427 }
428
265 #[test]
429 #[test]
266 fn token_merge_keeps_a_toggle_made_during_the_fetch() {
430 fn token_merge_keeps_a_toggle_made_during_the_fetch() {
267 let directory = tempdir().unwrap();
431 let directory = tempdir().unwrap();
@@ -279,10 +443,8 @@ mod tests {
279 tokens: GoogleTokenSet::default(),
443 tokens: GoogleTokenSet::default(),
280 });
444 });
281 save_calendar_accounts(&store, &stored).unwrap();
445 save_calendar_accounts(&store, &stored).unwrap();
282 // The fetch starts from this copy and refreshes the token.
283 let mut fetched = load_calendar_accounts(&store);
446 let mut fetched = load_calendar_accounts(&store);
284 fetched.google_accounts[0].tokens.access_token = "fresh".into();
447 fetched.google_accounts[0].tokens.access_token = "fresh".into();
285 // Meanwhile the user turns the calendar off and Outlook off.
286 stored.google_accounts[0].calendars[0].selected = false;
448 stored.google_accounts[0].calendars[0].selected = false;
287 stored.outlook_selected = false;
449 stored.outlook_selected = false;
288 save_calendar_accounts(&store, &stored).unwrap();
450 save_calendar_accounts(&store, &stored).unwrap();
crates/store/src/lib.rs +3 −3
@@ -26,9 +26,9 @@ mod text;
26 26 mod time;
27 27
28 28 pub use calendar_accounts::{
29 CALENDAR_ACCOUNTS_KEY, CalendarAccounts, CalendarProvider, CalendarRef, GoogleAccount,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, merge_google_tokens,
31 save_calendar_accounts,
29 CALENDAR_ACCOUNTS_KEY, CalDavAccount, CalDavCalendarInfo, CalendarAccounts, CalendarProvider,
30 CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet, IcsSubscription,
31 load_calendar_accounts, merge_caldav_metadata, merge_google_tokens, save_calendar_accounts,
32 32 };
33 33 pub use error::{Error, Result};
34 34 pub use image_files::ImageFileCache;
@@ -26,9 +26,9 @@ mod text;
26mod time;
26mod time;
27
27
28pub use calendar_accounts::{
28pub use calendar_accounts::{
29 CALENDAR_ACCOUNTS_KEY, CalendarAccounts, CalendarProvider, CalendarRef, GoogleAccount,
29 CALENDAR_ACCOUNTS_KEY, CalDavAccount, CalDavCalendarInfo, CalendarAccounts, CalendarProvider,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, merge_google_tokens,
30 CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet, IcsSubscription,
31 save_calendar_accounts,
31 load_calendar_accounts, merge_caldav_metadata, merge_google_tokens, save_calendar_accounts,
32};
32};
33pub use error::{Error, Result};
33pub use error::{Error, Result};
34pub use image_files::ImageFileCache;
34pub use image_files::ImageFileCache;
docs/decisions/0019-caldav-app-password-and-keyring.md added +27 −0
@@ -0,0 +1,27 @@
1 ---
2 status: accepted
3 date: 2026-11-16
4 ---
5
6 # ADR 0019: CalDAV with app password and OS keyring
7
8 ## Context
9
10 The next optional calendar after Google is CalDAV (Nextcloud, Fastmail, mailbox.org, Posteo, iCloud, Synology, Radicale). Per-provider OAuth would repeat Google Cloud work for every host. App passwords are how Thunderbird and DAVx⁵ already connect. Google OAuth tokens already sit in SQLite meta; an app password is long-lived and often unlocks mail as well as calendar.
11
12 Options were: OAuth per host, app password in SQLite like Google tokens, or app password in the OS keyring with metadata in SQLite.
13
14 ## Decision
15
16 Connect CalDAV with server URL, username, and app password (Basic auth). Credentials stay on the device. The app password lives in the OS keyring (Secret Service, Keychain, Credential Manager). SQLite keeps URL, username, calendar list, and selection only. Diagnostics and support bundles redact URL userinfo, username, and password.
17
18 RSVP updates the local `PARTSTAT` when the user is an attendee. The UI treats the response as delivered to organizers only when the server advertises scheduling (RFC 6638 schedule-outbox). One write target sends invitations: Outlook when it is among the targets, otherwise CalDAV alone.
19
20 Digest auth (Baïkal default) is unsupported; the connect error says so. HTTPS must not downgrade to HTTP on redirect. TLS uses the system trust store; there is no «ignore certificate» switch.
21
22 ## Consequences
23
24 - One client covers self-hosted and hosted CalDAV without a project OAuth app per provider.
25 - Flatpak needs `org.freedesktop.secrets`; packaging must request it.
26 - Users must create an app password (or enable Basic) on the server.
27 - Proton Calendar and Tuta remain outside this path (no CalDAV); read-only ICS is a later change.
@@ -0,0 +1,27 @@
1---
2status: accepted
3date: 2026-11-16
4---
5
6# ADR 0019: CalDAV with app password and OS keyring
7
8## Context
9
10The next optional calendar after Google is CalDAV (Nextcloud, Fastmail, mailbox.org, Posteo, iCloud, Synology, Radicale). Per-provider OAuth would repeat Google Cloud work for every host. App passwords are how Thunderbird and DAVx⁵ already connect. Google OAuth tokens already sit in SQLite meta; an app password is long-lived and often unlocks mail as well as calendar.
11
12Options were: OAuth per host, app password in SQLite like Google tokens, or app password in the OS keyring with metadata in SQLite.
13
14## Decision
15
16Connect CalDAV with server URL, username, and app password (Basic auth). Credentials stay on the device. The app password lives in the OS keyring (Secret Service, Keychain, Credential Manager). SQLite keeps URL, username, calendar list, and selection only. Diagnostics and support bundles redact URL userinfo, username, and password.
17
18RSVP updates the local `PARTSTAT` when the user is an attendee. The UI treats the response as delivered to organizers only when the server advertises scheduling (RFC 6638 schedule-outbox). One write target sends invitations: Outlook when it is among the targets, otherwise CalDAV alone.
19
20Digest auth (Baïkal default) is unsupported; the connect error says so. HTTPS must not downgrade to HTTP on redirect. TLS uses the system trust store; there is no «ignore certificate» switch.
21
22## Consequences
23
24- One client covers self-hosted and hosted CalDAV without a project OAuth app per provider.
25- Flatpak needs `org.freedesktop.secrets`; packaging must request it.
26- Users must create an app password (or enable Basic) on the server.
27- Proton Calendar and Tuta remain outside this path (no CalDAV); read-only ICS is a later change.
docs/decisions/README.md +2 −1
@@ -34,5 +34,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
34 34 | [0016](0016-calendar-week-start-and-time-scale-stay-local.md) | Calendar work hours go to the mailbox, week start and time scale stay local |
35 35 | [0017](0017-guest-orgs-switch-by-restart.md) | Guest orgs, one org per window, switch by restart |
36 36 | [0018](0018-regional-format-is-separate-from-the-app-language.md) | Regional format is separate from the app language |
37 | [0019](0019-caldav-app-password-and-keyring.md) | CalDAV with app password and OS keyring |
37 38
38 Records `0001` to `0018` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
39 Records `0001` to `0019` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -34,5 +34,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
34| [0016](0016-calendar-week-start-and-time-scale-stay-local.md) | Calendar work hours go to the mailbox, week start and time scale stay local |
34| [0016](0016-calendar-week-start-and-time-scale-stay-local.md) | Calendar work hours go to the mailbox, week start and time scale stay local |
35| [0017](0017-guest-orgs-switch-by-restart.md) | Guest orgs, one org per window, switch by restart |
35| [0017](0017-guest-orgs-switch-by-restart.md) | Guest orgs, one org per window, switch by restart |
36| [0018](0018-regional-format-is-separate-from-the-app-language.md) | Regional format is separate from the app language |
36| [0018](0018-regional-format-is-separate-from-the-app-language.md) | Regional format is separate from the app language |
37| [0019](0019-caldav-app-password-and-keyring.md) | CalDAV with app password and OS keyring |
37
38
38Records `0001` to `0018` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
39Records `0001` to `0019` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.