Merge pull request #56: feat(calendar): CalDAV accounts, ICS subscriptions, settings layout
@@ -23,7 +23,7 @@ dependencies = [
23
23
"atspi-common",
24
24
"phf 0.13.1",
25
25
"serde",
26
"zvariant",
26
"zvariant 5.15.0",
27
27
]
28
28
29
29
[[package]]
@@ -65,7 +65,7 @@ dependencies = [
65
65
"futures-lite",
66
66
"futures-util",
67
67
"serde",
68
"zbus",
68
"zbus 5.19.0",
69
69
]
70
70
71
71
[[package]]
@@ -340,7 +340,7 @@ dependencies = [
340
340
"tray-icon",
341
341
"windows 0.62.2",
342
342
"x11rb",
343
"zbus",
343
"zbus 5.19.0",
344
344
]
345
345
346
346
[[package]]
@@ -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
]
@@ -491,7 +494,7 @@ dependencies = [
491
494
"wayland-backend",
492
495
"wayland-client",
493
496
"wayland-protocols",
494
"zbus",
497
"zbus 5.19.0",
495
498
]
496
499
497
500
[[package]]
@@ -713,11 +716,11 @@ dependencies = [
713
716
"enumflags2",
714
717
"serde",
715
718
"static_assertions",
716
"zbus",
719
"zbus 5.19.0",
717
720
"zbus-lockstep",
718
721
"zbus-lockstep-macros",
719
"zbus_names",
720
"zvariant",
722
"zbus_names 4.3.4",
723
"zvariant 5.15.0",
721
724
]
722
725
723
726
[[package]]
@@ -728,7 +731,7 @@ checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc"
728
731
dependencies = [
729
732
"atspi-common",
730
733
"serde",
731
"zbus",
734
"zbus 5.19.0",
732
735
]
733
736
734
737
[[package]]
@@ -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"
@@ -2182,6 +2198,35 @@ version = "0.3.2"
2182
2198
source = "registry+https://github.com/rust-lang/crates.io-index"
2183
2199
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
2184
2200
2201
[[package]]
2202
name = "dbus"
2203
version = "0.9.11"
2204
source = "registry+https://github.com/rust-lang/crates.io-index"
2205
checksum = "b942602992bb7acfd1f51c49811c58a610ef9181b6e66f3e519d79b540a3bf73"
2206
dependencies = [
2207
"libc",
2208
"libdbus-sys",
2209
"windows-sys 0.61.2",
2210
]
2211
2212
[[package]]
2213
name = "dbus-secret-service"
2214
version = "4.1.0"
2215
source = "registry+https://github.com/rust-lang/crates.io-index"
2216
checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"
2217
dependencies = [
2218
"aes",
2219
"block-padding",
2220
"cbc",
2221
"dbus",
2222
"fastrand",
2223
"hkdf",
2224
"num",
2225
"once_cell",
2226
"sha2 0.10.9",
2227
"zeroize",
2228
]
2229
2185
2230
[[package]]
2186
2231
name = "deep_filter"
2187
2232
version = "0.5.7-pre"
@@ -5004,6 +5049,23 @@ dependencies = [
5004
5049
"unicode-segmentation",
5005
5050
]
5006
5051
5052
[[package]]
5053
name = "keyring"
5054
version = "3.6.3"
5055
source = "registry+https://github.com/rust-lang/crates.io-index"
5056
checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
5057
dependencies = [
5058
"byteorder",
5059
"dbus-secret-service",
5060
"log",
5061
"secret-service",
5062
"security-framework 2.11.1",
5063
"security-framework 3.7.0",
5064
"windows-sys 0.60.2",
5065
"zbus 4.4.0",
5066
"zeroize",
5067
]
5068
5007
5069
[[package]]
5008
5070
name = "khronos-egl"
5009
5071
version = "6.0.0"
@@ -5053,7 +5115,7 @@ dependencies = [
5053
5115
"pastey 0.2.3",
5054
5116
"serde",
5055
5117
"tokio",
5056
"zbus",
5118
"zbus 5.19.0",
5057
5119
]
5058
5120
5059
5121
[[package]]
@@ -5148,6 +5210,15 @@ version = "0.2.190"
5148
5210
source = "registry+https://github.com/rust-lang/crates.io-index"
5149
5211
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
5150
5212
5213
[[package]]
5214
name = "libdbus-sys"
5215
version = "0.2.7"
5216
source = "registry+https://github.com/rust-lang/crates.io-index"
5217
checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"
5218
dependencies = [
5219
"pkg-config",
5220
]
5221
5151
5222
[[package]]
5152
5223
name = "libfuzzer-sys"
5153
5224
version = "0.4.13"
@@ -5796,6 +5867,19 @@ version = "1.0.6"
5796
5867
source = "registry+https://github.com/rust-lang/crates.io-index"
5797
5868
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
5798
5869
5870
[[package]]
5871
name = "nix"
5872
version = "0.29.0"
5873
source = "registry+https://github.com/rust-lang/crates.io-index"
5874
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
5875
dependencies = [
5876
"bitflags 2.13.2",
5877
"cfg-if 1.0.5",
5878
"cfg_aliases",
5879
"libc",
5880
"memoffset",
5881
]
5882
5799
5883
[[package]]
5800
5884
name = "no_std_io2"
5801
5885
version = "0.9.4"
@@ -5949,7 +6033,7 @@ dependencies = [
5949
6033
"mac-notification-sys",
5950
6034
"serde",
5951
6035
"tauri-winrt-notification",
5952
"zbus",
6036
"zbus 5.19.0",
5953
6037
]
5954
6038
5955
6039
[[package]]
@@ -6113,7 +6197,7 @@ version = "0.7.6"
6113
6197
source = "registry+https://github.com/rust-lang/crates.io-index"
6114
6198
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
6115
6199
dependencies = [
6116
"proc-macro-crate 3.5.0",
6200
"proc-macro-crate 1.3.1",
6117
6201
"proc-macro2",
6118
6202
"quote",
6119
6203
"syn 2.0.119",
@@ -6569,10 +6653,10 @@ dependencies = [
6569
6653
"serde_bytes",
6570
6654
"sha2 0.10.9",
6571
6655
"subtle",
6572
"zbus",
6573
"zbus_macros",
6656
"zbus 5.19.0",
6657
"zbus_macros 5.19.0",
6574
6658
"zeroize",
6575
"zvariant",
6659
"zvariant 5.15.0",
6576
6660
]
6577
6661
6578
6662
[[package]]
@@ -6768,6 +6852,15 @@ dependencies = [
6768
6852
"phf_shared 0.11.3",
6769
6853
]
6770
6854
6855
[[package]]
6856
name = "phf"
6857
version = "0.12.1"
6858
source = "registry+https://github.com/rust-lang/crates.io-index"
6859
checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
6860
dependencies = [
6861
"phf_shared 0.12.1",
6862
]
6863
6771
6864
[[package]]
6772
6865
name = "phf"
6773
6866
version = "0.13.1"
@@ -6844,6 +6937,15 @@ dependencies = [
6844
6937
"siphasher",
6845
6938
]
6846
6939
6940
[[package]]
6941
name = "phf_shared"
6942
version = "0.12.1"
6943
source = "registry+https://github.com/rust-lang/crates.io-index"
6944
checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
6945
dependencies = [
6946
"siphasher",
6947
]
6948
6847
6949
[[package]]
6848
6950
name = "phf_shared"
6849
6951
version = "0.13.1"
@@ -7235,6 +7337,15 @@ version = "2.0.1"
7235
7337
source = "registry+https://github.com/rust-lang/crates.io-index"
7236
7338
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
7237
7339
7340
[[package]]
7341
name = "quick-xml"
7342
version = "0.37.5"
7343
source = "registry+https://github.com/rust-lang/crates.io-index"
7344
checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
7345
dependencies = [
7346
"memchr",
7347
]
7348
7238
7349
[[package]]
7239
7350
name = "quick-xml"
7240
7351
version = "0.41.0"
@@ -7884,6 +7995,19 @@ dependencies = [
7884
7995
"memchr",
7885
7996
]
7886
7997
7998
[[package]]
7999
name = "rrule"
8000
version = "0.14.0"
8001
source = "registry+https://github.com/rust-lang/crates.io-index"
8002
checksum = "720acfb4980b9d8a6a430f6d7a11933e701ebbeba5eee39cc9d8c5f932aaff74"
8003
dependencies = [
8004
"chrono",
8005
"chrono-tz",
8006
"log",
8007
"regex",
8008
"thiserror 2.0.21",
8009
]
8010
7887
8011
[[package]]
7888
8012
name = "rtrb"
7889
8013
version = "0.3.5"
@@ -8050,7 +8174,7 @@ dependencies = [
8050
8174
"errno",
8051
8175
"libc",
8052
8176
"linux-raw-sys 0.4.15",
8053
"windows-sys 0.52.0",
8177
"windows-sys 0.59.0",
8054
8178
]
8055
8179
8056
8180
[[package]]
@@ -8091,7 +8215,7 @@ dependencies = [
8091
8215
"openssl-probe",
8092
8216
"rustls-pki-types",
8093
8217
"schannel",
8094
"security-framework",
8218
"security-framework 3.7.0",
8095
8219
]
8096
8220
8097
8221
[[package]]
@@ -8128,7 +8252,7 @@ dependencies = [
8128
8252
"rustls-native-certs",
8129
8253
"rustls-platform-verifier-android",
8130
8254
"rustls-webpki",
8131
"security-framework",
8255
"security-framework 3.7.0",
8132
8256
"security-framework-sys",
8133
8257
"webpki-root-certs",
8134
8258
"windows-sys 0.61.2",
@@ -8301,6 +8425,38 @@ version = "4.1.0"
8301
8425
source = "registry+https://github.com/rust-lang/crates.io-index"
8302
8426
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
8303
8427
8428
[[package]]
8429
name = "secret-service"
8430
version = "4.0.0"
8431
source = "registry+https://github.com/rust-lang/crates.io-index"
8432
checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4"
8433
dependencies = [
8434
"aes",
8435
"cbc",
8436
"futures-util",
8437
"generic-array",
8438
"hkdf",
8439
"num",
8440
"once_cell",
8441
"rand 0.8.8",
8442
"serde",
8443
"sha2 0.10.9",
8444
"zbus 4.4.0",
8445
]
8446
8447
[[package]]
8448
name = "security-framework"
8449
version = "2.11.1"
8450
source = "registry+https://github.com/rust-lang/crates.io-index"
8451
checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
8452
dependencies = [
8453
"bitflags 2.13.2",
8454
"core-foundation 0.9.4",
8455
"core-foundation-sys 0.8.7",
8456
"libc",
8457
"security-framework-sys",
8458
]
8459
8304
8460
[[package]]
8305
8461
name = "security-framework"
8306
8462
version = "3.7.0"
@@ -9249,7 +9405,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
9249
9405
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
9250
9406
dependencies = [
9251
9407
"fastrand",
9252
"getrandom 0.4.3",
9408
"getrandom 0.3.4",
9253
9409
"once_cell",
9254
9410
"rustix 1.1.5",
9255
9411
"windows-sys 0.61.2",
@@ -10533,7 +10689,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
10533
10689
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
10534
10690
dependencies = [
10535
10691
"proc-macro2",
10536
"quick-xml",
10692
"quick-xml 0.41.0",
10537
10693
"quote",
10538
10694
]
10539
10695
@@ -10888,7 +11044,7 @@ version = "0.1.11"
10888
11044
source = "registry+https://github.com/rust-lang/crates.io-index"
10889
11045
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
10890
11046
dependencies = [
10891
"windows-sys 0.61.2",
11047
"windows-sys 0.48.0",
10892
11048
]
10893
11049
10894
11050
[[package]]
@@ -11266,6 +11422,15 @@ dependencies = [
11266
11422
"windows-targets 0.52.6",
11267
11423
]
11268
11424
11425
[[package]]
11426
name = "windows-sys"
11427
version = "0.59.0"
11428
source = "registry+https://github.com/rust-lang/crates.io-index"
11429
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
11430
dependencies = [
11431
"windows-targets 0.52.6",
11432
]
11433
11269
11434
[[package]]
11270
11435
name = "windows-sys"
11271
11436
version = "0.60.2"
@@ -11660,7 +11825,7 @@ checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566"
11660
11825
dependencies = [
11661
11826
"bitflags 2.13.2",
11662
11827
"libc",
11663
"quick-xml",
11828
"quick-xml 0.41.0",
11664
11829
"x11",
11665
11830
]
11666
11831
@@ -11670,6 +11835,16 @@ version = "0.3.11"
11670
11835
source = "registry+https://github.com/rust-lang/crates.io-index"
11671
11836
checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"
11672
11837
11838
[[package]]
11839
name = "xdg-home"
11840
version = "1.3.0"
11841
source = "registry+https://github.com/rust-lang/crates.io-index"
11842
checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6"
11843
dependencies = [
11844
"libc",
11845
"windows-sys 0.59.0",
11846
]
11847
11673
11848
[[package]]
11674
11849
name = "xim-ctext"
11675
11850
version = "0.3.0"
@@ -11775,6 +11950,45 @@ dependencies = [
11775
11950
"synstructure",
11776
11951
]
11777
11952
11953
[[package]]
11954
name = "zbus"
11955
version = "4.4.0"
11956
source = "registry+https://github.com/rust-lang/crates.io-index"
11957
checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725"
11958
dependencies = [
11959
"async-broadcast",
11960
"async-executor",
11961
"async-fs",
11962
"async-io",
11963
"async-lock",
11964
"async-process",
11965
"async-recursion",
11966
"async-task",
11967
"async-trait",
11968
"blocking",
11969
"enumflags2",
11970
"event-listener",
11971
"futures-core",
11972
"futures-sink",
11973
"futures-util",
11974
"hex",
11975
"nix",
11976
"ordered-stream",
11977
"rand 0.8.8",
11978
"serde",
11979
"serde_repr",
11980
"sha1",
11981
"static_assertions",
11982
"tokio",
11983
"tracing",
11984
"uds_windows",
11985
"windows-sys 0.52.0",
11986
"xdg-home",
11987
"zbus_macros 4.4.0",
11988
"zbus_names 3.0.0",
11989
"zvariant 4.2.0",
11990
]
11991
11778
11992
[[package]]
11779
11993
name = "zbus"
11780
11994
version = "5.19.0"
@@ -11806,9 +12020,9 @@ dependencies = [
11806
12020
"uuid",
11807
12021
"windows-sys 0.61.2",
11808
12022
"winnow 1.0.4",
11809
"zbus_macros",
11810
"zbus_names",
11811
"zvariant",
12023
"zbus_macros 5.19.0",
12024
"zbus_names 4.3.4",
12025
"zvariant 5.15.0",
11812
12026
]
11813
12027
11814
12028
[[package]]
@@ -11818,7 +12032,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
11818
12032
checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863"
11819
12033
dependencies = [
11820
12034
"zbus_xml",
11821
"zvariant",
12035
"zvariant 5.15.0",
11822
12036
]
11823
12037
11824
12038
[[package]]
@@ -11832,7 +12046,20 @@ dependencies = [
11832
12046
"syn 2.0.119",
11833
12047
"zbus-lockstep",
11834
12048
"zbus_xml",
11835
"zvariant",
12049
"zvariant 5.15.0",
12050
]
12051
12052
[[package]]
12053
name = "zbus_macros"
12054
version = "4.4.0"
12055
source = "registry+https://github.com/rust-lang/crates.io-index"
12056
checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e"
12057
dependencies = [
12058
"proc-macro-crate 3.5.0",
12059
"proc-macro2",
12060
"quote",
12061
"syn 2.0.119",
12062
"zvariant_utils 2.1.0",
11836
12063
]
11837
12064
11838
12065
[[package]]
@@ -11845,9 +12072,20 @@ dependencies = [
11845
12072
"proc-macro2",
11846
12073
"quote",
11847
12074
"syn 3.0.6",
11848
"zbus_names",
11849
"zvariant",
11850
"zvariant_utils",
12075
"zbus_names 4.3.4",
12076
"zvariant 5.15.0",
12077
"zvariant_utils 4.2.0",
12078
]
12079
12080
[[package]]
12081
name = "zbus_names"
12082
version = "3.0.0"
12083
source = "registry+https://github.com/rust-lang/crates.io-index"
12084
checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c"
12085
dependencies = [
12086
"serde",
12087
"static_assertions",
12088
"zvariant 4.2.0",
11851
12089
]
11852
12090
11853
12091
[[package]]
@@ -11858,7 +12096,7 @@ checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"
11858
12096
dependencies = [
11859
12097
"serde",
11860
12098
"winnow 1.0.4",
11861
"zvariant",
12099
"zvariant 5.15.0",
11862
12100
]
11863
12101
11864
12102
[[package]]
@@ -11869,8 +12107,8 @@ checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a"
11869
12107
dependencies = [
11870
12108
"serde",
11871
12109
"winnow 1.0.4",
11872
"zbus_names",
11873
"zvariant",
12110
"zbus_names 4.3.4",
12111
"zvariant 5.15.0",
11874
12112
]
11875
12113
11876
12114
[[package]]
@@ -12106,6 +12344,19 @@ dependencies = [
12106
12344
"zune-core 0.5.3",
12107
12345
]
12108
12346
12347
[[package]]
12348
name = "zvariant"
12349
version = "4.2.0"
12350
source = "registry+https://github.com/rust-lang/crates.io-index"
12351
checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe"
12352
dependencies = [
12353
"endi",
12354
"enumflags2",
12355
"serde",
12356
"static_assertions",
12357
"zvariant_derive 4.2.0",
12358
]
12359
12109
12360
[[package]]
12110
12361
name = "zvariant"
12111
12362
version = "5.15.0"
@@ -12118,8 +12369,21 @@ dependencies = [
12118
12369
"serde_bytes",
12119
12370
"winnow 1.0.4",
12120
12371
"zcheapstr",
12121
"zvariant_derive",
12122
"zvariant_utils",
12372
"zvariant_derive 5.15.0",
12373
"zvariant_utils 4.2.0",
12374
]
12375
12376
[[package]]
12377
name = "zvariant_derive"
12378
version = "4.2.0"
12379
source = "registry+https://github.com/rust-lang/crates.io-index"
12380
checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449"
12381
dependencies = [
12382
"proc-macro-crate 3.5.0",
12383
"proc-macro2",
12384
"quote",
12385
"syn 2.0.119",
12386
"zvariant_utils 2.1.0",
12123
12387
]
12124
12388
12125
12389
[[package]]
@@ -12132,7 +12396,18 @@ dependencies = [
12132
12396
"proc-macro2",
12133
12397
"quote",
12134
12398
"syn 3.0.6",
12135
"zvariant_utils",
12399
"zvariant_utils 4.2.0",
12400
]
12401
12402
[[package]]
12403
name = "zvariant_utils"
12404
version = "2.1.0"
12405
source = "registry+https://github.com/rust-lang/crates.io-index"
12406
checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340"
12407
dependencies = [
12408
"proc-macro2",
12409
"quote",
12410
"syn 2.0.119",
12136
12411
]
12137
12412
12138
12413
[[package]]
@@ -23,7 +23,7 @@ dependencies = [23
"atspi-common",23
"atspi-common",24
"phf 0.13.1",24
"phf 0.13.1",25
"serde",25
"serde",26
"zvariant",26
"zvariant 5.15.0",27
]27
]28
28
29
[[package]]29
[[package]]@@ -65,7 +65,7 @@ dependencies = [65
"futures-lite",65
"futures-lite",66
"futures-util",66
"futures-util",67
"serde",67
"serde",68
"zbus",68
"zbus 5.19.0",69
]69
]70
70
71
[[package]]71
[[package]]@@ -340,7 +340,7 @@ dependencies = [340
"tray-icon",340
"tray-icon",341
"windows 0.62.2",341
"windows 0.62.2",342
"x11rb",342
"x11rb",343
"zbus",343
"zbus 5.19.0",344
]344
]345
345
346
[[package]]346
[[package]]@@ -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
]@@ -491,7 +494,7 @@ dependencies = [491
"wayland-backend",494
"wayland-backend",492
"wayland-client",495
"wayland-client",493
"wayland-protocols",496
"wayland-protocols",494
"zbus",497
"zbus 5.19.0",495
]498
]496
499
497
[[package]]500
[[package]]@@ -713,11 +716,11 @@ dependencies = [713
"enumflags2",716
"enumflags2",714
"serde",717
"serde",715
"static_assertions",718
"static_assertions",716
"zbus",719
"zbus 5.19.0",717
"zbus-lockstep",720
"zbus-lockstep",718
"zbus-lockstep-macros",721
"zbus-lockstep-macros",719
"zbus_names",722
"zbus_names 4.3.4",720
"zvariant",723
"zvariant 5.15.0",721
]724
]722
725
723
[[package]]726
[[package]]@@ -728,7 +731,7 @@ checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc"728
dependencies = [731
dependencies = [729
"atspi-common",732
"atspi-common",730
"serde",733
"serde",731
"zbus",734
"zbus 5.19.0",732
]735
]733
736
734
[[package]]737
[[package]]@@ -1376,11 +1379,14 @@ version = "0.4.0"1376
dependencies = [1379
dependencies = [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]]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
[[package]]1425
[[package]]1410
name = "cipher"1426
name = "cipher"1411
version = "0.4.4"1427
version = "0.4.4"@@ -2182,6 +2198,35 @@ version = "0.3.2"2182
source = "registry+https://github.com/rust-lang/crates.io-index"2198
source = "registry+https://github.com/rust-lang/crates.io-index"2183
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"2199
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"2184
2200
2201
[[package]]2202
name = "dbus"2203
version = "0.9.11"2204
source = "registry+https://github.com/rust-lang/crates.io-index"2205
checksum = "b942602992bb7acfd1f51c49811c58a610ef9181b6e66f3e519d79b540a3bf73"2206
dependencies = [2207
"libc",2208
"libdbus-sys",2209
"windows-sys 0.61.2",2210
]2211
2212
[[package]]2213
name = "dbus-secret-service"2214
version = "4.1.0"2215
source = "registry+https://github.com/rust-lang/crates.io-index"2216
checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"2217
dependencies = [2218
"aes",2219
"block-padding",2220
"cbc",2221
"dbus",2222
"fastrand",2223
"hkdf",2224
"num",2225
"once_cell",2226
"sha2 0.10.9",2227
"zeroize",2228
]2229
2185
[[package]]2230
[[package]]2186
name = "deep_filter"2231
name = "deep_filter"2187
version = "0.5.7-pre"2232
version = "0.5.7-pre"@@ -5004,6 +5049,23 @@ dependencies = [5004
"unicode-segmentation",5049
"unicode-segmentation",5005
]5050
]5006
5051
5052
[[package]]5053
name = "keyring"5054
version = "3.6.3"5055
source = "registry+https://github.com/rust-lang/crates.io-index"5056
checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"5057
dependencies = [5058
"byteorder",5059
"dbus-secret-service",5060
"log",5061
"secret-service",5062
"security-framework 2.11.1",5063
"security-framework 3.7.0",5064
"windows-sys 0.60.2",5065
"zbus 4.4.0",5066
"zeroize",5067
]5068
5007
[[package]]5069
[[package]]5008
name = "khronos-egl"5070
name = "khronos-egl"5009
version = "6.0.0"5071
version = "6.0.0"@@ -5053,7 +5115,7 @@ dependencies = [5053
"pastey 0.2.3",5115
"pastey 0.2.3",5054
"serde",5116
"serde",5055
"tokio",5117
"tokio",5056
"zbus",5118
"zbus 5.19.0",5057
]5119
]5058
5120
5059
[[package]]5121
[[package]]@@ -5148,6 +5210,15 @@ version = "0.2.190"5148
source = "registry+https://github.com/rust-lang/crates.io-index"5210
source = "registry+https://github.com/rust-lang/crates.io-index"5149
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"5211
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"5150
5212
5213
[[package]]5214
name = "libdbus-sys"5215
version = "0.2.7"5216
source = "registry+https://github.com/rust-lang/crates.io-index"5217
checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"5218
dependencies = [5219
"pkg-config",5220
]5221
5151
[[package]]5222
[[package]]5152
name = "libfuzzer-sys"5223
name = "libfuzzer-sys"5153
version = "0.4.13"5224
version = "0.4.13"@@ -5796,6 +5867,19 @@ version = "1.0.6"5796
source = "registry+https://github.com/rust-lang/crates.io-index"5867
source = "registry+https://github.com/rust-lang/crates.io-index"5797
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"5868
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"5798
5869
5870
[[package]]5871
name = "nix"5872
version = "0.29.0"5873
source = "registry+https://github.com/rust-lang/crates.io-index"5874
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"5875
dependencies = [5876
"bitflags 2.13.2",5877
"cfg-if 1.0.5",5878
"cfg_aliases",5879
"libc",5880
"memoffset",5881
]5882
5799
[[package]]5883
[[package]]5800
name = "no_std_io2"5884
name = "no_std_io2"5801
version = "0.9.4"5885
version = "0.9.4"@@ -5949,7 +6033,7 @@ dependencies = [5949
"mac-notification-sys",6033
"mac-notification-sys",5950
"serde",6034
"serde",5951
"tauri-winrt-notification",6035
"tauri-winrt-notification",5952
"zbus",6036
"zbus 5.19.0",5953
]6037
]5954
6038
5955
[[package]]6039
[[package]]@@ -6113,7 +6197,7 @@ version = "0.7.6"6113
source = "registry+https://github.com/rust-lang/crates.io-index"6197
source = "registry+https://github.com/rust-lang/crates.io-index"6114
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"6198
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"6115
dependencies = [6199
dependencies = [6116
"proc-macro-crate 3.5.0",6200
"proc-macro-crate 1.3.1",6117
"proc-macro2",6201
"proc-macro2",6118
"quote",6202
"quote",6119
"syn 2.0.119",6203
"syn 2.0.119",@@ -6569,10 +6653,10 @@ dependencies = [6569
"serde_bytes",6653
"serde_bytes",6570
"sha2 0.10.9",6654
"sha2 0.10.9",6571
"subtle",6655
"subtle",6572
"zbus",6656
"zbus 5.19.0",6573
"zbus_macros",6657
"zbus_macros 5.19.0",6574
"zeroize",6658
"zeroize",6575
"zvariant",6659
"zvariant 5.15.0",6576
]6660
]6577
6661
6578
[[package]]6662
[[package]]@@ -6768,6 +6852,15 @@ dependencies = [6768
"phf_shared 0.11.3",6852
"phf_shared 0.11.3",6769
]6853
]6770
6854
6855
[[package]]6856
name = "phf"6857
version = "0.12.1"6858
source = "registry+https://github.com/rust-lang/crates.io-index"6859
checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"6860
dependencies = [6861
"phf_shared 0.12.1",6862
]6863
6771
[[package]]6864
[[package]]6772
name = "phf"6865
name = "phf"6773
version = "0.13.1"6866
version = "0.13.1"@@ -6844,6 +6937,15 @@ dependencies = [6844
"siphasher",6937
"siphasher",6845
]6938
]6846
6939
6940
[[package]]6941
name = "phf_shared"6942
version = "0.12.1"6943
source = "registry+https://github.com/rust-lang/crates.io-index"6944
checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"6945
dependencies = [6946
"siphasher",6947
]6948
6847
[[package]]6949
[[package]]6848
name = "phf_shared"6950
name = "phf_shared"6849
version = "0.13.1"6951
version = "0.13.1"@@ -7235,6 +7337,15 @@ version = "2.0.1"7235
source = "registry+https://github.com/rust-lang/crates.io-index"7337
source = "registry+https://github.com/rust-lang/crates.io-index"7236
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"7338
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"7237
7339
7340
[[package]]7341
name = "quick-xml"7342
version = "0.37.5"7343
source = "registry+https://github.com/rust-lang/crates.io-index"7344
checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"7345
dependencies = [7346
"memchr",7347
]7348
7238
[[package]]7349
[[package]]7239
name = "quick-xml"7350
name = "quick-xml"7240
version = "0.41.0"7351
version = "0.41.0"@@ -7884,6 +7995,19 @@ dependencies = [7884
"memchr",7995
"memchr",7885
]7996
]7886
7997
7998
[[package]]7999
name = "rrule"8000
version = "0.14.0"8001
source = "registry+https://github.com/rust-lang/crates.io-index"8002
checksum = "720acfb4980b9d8a6a430f6d7a11933e701ebbeba5eee39cc9d8c5f932aaff74"8003
dependencies = [8004
"chrono",8005
"chrono-tz",8006
"log",8007
"regex",8008
"thiserror 2.0.21",8009
]8010
7887
[[package]]8011
[[package]]7888
name = "rtrb"8012
name = "rtrb"7889
version = "0.3.5"8013
version = "0.3.5"@@ -8050,7 +8174,7 @@ dependencies = [8050
"errno",8174
"errno",8051
"libc",8175
"libc",8052
"linux-raw-sys 0.4.15",8176
"linux-raw-sys 0.4.15",8053
"windows-sys 0.52.0",8177
"windows-sys 0.59.0",8054
]8178
]8055
8179
8056
[[package]]8180
[[package]]@@ -8091,7 +8215,7 @@ dependencies = [8091
"openssl-probe",8215
"openssl-probe",8092
"rustls-pki-types",8216
"rustls-pki-types",8093
"schannel",8217
"schannel",8094
"security-framework",8218
"security-framework 3.7.0",8095
]8219
]8096
8220
8097
[[package]]8221
[[package]]@@ -8128,7 +8252,7 @@ dependencies = [8128
"rustls-native-certs",8252
"rustls-native-certs",8129
"rustls-platform-verifier-android",8253
"rustls-platform-verifier-android",8130
"rustls-webpki",8254
"rustls-webpki",8131
"security-framework",8255
"security-framework 3.7.0",8132
"security-framework-sys",8256
"security-framework-sys",8133
"webpki-root-certs",8257
"webpki-root-certs",8134
"windows-sys 0.61.2",8258
"windows-sys 0.61.2",@@ -8301,6 +8425,38 @@ version = "4.1.0"8301
source = "registry+https://github.com/rust-lang/crates.io-index"8425
source = "registry+https://github.com/rust-lang/crates.io-index"8302
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"8426
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"8303
8427
8428
[[package]]8429
name = "secret-service"8430
version = "4.0.0"8431
source = "registry+https://github.com/rust-lang/crates.io-index"8432
checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4"8433
dependencies = [8434
"aes",8435
"cbc",8436
"futures-util",8437
"generic-array",8438
"hkdf",8439
"num",8440
"once_cell",8441
"rand 0.8.8",8442
"serde",8443
"sha2 0.10.9",8444
"zbus 4.4.0",8445
]8446
8447
[[package]]8448
name = "security-framework"8449
version = "2.11.1"8450
source = "registry+https://github.com/rust-lang/crates.io-index"8451
checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"8452
dependencies = [8453
"bitflags 2.13.2",8454
"core-foundation 0.9.4",8455
"core-foundation-sys 0.8.7",8456
"libc",8457
"security-framework-sys",8458
]8459
8304
[[package]]8460
[[package]]8305
name = "security-framework"8461
name = "security-framework"8306
version = "3.7.0"8462
version = "3.7.0"@@ -9249,7 +9405,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"9249
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"9405
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"9250
dependencies = [9406
dependencies = [9251
"fastrand",9407
"fastrand",9252
"getrandom 0.4.3",9408
"getrandom 0.3.4",9253
"once_cell",9409
"once_cell",9254
"rustix 1.1.5",9410
"rustix 1.1.5",9255
"windows-sys 0.61.2",9411
"windows-sys 0.61.2",@@ -10533,7 +10689,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"10533
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"10689
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"10534
dependencies = [10690
dependencies = [10535
"proc-macro2",10691
"proc-macro2",10536
"quick-xml",10692
"quick-xml 0.41.0",10537
"quote",10693
"quote",10538
]10694
]10539
10695
@@ -10888,7 +11044,7 @@ version = "0.1.11"10888
source = "registry+https://github.com/rust-lang/crates.io-index"11044
source = "registry+https://github.com/rust-lang/crates.io-index"10889
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"11045
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"10890
dependencies = [11046
dependencies = [10891
"windows-sys 0.61.2",11047
"windows-sys 0.48.0",10892
]11048
]10893
11049
10894
[[package]]11050
[[package]]@@ -11266,6 +11422,15 @@ dependencies = [11266
"windows-targets 0.52.6",11422
"windows-targets 0.52.6",11267
]11423
]11268
11424
11425
[[package]]11426
name = "windows-sys"11427
version = "0.59.0"11428
source = "registry+https://github.com/rust-lang/crates.io-index"11429
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"11430
dependencies = [11431
"windows-targets 0.52.6",11432
]11433
11269
[[package]]11434
[[package]]11270
name = "windows-sys"11435
name = "windows-sys"11271
version = "0.60.2"11436
version = "0.60.2"@@ -11660,7 +11825,7 @@ checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566"11660
dependencies = [11825
dependencies = [11661
"bitflags 2.13.2",11826
"bitflags 2.13.2",11662
"libc",11827
"libc",11663
"quick-xml",11828
"quick-xml 0.41.0",11664
"x11",11829
"x11",11665
]11830
]11666
11831
@@ -11670,6 +11835,16 @@ version = "0.3.11"11670
source = "registry+https://github.com/rust-lang/crates.io-index"11835
source = "registry+https://github.com/rust-lang/crates.io-index"11671
checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"11836
checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"11672
11837
11838
[[package]]11839
name = "xdg-home"11840
version = "1.3.0"11841
source = "registry+https://github.com/rust-lang/crates.io-index"11842
checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6"11843
dependencies = [11844
"libc",11845
"windows-sys 0.59.0",11846
]11847
11673
[[package]]11848
[[package]]11674
name = "xim-ctext"11849
name = "xim-ctext"11675
version = "0.3.0"11850
version = "0.3.0"@@ -11775,6 +11950,45 @@ dependencies = [11775
"synstructure",11950
"synstructure",11776
]11951
]11777
11952
11953
[[package]]11954
name = "zbus"11955
version = "4.4.0"11956
source = "registry+https://github.com/rust-lang/crates.io-index"11957
checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725"11958
dependencies = [11959
"async-broadcast",11960
"async-executor",11961
"async-fs",11962
"async-io",11963
"async-lock",11964
"async-process",11965
"async-recursion",11966
"async-task",11967
"async-trait",11968
"blocking",11969
"enumflags2",11970
"event-listener",11971
"futures-core",11972
"futures-sink",11973
"futures-util",11974
"hex",11975
"nix",11976
"ordered-stream",11977
"rand 0.8.8",11978
"serde",11979
"serde_repr",11980
"sha1",11981
"static_assertions",11982
"tokio",11983
"tracing",11984
"uds_windows",11985
"windows-sys 0.52.0",11986
"xdg-home",11987
"zbus_macros 4.4.0",11988
"zbus_names 3.0.0",11989
"zvariant 4.2.0",11990
]11991
11778
[[package]]11992
[[package]]11779
name = "zbus"11993
name = "zbus"11780
version = "5.19.0"11994
version = "5.19.0"@@ -11806,9 +12020,9 @@ dependencies = [11806
"uuid",12020
"uuid",11807
"windows-sys 0.61.2",12021
"windows-sys 0.61.2",11808
"winnow 1.0.4",12022
"winnow 1.0.4",11809
"zbus_macros",12023
"zbus_macros 5.19.0",11810
"zbus_names",12024
"zbus_names 4.3.4",11811
"zvariant",12025
"zvariant 5.15.0",11812
]12026
]11813
12027
11814
[[package]]12028
[[package]]@@ -11818,7 +12032,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"11818
checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863"12032
checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863"11819
dependencies = [12033
dependencies = [11820
"zbus_xml",12034
"zbus_xml",11821
"zvariant",12035
"zvariant 5.15.0",11822
]12036
]11823
12037
11824
[[package]]12038
[[package]]@@ -11832,7 +12046,20 @@ dependencies = [11832
"syn 2.0.119",12046
"syn 2.0.119",11833
"zbus-lockstep",12047
"zbus-lockstep",11834
"zbus_xml",12048
"zbus_xml",11835
"zvariant",12049
"zvariant 5.15.0",12050
]12051
12052
[[package]]12053
name = "zbus_macros"12054
version = "4.4.0"12055
source = "registry+https://github.com/rust-lang/crates.io-index"12056
checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e"12057
dependencies = [12058
"proc-macro-crate 3.5.0",12059
"proc-macro2",12060
"quote",12061
"syn 2.0.119",12062
"zvariant_utils 2.1.0",11836
]12063
]11837
12064
11838
[[package]]12065
[[package]]@@ -11845,9 +12072,20 @@ dependencies = [11845
"proc-macro2",12072
"proc-macro2",11846
"quote",12073
"quote",11847
"syn 3.0.6",12074
"syn 3.0.6",11848
"zbus_names",12075
"zbus_names 4.3.4",11849
"zvariant",12076
"zvariant 5.15.0",11850
"zvariant_utils",12077
"zvariant_utils 4.2.0",12078
]12079
12080
[[package]]12081
name = "zbus_names"12082
version = "3.0.0"12083
source = "registry+https://github.com/rust-lang/crates.io-index"12084
checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c"12085
dependencies = [12086
"serde",12087
"static_assertions",12088
"zvariant 4.2.0",11851
]12089
]11852
12090
11853
[[package]]12091
[[package]]@@ -11858,7 +12096,7 @@ checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"11858
dependencies = [12096
dependencies = [11859
"serde",12097
"serde",11860
"winnow 1.0.4",12098
"winnow 1.0.4",11861
"zvariant",12099
"zvariant 5.15.0",11862
]12100
]11863
12101
11864
[[package]]12102
[[package]]@@ -11869,8 +12107,8 @@ checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a"11869
dependencies = [12107
dependencies = [11870
"serde",12108
"serde",11871
"winnow 1.0.4",12109
"winnow 1.0.4",11872
"zbus_names",12110
"zbus_names 4.3.4",11873
"zvariant",12111
"zvariant 5.15.0",11874
]12112
]11875
12113
11876
[[package]]12114
[[package]]@@ -12106,6 +12344,19 @@ dependencies = [12106
"zune-core 0.5.3",12344
"zune-core 0.5.3",12107
]12345
]12108
12346
12347
[[package]]12348
name = "zvariant"12349
version = "4.2.0"12350
source = "registry+https://github.com/rust-lang/crates.io-index"12351
checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe"12352
dependencies = [12353
"endi",12354
"enumflags2",12355
"serde",12356
"static_assertions",12357
"zvariant_derive 4.2.0",12358
]12359
12109
[[package]]12360
[[package]]12110
name = "zvariant"12361
name = "zvariant"12111
version = "5.15.0"12362
version = "5.15.0"@@ -12118,8 +12369,21 @@ dependencies = [12118
"serde_bytes",12369
"serde_bytes",12119
"winnow 1.0.4",12370
"winnow 1.0.4",12120
"zcheapstr",12371
"zcheapstr",12121
"zvariant_derive",12372
"zvariant_derive 5.15.0",12122
"zvariant_utils",12373
"zvariant_utils 4.2.0",12374
]12375
12376
[[package]]12377
name = "zvariant_derive"12378
version = "4.2.0"12379
source = "registry+https://github.com/rust-lang/crates.io-index"12380
checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449"12381
dependencies = [12382
"proc-macro-crate 3.5.0",12383
"proc-macro2",12384
"quote",12385
"syn 2.0.119",12386
"zvariant_utils 2.1.0",12123
]12387
]12124
12388
12125
[[package]]12389
[[package]]@@ -12132,7 +12396,18 @@ dependencies = [12132
"proc-macro2",12396
"proc-macro2",12133
"quote",12397
"quote",12134
"syn 3.0.6",12398
"syn 3.0.6",12135
"zvariant_utils",12399
"zvariant_utils 4.2.0",12400
]12401
12402
[[package]]12403
name = "zvariant_utils"12404
version = "2.1.0"12405
source = "registry+https://github.com/rust-lang/crates.io-index"12406
checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340"12407
dependencies = [12408
"proc-macro2",12409
"quote",12410
"syn 2.0.119",12136
]12411
]12137
12412
12138
[[package]]12413
[[package]]@@ -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: Calendar107
en: Calendar108
de: Kalender108
de: Kalender109
calendar_accounts:110
en: Calendar accounts111
de: Kalenderkonten109
devices:112
devices:110
en: Devices113
en: Devices111
de: Geräte114
de: Geräte@@ -262,6 +265,12 @@ settings:262
section_google:265
section_google:263
en: GOOGLE266
en: GOOGLE264
de: GOOGLE267
de: GOOGLE268
section_caldav:269
en: CALDAV270
de: CALDAV271
section_ics:272
en: ICS SUBSCRIPTIONS273
de: ICS-ABOS265
section_home:274
section_home:266
en: HOME CALENDAR275
en: HOME CALENDAR267
de: HAUPTKALENDER276
de: HAUPTKALENDER@@ -271,6 +280,63 @@ settings:271
google_title:280
google_title:272
en: Google Calendar281
en: Google Calendar273
de: Google Kalender282
de: Google Kalender283
caldav_title:284
en: CalDAV calendar285
de: CalDAV-Kalender286
caldav_url:287
en: Server URL288
de: Server-URL289
caldav_username:290
en: Username291
de: Benutzername292
caldav_password:293
en: App password294
de: App-Passwort295
caldav_connect:296
en: Connect CalDAV297
de: CalDAV verbinden298
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: Nextcloud303
de: Nextcloud304
caldav_template_fastmail:305
en: Fastmail306
de: Fastmail307
caldav_template_icloud:308
en: iCloud309
de: iCloud310
caldav_connected:311
en: CalDAV account connected312
de: CalDAV-Konto verbunden313
caldav_connect_failed:314
en: CalDAV connect failed315
de: CalDAV-Verbindung fehlgeschlagen316
caldav_readonly:317
en: Read-only318
de: Nur lesen319
ics_title:320
en: ICS subscription321
de: ICS-Abo322
ics_url:323
en: ICS URL324
de: ICS-URL325
ics_name:326
en: Display name327
de: Anzeigename328
ics_connect:329
en: Add subscription330
de: Abo hinzufügen331
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 added336
de: ICS-Abo hinzugefügt337
ics_connect_failed:338
en: ICS subscription failed339
de: ICS-Abo fehlgeschlagen274
connect_button:340
connect_button:275
en: Connect Google341
en: Connect Google276
de: Google verbinden342
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 Google377
en: Also write when home is not Outlook312
de: Zusätzlich schreiben, wenn der Hauptkalender Google ist378
de: Zusätzlich schreiben, wenn der Hauptkalender nicht Outlook ist313
outlook_home_detail:379
outlook_home_detail:314
en: Default when no Google home is chosen380
en: Default when no other home calendar is chosen315
de: Standard, wenn kein Google-Hauptkalender gewählt ist381
de: Standard, wenn kein anderer Hauptkalender gewählt ist316
no_extra_targets:382
no_extra_targets:317
en: No extra write targets383
en: No extra write targets318
de: Keine weiteren Schreibziele384
de: Keine weiteren Schreibziele319
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: VIEW389
en: VIEW324
de: ANSICHT390
de: ANSICHT@@ -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 = accounts259
.google_accounts260
.iter()261
.map(|account| account.calendars.len())262
.sum::<usize>();263
event264
.account_id265
.as_deref()266
.zip(event.calendar_id.as_deref())267
.and_then(|(account_id, calendar_id)| {268
accounts269
.caldav_accounts270
.iter()271
.flat_map(|account| {272
account273
.calendars274
.iter()275
.map(move |calendar| (account.id.as_str(), calendar.id.as_str()))276
})277
.position(|(account, calendar)| {278
account == account_id && calendar == calendar_id279
})280
.map(|position| position + 1 + google_len)281
})282
.unwrap_or(1 + google_len)283
}284
chatsvc::CalendarSource::Ics => {285
let offset = 1286
+ accounts287
.google_accounts288
.iter()289
.map(|account| account.calendars.len())290
.sum::<usize>()291
+ accounts292
.caldav_accounts293
.iter()294
.map(|account| account.calendars.len())295
.sum::<usize>();296
event297
.account_id298
.as_deref()299
.and_then(|id| {300
accounts301
.ics_subscriptions302
.iter()303
.position(|subscription| subscription.id == id)304
.map(|position| position + offset)305
})306
.unwrap_or(offset)307
}257
}308
}258
}309
}259
310
@@ -37,6 +37,15 @@ 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 = { version = "3", features = [
41
"apple-native",
42
"windows-native",
43
"async-secret-service",
44
"tokio",
45
"crypto-rust",
46
] }
47
reqwest = { version = "0.13", default-features = false, features = ["rustls"] }
48
url = "2"
40
49
41
50
[target.'cfg(windows)'.dependencies]
42
51
webview.workspace = true
@@ -37,6 +37,15 @@ teams-core.workspace = true37
tokio.workspace = true37
tokio.workspace = true38
uuid.workspace = true38
uuid.workspace = true39
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }39
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }40
keyring = { version = "3", features = [41
"apple-native",42
"windows-native",43
"async-secret-service",44
"tokio",45
"crypto-rust",46
] }47
reqwest = { version = "0.13", default-features = false, features = ["rustls"] }48
url = "2"40
49
41
[target.'cfg(windows)'.dependencies]50
[target.'cfg(windows)'.dependencies]42
webview.workspace = true51
webview.workspace = true@@ -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
}@@ -0,0 +1,68 @@
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
pub async fn store_password_async(account_id: String, password: String) -> Result<(), String> {
25
tokio::task::spawn_blocking(move || store_password(&account_id, &password))
26
.await
27
.map_err(|error| error.to_string())?
28
}
29
30
pub async fn load_password_async(account_id: String) -> Result<String, String> {
31
tokio::task::spawn_blocking(move || load_password(&account_id))
32
.await
33
.map_err(|error| error.to_string())?
34
}
35
36
pub async fn delete_password_async(account_id: String) -> Result<(), String> {
37
tokio::task::spawn_blocking(move || delete_password(&account_id))
38
.await
39
.map_err(|error| error.to_string())?
40
}
41
42
/// Redact credentials that must never appear in diagnostics or support bundles.
43
pub fn redact_secret_text(text: &str) -> String {
44
let mut out = text.to_owned();
45
// user:pass@host
46
if let Some(scheme_end) = out.find("://") {
47
let after = scheme_end + 3;
48
if let Some(at) = out[after..].find('@') {
49
let creds = &out[after..after + at];
50
if creds.contains(':') {
51
out.replace_range(after..after + at, "***:***");
52
}
53
}
54
}
55
out
56
}
57
58
#[cfg(test)]
59
mod tests {
60
use super::*;
61
62
#[test]
63
fn redacts_userinfo_in_urls() {
64
let scrubbed = redact_secret_text("GET https://joe:s3cret@cloud.example/dav/ ok");
65
assert!(!scrubbed.contains("s3cret"));
66
assert!(scrubbed.contains("***:***@cloud.example"));
67
}
68
}
@@ -0,0 +1,68 @@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
pub async fn store_password_async(account_id: String, password: String) -> Result<(), String> {25
tokio::task::spawn_blocking(move || store_password(&account_id, &password))26
.await27
.map_err(|error| error.to_string())?28
}29
30
pub async fn load_password_async(account_id: String) -> Result<String, String> {31
tokio::task::spawn_blocking(move || load_password(&account_id))32
.await33
.map_err(|error| error.to_string())?34
}35
36
pub async fn delete_password_async(account_id: String) -> Result<(), String> {37
tokio::task::spawn_blocking(move || delete_password(&account_id))38
.await39
.map_err(|error| error.to_string())?40
}41
42
/// Redact credentials that must never appear in diagnostics or support bundles.43
pub fn redact_secret_text(text: &str) -> String {44
let mut out = text.to_owned();45
// user:pass@host46
if let Some(scheme_end) = out.find("://") {47
let after = scheme_end + 3;48
if let Some(at) = out[after..].find('@') {49
let creds = &out[after..after + at];50
if creds.contains(':') {51
out.replace_range(after..after + at, "***:***");52
}53
}54
}55
out56
}57
58
#[cfg(test)]59
mod tests {60
use super::*;61
62
#[test]63
fn redacts_userinfo_in_urls() {64
let scrubbed = redact_secret_text("GET https://joe:s3cret@cloud.example/dav/ ok");65
assert!(!scrubbed.contains("s3cret"));66
assert!(scrubbed.contains("***:***@cloud.example"));67
}68
}@@ -0,0 +1,222 @@
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, href_from_object_id,
7
new_event_uid, partstat_for_reply,
8
};
9
10
use crate::caldav_credentials::{delete_password, load_password_async, store_password_async};
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).map_err(|e| e.to_string())?;
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_async(id.clone(), password.to_owned()).await?;
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
/// Events plus per-calendar failure messages. One bad calendar does not drop the rest.
60
pub async fn fetch_caldav_events(
61
accounts: &mut CalendarAccounts,
62
start: DateTime<Utc>,
63
end: DateTime<Utc>,
64
) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {
65
let mut all = Vec::new();
66
let mut failures = Vec::new();
67
for index in 0..accounts.caldav_accounts.len() {
68
let account = &accounts.caldav_accounts[index];
69
let password = match load_password_async(account.id.clone()).await {
70
Ok(password) => password,
71
Err(error) => {
72
failures.push(format!(
73
"CalDAV password missing for {}: {error}",
74
account.username
75
));
76
continue;
77
}
78
};
79
let client = match CalDavClient::new(&account.username, &password) {
80
Ok(client) => client,
81
Err(error) => {
82
failures.push(format!("CalDAV {}: {error}", account.username));
83
continue;
84
}
85
};
86
let account_id = account.id.clone();
87
let calendars: Vec<(String, String)> = account
88
.calendars
89
.iter()
90
.filter(|calendar| calendar.selected)
91
.map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
92
.collect();
93
for (calendar_id, calendar_name) in calendars {
94
match client
95
.fetch_events(&calendar_id, &account_id, Some(&calendar_name), start, end)
96
.await
97
{
98
Ok(events) => all.extend(events.into_iter().map(|item| item.event)),
99
Err(error) => failures.push(format!("CalDAV {calendar_name}: {error}")),
100
}
101
}
102
}
103
Ok((all, failures))
104
}
105
106
pub async fn insert_caldav_event(
107
accounts: &mut CalendarAccounts,
108
account_id: &str,
109
calendar_id: &str,
110
draft: &CalDavEventDraft,
111
) -> Result<(), String> {
112
let account = accounts
113
.caldav_account(account_id)
114
.ok_or_else(|| format!("CalDAV account {account_id} missing"))?;
115
let password = load_password_async(account_id.to_owned()).await?;
116
let client = CalDavClient::new(&account.username, password).map_err(|e| e.to_string())?;
117
client
118
.put_event(calendar_id, draft, Utc::now())
119
.await
120
.map(|_| ())
121
.map_err(|e| e.to_string())
122
}
123
124
pub async fn respond_caldav_event(
125
accounts: &mut CalendarAccounts,
126
account_id: &str,
127
href: &str,
128
reply: Reply,
129
) -> Result<bool, String> {
130
let account = accounts
131
.caldav_account(account_id)
132
.ok_or_else(|| format!("CalDAV account {account_id} missing"))?;
133
let password = load_password_async(account_id.to_owned()).await?;
134
let mailto = account
135
.user_addresses
136
.iter()
137
.find(|addr| addr.to_ascii_lowercase().contains('@'))
138
.cloned()
139
.or_else(|| {
140
account
141
.username
142
.contains('@')
143
.then(|| format!("mailto:{}", account.username))
144
})
145
.ok_or_else(|| "CalDAV calendar-user-address missing".to_owned())?;
146
let notified = account.schedule_outbox.is_some();
147
let client = CalDavClient::new(&account.username, password).map_err(|e| e.to_string())?;
148
let href = href_from_object_id(href).to_owned();
149
client
150
.update_partstat(&href, None, &mailto, partstat_for_reply(reply))
151
.await
152
.map_err(|e| e.to_string())?;
153
Ok(notified)
154
}
155
156
pub async fn delete_caldav_event(
157
accounts: &mut CalendarAccounts,
158
account_id: &str,
159
object_id: &str,
160
series: bool,
161
occurrence_start: DateTime<Utc>,
162
) -> Result<(), String> {
163
let account = accounts
164
.caldav_account(account_id)
165
.ok_or_else(|| format!("CalDAV account {account_id} missing"))?;
166
let password = load_password_async(account_id.to_owned()).await?;
167
let client = CalDavClient::new(&account.username, password).map_err(|e| e.to_string())?;
168
let href = href_from_object_id(object_id);
169
if series {
170
client
171
.exclude_occurrence(href, occurrence_start, None)
172
.await
173
.map_err(|e| e.to_string())
174
} else {
175
client.delete(href, None).await.map_err(|e| e.to_string())
176
}
177
}
178
179
pub fn draft_from_meeting(
180
subject: &str,
181
start: DateTime<Utc>,
182
end: DateTime<Utc>,
183
join_url: Option<&str>,
184
attendees: &[String],
185
include_attendees: bool,
186
repeat: chatsvc::Repeat,
187
) -> CalDavEventDraft {
188
CalDavEventDraft {
189
uid: new_event_uid(),
190
summary: subject.to_owned(),
191
start,
192
end,
193
all_day: false,
194
description: None,
195
location: None,
196
join_url: join_url.map(str::to_owned),
197
attendees: if include_attendees {
198
attendees.to_vec()
199
} else {
200
Vec::new()
201
},
202
repeat,
203
sequence: 0,
204
}
205
}
206
207
fn normalize_url(url: &str) -> Result<String, String> {
208
let trimmed = url.trim();
209
if trimmed.is_empty() {
210
return Err("CalDAV URL is empty".into());
211
}
212
let with_scheme = if trimmed.contains("://") {
213
trimmed.to_owned()
214
} else {
215
format!("https://{trimmed}")
216
};
217
let parsed = url::Url::parse(&with_scheme).map_err(|e| e.to_string())?;
218
if parsed.username() != "" || parsed.password().is_some() {
219
return Err("Put the username and app password in the form fields, not in the URL".into());
220
}
221
Ok(parsed.to_string())
222
}
@@ -0,0 +1,222 @@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, href_from_object_id,7
new_event_uid, partstat_for_reply,8
};9
10
use crate::caldav_credentials::{delete_password, load_password_async, store_password_async};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).map_err(|e| e.to_string())?;20
let discovered = discover_caldav(&client, &url)21
.await22
.map_err(|e| e.to_string())?;23
let listed = client24
.list_calendars(&discovered.home_set)25
.await26
.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_async(id.clone(), password.to_owned()).await?;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: listed38
.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
/// Events plus per-calendar failure messages. One bad calendar does not drop the rest.60
pub async fn fetch_caldav_events(61
accounts: &mut CalendarAccounts,62
start: DateTime<Utc>,63
end: DateTime<Utc>,64
) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {65
let mut all = Vec::new();66
let mut failures = Vec::new();67
for index in 0..accounts.caldav_accounts.len() {68
let account = &accounts.caldav_accounts[index];69
let password = match load_password_async(account.id.clone()).await {70
Ok(password) => password,71
Err(error) => {72
failures.push(format!(73
"CalDAV password missing for {}: {error}",74
account.username75
));76
continue;77
}78
};79
let client = match CalDavClient::new(&account.username, &password) {80
Ok(client) => client,81
Err(error) => {82
failures.push(format!("CalDAV {}: {error}", account.username));83
continue;84
}85
};86
let account_id = account.id.clone();87
let calendars: Vec<(String, String)> = account88
.calendars89
.iter()90
.filter(|calendar| calendar.selected)91
.map(|calendar| (calendar.id.clone(), calendar.summary.clone()))92
.collect();93
for (calendar_id, calendar_name) in calendars {94
match client95
.fetch_events(&calendar_id, &account_id, Some(&calendar_name), start, end)96
.await97
{98
Ok(events) => all.extend(events.into_iter().map(|item| item.event)),99
Err(error) => failures.push(format!("CalDAV {calendar_name}: {error}")),100
}101
}102
}103
Ok((all, failures))104
}105
106
pub async fn insert_caldav_event(107
accounts: &mut CalendarAccounts,108
account_id: &str,109
calendar_id: &str,110
draft: &CalDavEventDraft,111
) -> Result<(), String> {112
let account = accounts113
.caldav_account(account_id)114
.ok_or_else(|| format!("CalDAV account {account_id} missing"))?;115
let password = load_password_async(account_id.to_owned()).await?;116
let client = CalDavClient::new(&account.username, password).map_err(|e| e.to_string())?;117
client118
.put_event(calendar_id, draft, Utc::now())119
.await120
.map(|_| ())121
.map_err(|e| e.to_string())122
}123
124
pub async fn respond_caldav_event(125
accounts: &mut CalendarAccounts,126
account_id: &str,127
href: &str,128
reply: Reply,129
) -> Result<bool, String> {130
let account = accounts131
.caldav_account(account_id)132
.ok_or_else(|| format!("CalDAV account {account_id} missing"))?;133
let password = load_password_async(account_id.to_owned()).await?;134
let mailto = account135
.user_addresses136
.iter()137
.find(|addr| addr.to_ascii_lowercase().contains('@'))138
.cloned()139
.or_else(|| {140
account141
.username142
.contains('@')143
.then(|| format!("mailto:{}", account.username))144
})145
.ok_or_else(|| "CalDAV calendar-user-address missing".to_owned())?;146
let notified = account.schedule_outbox.is_some();147
let client = CalDavClient::new(&account.username, password).map_err(|e| e.to_string())?;148
let href = href_from_object_id(href).to_owned();149
client150
.update_partstat(&href, None, &mailto, partstat_for_reply(reply))151
.await152
.map_err(|e| e.to_string())?;153
Ok(notified)154
}155
156
pub async fn delete_caldav_event(157
accounts: &mut CalendarAccounts,158
account_id: &str,159
object_id: &str,160
series: bool,161
occurrence_start: DateTime<Utc>,162
) -> Result<(), String> {163
let account = accounts164
.caldav_account(account_id)165
.ok_or_else(|| format!("CalDAV account {account_id} missing"))?;166
let password = load_password_async(account_id.to_owned()).await?;167
let client = CalDavClient::new(&account.username, password).map_err(|e| e.to_string())?;168
let href = href_from_object_id(object_id);169
if series {170
client171
.exclude_occurrence(href, occurrence_start, None)172
.await173
.map_err(|e| e.to_string())174
} else {175
client.delete(href, None).await.map_err(|e| e.to_string())176
}177
}178
179
pub fn draft_from_meeting(180
subject: &str,181
start: DateTime<Utc>,182
end: DateTime<Utc>,183
join_url: Option<&str>,184
attendees: &[String],185
include_attendees: bool,186
repeat: chatsvc::Repeat,187
) -> CalDavEventDraft {188
CalDavEventDraft {189
uid: new_event_uid(),190
summary: subject.to_owned(),191
start,192
end,193
all_day: false,194
description: None,195
location: None,196
join_url: join_url.map(str::to_owned),197
attendees: if include_attendees {198
attendees.to_vec()199
} else {200
Vec::new()201
},202
repeat,203
sequence: 0,204
}205
}206
207
fn normalize_url(url: &str) -> Result<String, String> {208
let trimmed = url.trim();209
if trimmed.is_empty() {210
return Err("CalDAV URL is empty".into());211
}212
let with_scheme = if trimmed.contains("://") {213
trimmed.to_owned()214
} else {215
format!("https://{trimmed}")216
};217
let parsed = url::Url::parse(&with_scheme).map_err(|e| e.to_string())?;218
if parsed.username() != "" || parsed.password().is_some() {219
return Err("Put the username and app password in the form fields, not in the URL".into());220
}221
Ok(parsed.to_string())222
}@@ -33,6 +33,149 @@ 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 = crate::caldav_sync::connect_caldav(&mut accounts, &url, &username, &password)
47
.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| match connecting.await {
52
Ok(Ok(_)) => {
53
this.update(cx, |state, cx| {
54
state.raise_notice(tr("settings.calendar.caldav_connected"), None, cx);
55
state.refresh_calendar(cx);
56
state.load_calendar_week(cx);
57
cx.notify();
58
})
59
.ok();
60
}
61
Ok(Err(error)) => {
62
this.update(cx, |state, cx| {
63
state.raise_notice(
64
crate::caldav_credentials::redact_secret_text(&error),
65
None,
66
cx,
67
);
68
})
69
.ok();
70
}
71
Err(_) => {
72
this.update(cx, |state, cx| {
73
state.raise_notice(tr("settings.calendar.caldav_connect_failed"), None, cx);
74
})
75
.ok();
76
}
77
})
78
.detach();
79
}
80
81
pub fn disconnect_caldav_account(&mut self, account_id: &str, cx: &mut Context<Self>) {
82
let mut accounts = load_calendar_accounts(&self.store);
83
if let Err(error) = crate::caldav_sync::disconnect_caldav(&mut accounts, account_id) {
84
self.raise_notice(error, None, cx);
85
return;
86
}
87
let _ = save_calendar_accounts(&self.store, &accounts);
88
self.refresh_calendar(cx);
89
self.load_calendar_week(cx);
90
cx.notify();
91
}
92
93
pub fn toggle_caldav_calendar_selected(
94
&mut self,
95
account_id: &str,
96
calendar_id: &str,
97
cx: &mut Context<Self>,
98
) {
99
let mut accounts = load_calendar_accounts(&self.store);
100
if let Some(calendar) = accounts.caldav_account_mut(account_id).and_then(|account| {
101
account
102
.calendars
103
.iter_mut()
104
.find(|calendar| calendar.id == calendar_id)
105
}) {
106
calendar.selected = !calendar.selected;
107
}
108
let _ = save_calendar_accounts(&self.store, &accounts);
109
self.refresh_calendar(cx);
110
self.load_calendar_week(cx);
111
cx.notify();
112
}
113
114
pub fn connect_ics_subscription(
115
&mut self,
116
url: String,
117
summary: String,
118
cx: &mut Context<Self>,
119
) {
120
let store = self.store.clone();
121
let connecting = runtime::spawn(async move {
122
let mut accounts = load_calendar_accounts(&store);
123
let id = crate::ics_sync::add_ics_subscription(&mut accounts, &url, &summary).await?;
124
save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
125
Ok::<_, String>(id)
126
});
127
cx.spawn(async move |this, cx| match connecting.await {
128
Ok(Ok(_)) => {
129
this.update(cx, |state, cx| {
130
state.raise_notice(tr("settings.calendar.ics_connected"), None, cx);
131
state.refresh_calendar(cx);
132
state.load_calendar_week(cx);
133
cx.notify();
134
})
135
.ok();
136
}
137
Ok(Err(error)) => {
138
this.update(cx, |state, cx| state.raise_notice(error, None, cx))
139
.ok();
140
}
141
Err(_) => {
142
this.update(cx, |state, cx| {
143
state.raise_notice(tr("settings.calendar.ics_connect_failed"), None, cx);
144
})
145
.ok();
146
}
147
})
148
.detach();
149
}
150
151
pub fn disconnect_ics_subscription(&mut self, subscription_id: &str, cx: &mut Context<Self>) {
152
let mut accounts = load_calendar_accounts(&self.store);
153
accounts.disconnect_ics(subscription_id);
154
let _ = save_calendar_accounts(&self.store, &accounts);
155
self.refresh_calendar(cx);
156
self.load_calendar_week(cx);
157
cx.notify();
158
}
159
160
pub fn toggle_ics_subscription_selected(
161
&mut self,
162
subscription_id: &str,
163
cx: &mut Context<Self>,
164
) {
165
let mut accounts = load_calendar_accounts(&self.store);
166
if let Some(subscription) = accounts
167
.ics_subscriptions
168
.iter_mut()
169
.find(|subscription| subscription.id == subscription_id)
170
{
171
subscription.selected = !subscription.selected;
172
}
173
let _ = save_calendar_accounts(&self.store, &accounts);
174
self.refresh_calendar(cx);
175
self.load_calendar_week(cx);
176
cx.notify();
177
}
178
36
179
pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {
37
180
let mut accounts = load_calendar_accounts(&self.store);
38
181
accounts.home = home;
@@ -33,6 +33,149 @@ 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 = crate::caldav_sync::connect_caldav(&mut accounts, &url, &username, &password)47
.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| match connecting.await {52
Ok(Ok(_)) => {53
this.update(cx, |state, cx| {54
state.raise_notice(tr("settings.calendar.caldav_connected"), None, cx);55
state.refresh_calendar(cx);56
state.load_calendar_week(cx);57
cx.notify();58
})59
.ok();60
}61
Ok(Err(error)) => {62
this.update(cx, |state, cx| {63
state.raise_notice(64
crate::caldav_credentials::redact_secret_text(&error),65
None,66
cx,67
);68
})69
.ok();70
}71
Err(_) => {72
this.update(cx, |state, cx| {73
state.raise_notice(tr("settings.calendar.caldav_connect_failed"), None, cx);74
})75
.ok();76
}77
})78
.detach();79
}80
81
pub fn disconnect_caldav_account(&mut self, account_id: &str, cx: &mut Context<Self>) {82
let mut accounts = load_calendar_accounts(&self.store);83
if let Err(error) = crate::caldav_sync::disconnect_caldav(&mut accounts, account_id) {84
self.raise_notice(error, None, cx);85
return;86
}87
let _ = save_calendar_accounts(&self.store, &accounts);88
self.refresh_calendar(cx);89
self.load_calendar_week(cx);90
cx.notify();91
}92
93
pub fn toggle_caldav_calendar_selected(94
&mut self,95
account_id: &str,96
calendar_id: &str,97
cx: &mut Context<Self>,98
) {99
let mut accounts = load_calendar_accounts(&self.store);100
if let Some(calendar) = accounts.caldav_account_mut(account_id).and_then(|account| {101
account102
.calendars103
.iter_mut()104
.find(|calendar| calendar.id == calendar_id)105
}) {106
calendar.selected = !calendar.selected;107
}108
let _ = save_calendar_accounts(&self.store, &accounts);109
self.refresh_calendar(cx);110
self.load_calendar_week(cx);111
cx.notify();112
}113
114
pub fn connect_ics_subscription(115
&mut self,116
url: String,117
summary: String,118
cx: &mut Context<Self>,119
) {120
let store = self.store.clone();121
let connecting = runtime::spawn(async move {122
let mut accounts = load_calendar_accounts(&store);123
let id = crate::ics_sync::add_ics_subscription(&mut accounts, &url, &summary).await?;124
save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;125
Ok::<_, String>(id)126
});127
cx.spawn(async move |this, cx| match connecting.await {128
Ok(Ok(_)) => {129
this.update(cx, |state, cx| {130
state.raise_notice(tr("settings.calendar.ics_connected"), None, cx);131
state.refresh_calendar(cx);132
state.load_calendar_week(cx);133
cx.notify();134
})135
.ok();136
}137
Ok(Err(error)) => {138
this.update(cx, |state, cx| state.raise_notice(error, None, cx))139
.ok();140
}141
Err(_) => {142
this.update(cx, |state, cx| {143
state.raise_notice(tr("settings.calendar.ics_connect_failed"), None, cx);144
})145
.ok();146
}147
})148
.detach();149
}150
151
pub fn disconnect_ics_subscription(&mut self, subscription_id: &str, cx: &mut Context<Self>) {152
let mut accounts = load_calendar_accounts(&self.store);153
accounts.disconnect_ics(subscription_id);154
let _ = save_calendar_accounts(&self.store, &accounts);155
self.refresh_calendar(cx);156
self.load_calendar_week(cx);157
cx.notify();158
}159
160
pub fn toggle_ics_subscription_selected(161
&mut self,162
subscription_id: &str,163
cx: &mut Context<Self>,164
) {165
let mut accounts = load_calendar_accounts(&self.store);166
if let Some(subscription) = accounts167
.ics_subscriptions168
.iter_mut()169
.find(|subscription| subscription.id == subscription_id)170
{171
subscription.selected = !subscription.selected;172
}173
let _ = save_calendar_accounts(&self.store, &accounts);174
self.refresh_calendar(cx);175
self.load_calendar_week(cx);176
cx.notify();177
}178
36
pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {179
pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {37
let mut accounts = load_calendar_accounts(&self.store);180
let mut accounts = load_calendar_accounts(&self.store);38
accounts.home = home;181
accounts.home = home;@@ -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,33 @@ 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!(
136
"caldav:{}:{}",
137
target.account_id, target.calendar_id
138
))
139
}
101
140
}
102
141
}
103
142
@@ -108,22 +147,20 @@ mod tests {
108
147
use super::*;
109
148
110
149
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(),
150
let mut accounts = CalendarAccounts::default();
151
accounts.home = CalendarRef::google("g1", "primary");
152
accounts.google_accounts.push(GoogleAccount {
153
id: "g1".into(),
154
email: "joe@example.com".into(),
155
calendars: vec![GoogleCalendarInfo {
156
id: "primary".into(),
157
summary: "Joe".into(),
158
selected: true,
159
primary: true,
125
160
}],
126
}
161
tokens: GoogleTokenSet::default(),
162
});
163
accounts
127
164
}
128
165
129
166
#[test]
@@ -142,6 +179,13 @@ mod tests {
142
179
assert!(needs_join_first(&google_home()));
143
180
}
144
181
182
#[test]
183
fn caldav_only_home_needs_join_first() {
184
let mut accounts = CalendarAccounts::default();
185
accounts.home = CalendarRef::caldav("c1", "/cal/");
186
assert!(needs_join_first(&accounts));
187
}
188
145
189
#[test]
146
190
fn outlook_home_with_google_extra_needs_join_first() {
147
191
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.10
pub fn needs_join_first(accounts: &CalendarAccounts) -> bool {10
pub fn needs_join_first(accounts: &CalendarAccounts) -> bool {11
let targets = accounts.resolved_write_targets();11
accounts12
targets.len() > 112
.resolved_write_targets()13
|| targets13
.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 = targets43
.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
.await57
{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 => launcher92
CalendarProvider::Outlook => launcher@@ -98,6 +110,33 @@ 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> = event115
.attendees116
.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!(136
"caldav:{}:{}",137
target.account_id, target.calendar_id138
))139
}101
}140
}102
}141
}103
142
@@ -108,22 +147,20 @@ mod tests {108
use super::*;147
use super::*;109
148
110
fn google_home() -> CalendarAccounts {149
fn google_home() -> CalendarAccounts {111
CalendarAccounts {150
let mut accounts = CalendarAccounts::default();112
home: CalendarRef::google("g1", "primary"),151
accounts.home = CalendarRef::google("g1", "primary");113
write_targets: Vec::new(),152
accounts.google_accounts.push(GoogleAccount {114
outlook_selected: true,153
id: "g1".into(),115
google_accounts: vec![GoogleAccount {154
email: "joe@example.com".into(),116
id: "g1".into(),155
calendars: vec![GoogleCalendarInfo {117
email: "joe@example.com".into(),156
id: "primary".into(),118
calendars: vec![GoogleCalendarInfo {157
summary: "Joe".into(),119
id: "primary".into(),158
selected: true,120
summary: "Joe".into(),159
primary: true,121
selected: true,122
primary: true,123
}],124
tokens: GoogleTokenSet::default(),125
}],160
}],126
}161
tokens: GoogleTokenSet::default(),162
});163
accounts127
}164
}128
165
129
#[test]166
#[test]@@ -142,6 +179,13 @@ mod tests {142
assert!(needs_join_first(&google_home()));179
assert!(needs_join_first(&google_home()));143
}180
}144
181
182
#[test]183
fn caldav_only_home_needs_join_first() {184
let mut accounts = CalendarAccounts::default();185
accounts.home = CalendarRef::caldav("c1", "/cal/");186
assert!(needs_join_first(&accounts));187
}188
145
#[test]189
#[test]146
fn outlook_home_with_google_extra_needs_join_first() {190
fn outlook_home_with_google_extra_needs_join_first() {147
let mut accounts = CalendarAccounts::default();191
let mut accounts = CalendarAccounts::default();@@ -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;@@ -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
@@ -283,6 +283,8 @@ impl AppState {
283
283
let source = event.source;
284
284
let account_id = event.account_id.clone();
285
285
let calendar_id = event.calendar_id.clone();
286
let series = event.series;
287
let occurrence_start = event.start;
286
288
self.remove_calendar_event(&event_id);
287
289
cx.notify();
288
290
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
@@ -316,6 +318,24 @@ impl AppState {
316
318
let _ = store::save_calendar_accounts(&store, &accounts);
317
319
result
318
320
}
321
chatsvc::CalendarSource::CalDav => {
322
let mut accounts = store::load_calendar_accounts(&store);
323
let account =
324
account_id.ok_or_else(|| "CalDAV account missing".to_owned())?;
325
let result = crate::caldav_sync::delete_caldav_event(
326
&mut accounts,
327
&account,
328
&event_id,
329
series,
330
occurrence_start,
331
)
332
.await;
333
let _ = store::save_calendar_accounts(&store, &accounts);
334
result
335
}
336
chatsvc::CalendarSource::Ics => {
337
Err("Read-only ICS subscriptions cannot delete events".into())
338
}
319
339
}
320
340
}
321
341
});
@@ -544,6 +564,25 @@ impl AppState {
544
564
let _ = store::save_calendar_accounts(&store, &accounts);
545
565
result
546
566
}
567
chatsvc::CalendarSource::CalDav => {
568
let mut accounts = store::load_calendar_accounts(&store);
569
let account =
570
account_id.ok_or_else(|| "CalDAV account missing".to_owned())?;
571
let href = chatsvc::href_from_object_id(&event_id).to_owned();
572
let result = crate::caldav_sync::respond_caldav_event(
573
&mut accounts,
574
&account,
575
&href,
576
reply,
577
)
578
.await
579
.map(|_| ());
580
let _ = store::save_calendar_accounts(&store, &accounts);
581
result
582
}
583
chatsvc::CalendarSource::Ics => {
584
Err("Read-only ICS subscriptions cannot RSVP".into())
585
}
547
586
}
548
587
}
549
588
});
@@ -283,6 +283,8 @@ impl AppState {283
let source = event.source;283
let source = event.source;284
let account_id = event.account_id.clone();284
let account_id = event.account_id.clone();285
let calendar_id = event.calendar_id.clone();285
let calendar_id = event.calendar_id.clone();286
let series = event.series;287
let occurrence_start = event.start;286
self.remove_calendar_event(&event_id);288
self.remove_calendar_event(&event_id);287
cx.notify();289
cx.notify();288
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);290
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);@@ -316,6 +318,24 @@ impl AppState {316
let _ = store::save_calendar_accounts(&store, &accounts);318
let _ = store::save_calendar_accounts(&store, &accounts);317
result319
result318
}320
}321
chatsvc::CalendarSource::CalDav => {322
let mut accounts = store::load_calendar_accounts(&store);323
let account =324
account_id.ok_or_else(|| "CalDAV account missing".to_owned())?;325
let result = crate::caldav_sync::delete_caldav_event(326
&mut accounts,327
&account,328
&event_id,329
series,330
occurrence_start,331
)332
.await;333
let _ = store::save_calendar_accounts(&store, &accounts);334
result335
}336
chatsvc::CalendarSource::Ics => {337
Err("Read-only ICS subscriptions cannot delete events".into())338
}319
}339
}320
}340
}321
});341
});@@ -544,6 +564,25 @@ impl AppState {544
let _ = store::save_calendar_accounts(&store, &accounts);564
let _ = store::save_calendar_accounts(&store, &accounts);545
result565
result546
}566
}567
chatsvc::CalendarSource::CalDav => {568
let mut accounts = store::load_calendar_accounts(&store);569
let account =570
account_id.ok_or_else(|| "CalDAV account missing".to_owned())?;571
let href = chatsvc::href_from_object_id(&event_id).to_owned();572
let result = crate::caldav_sync::respond_caldav_event(573
&mut accounts,574
&account,575
&href,576
reply,577
)578
.await579
.map(|_| ());580
let _ = store::save_calendar_accounts(&store, &accounts);581
result582
}583
chatsvc::CalendarSource::Ics => {584
Err("Read-only ICS subscriptions cannot RSVP".into())585
}547
}586
}548
}587
}549
});588
});@@ -274,15 +274,55 @@ 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, partial)) => {
282
let _ = store::merge_caldav_metadata(&store, &fetched_accounts);
283
caldav_count = Some(events.len());
284
combined.extend(events);
285
for message in partial {
286
failures.push(CalendarLoadFailure {
287
source: CalendarSource::CalDav,
288
message,
289
});
290
}
291
}
292
Err(error) => failures.push(CalendarLoadFailure {
293
source: CalendarSource::CalDav,
294
message: error,
295
}),
296
}
297
}
298
if accounts.has_ics() {
299
match crate::ics_sync::fetch_ics_events(&accounts, from, to).await {
300
Ok((events, partial)) => {
301
combined.extend(events);
302
for message in partial {
303
failures.push(CalendarLoadFailure {
304
source: CalendarSource::Ics,
305
message,
306
});
307
}
308
}
309
Err(error) => failures.push(CalendarLoadFailure {
310
source: CalendarSource::Ics,
311
message: error,
312
}),
313
}
314
}
277
315
crate::diagnostics::record(load_summary(
278
316
from,
279
317
to,
280
318
outlook_count,
281
319
google_count,
320
caldav_count,
282
321
started.elapsed().as_millis(),
283
322
&failures,
284
323
));
285
(chatsvc::merge_calendar_events(combined), failures)
324
let home = home_calendar(&accounts);
325
(chatsvc::merge_calendar_events(combined, home), failures)
286
326
});
287
327
cx.spawn(async move |this, cx| {
288
328
let loaded = receiver.await.unwrap_or_else(|_| {
@@ -314,12 +354,17 @@ impl AppState {
314
354
}
315
355
316
356
/// A source that failed keeps its previous events on screen instead of blanking the week.
357
/// When the round already returned some events for that source (partial calendar failure),
358
/// previous events are left out so successful calendars are not duplicated.
317
359
pub(crate) fn keep_failed_sources(
318
360
previous: &[CalendarEvent],
319
361
mut events: Vec<CalendarEvent>,
320
362
failures: &[CalendarLoadFailure],
321
363
) -> Vec<CalendarEvent> {
322
364
for failure in failures {
365
if events.iter().any(|event| event.source == failure.source) {
366
continue;
367
}
323
368
events.extend(
324
369
previous
325
370
.iter()
@@ -337,16 +382,18 @@ pub(crate) fn load_summary(
337
382
to: chrono::DateTime<chrono::Utc>,
338
383
outlook: Option<usize>,
339
384
google: Option<usize>,
385
caldav: Option<usize>,
340
386
elapsed_ms: u128,
341
387
failures: &[CalendarLoadFailure],
342
388
) -> String {
343
389
let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
344
390
let mut line = format!(
345
"calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",
391
"calendar grid: {}..{} outlook={} google={} caldav={} in {elapsed_ms} ms",
346
392
from.format("%Y-%m-%dT%H:%MZ"),
347
393
to.format("%Y-%m-%dT%H:%MZ"),
348
394
count(outlook),
349
395
count(google),
396
count(caldav),
350
397
);
351
398
for failure in failures {
352
399
line.push_str(&format!(
@@ -358,6 +405,20 @@ pub(crate) fn load_summary(
358
405
line
359
406
}
360
407
408
fn home_calendar(accounts: &store::CalendarAccounts) -> Option<chatsvc::HomeCalendar<'_>> {
409
use store::CalendarProvider;
410
let source = match accounts.home.provider {
411
CalendarProvider::Outlook => CalendarSource::Outlook,
412
CalendarProvider::Google => CalendarSource::Google,
413
CalendarProvider::CalDav => CalendarSource::CalDav,
414
};
415
Some(chatsvc::HomeCalendar {
416
source,
417
account_id: accounts.home.account_id.as_str(),
418
calendar_id: accounts.home.calendar_id.as_str(),
419
})
420
}
421
361
422
fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
362
423
for event in events {
363
424
let Some(old) = previous
@@ -633,6 +694,24 @@ mod tests {
633
694
assert_eq!(ids, ["google-new"]);
634
695
}
635
696
697
#[test]
698
fn a_partial_source_failure_does_not_duplicate_fresh_events() {
699
let previous = vec![
700
event("caldav-old-a", CalendarSource::CalDav, 9),
701
event("caldav-old-b", CalendarSource::CalDav, 10),
702
];
703
let fresh = vec![event("caldav-new", CalendarSource::CalDav, 8)];
704
let failures = [CalendarLoadFailure {
705
source: CalendarSource::CalDav,
706
message: "CalDAV Work: timeout".into(),
707
}];
708
let ids: Vec<_> = keep_failed_sources(&previous, fresh, &failures)
709
.into_iter()
710
.map(|event| event.object_id)
711
.collect();
712
assert_eq!(ids, ["caldav-new"]);
713
}
714
636
715
#[test]
637
716
fn the_load_summary_names_counts_and_failures() {
638
717
let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
@@ -642,8 +721,8 @@ mod tests {
642
721
message: "client_secret is missing".into(),
643
722
}];
644
723
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; \
724
load_summary(from, to, Some(3), None, None, 412, &failures),
725
"calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- caldav=- in 412 ms; \
647
726
Google failed: client_secret is missing"
648
727
);
649
728
}
@@ -274,15 +274,55 @@ 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).await280
{281
Ok((events, partial)) => {282
let _ = store::merge_caldav_metadata(&store, &fetched_accounts);283
caldav_count = Some(events.len());284
combined.extend(events);285
for message in partial {286
failures.push(CalendarLoadFailure {287
source: CalendarSource::CalDav,288
message,289
});290
}291
}292
Err(error) => failures.push(CalendarLoadFailure {293
source: CalendarSource::CalDav,294
message: error,295
}),296
}297
}298
if accounts.has_ics() {299
match crate::ics_sync::fetch_ics_events(&accounts, from, to).await {300
Ok((events, partial)) => {301
combined.extend(events);302
for message in partial {303
failures.push(CalendarLoadFailure {304
source: CalendarSource::Ics,305
message,306
});307
}308
}309
Err(error) => failures.push(CalendarLoadFailure {310
source: CalendarSource::Ics,311
message: error,312
}),313
}314
}277
crate::diagnostics::record(load_summary(315
crate::diagnostics::record(load_summary(278
from,316
from,279
to,317
to,280
outlook_count,318
outlook_count,281
google_count,319
google_count,320
caldav_count,282
started.elapsed().as_millis(),321
started.elapsed().as_millis(),283
&failures,322
&failures,284
));323
));285
(chatsvc::merge_calendar_events(combined), failures)324
let home = home_calendar(&accounts);325
(chatsvc::merge_calendar_events(combined, home), failures)286
});326
});287
cx.spawn(async move |this, cx| {327
cx.spawn(async move |this, cx| {288
let loaded = receiver.await.unwrap_or_else(|_| {328
let loaded = receiver.await.unwrap_or_else(|_| {@@ -314,12 +354,17 @@ impl AppState {314
}354
}315
355
316
/// A source that failed keeps its previous events on screen instead of blanking the week.356
/// A source that failed keeps its previous events on screen instead of blanking the week.357
/// When the round already returned some events for that source (partial calendar failure),358
/// previous events are left out so successful calendars are not duplicated.317
pub(crate) fn keep_failed_sources(359
pub(crate) fn keep_failed_sources(318
previous: &[CalendarEvent],360
previous: &[CalendarEvent],319
mut events: Vec<CalendarEvent>,361
mut events: Vec<CalendarEvent>,320
failures: &[CalendarLoadFailure],362
failures: &[CalendarLoadFailure],321
) -> Vec<CalendarEvent> {363
) -> Vec<CalendarEvent> {322
for failure in failures {364
for failure in failures {365
if events.iter().any(|event| event.source == failure.source) {366
continue;367
}323
events.extend(368
events.extend(324
previous369
previous325
.iter()370
.iter()@@ -337,16 +382,18 @@ pub(crate) fn load_summary(337
to: chrono::DateTime<chrono::Utc>,382
to: chrono::DateTime<chrono::Utc>,338
outlook: Option<usize>,383
outlook: Option<usize>,339
google: Option<usize>,384
google: Option<usize>,385
caldav: Option<usize>,340
elapsed_ms: u128,386
elapsed_ms: u128,341
failures: &[CalendarLoadFailure],387
failures: &[CalendarLoadFailure],342
) -> String {388
) -> String {343
let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());389
let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());344
let mut line = format!(390
let mut line = format!(345
"calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",391
"calendar grid: {}..{} outlook={} google={} caldav={} in {elapsed_ms} ms",346
from.format("%Y-%m-%dT%H:%MZ"),392
from.format("%Y-%m-%dT%H:%MZ"),347
to.format("%Y-%m-%dT%H:%MZ"),393
to.format("%Y-%m-%dT%H:%MZ"),348
count(outlook),394
count(outlook),349
count(google),395
count(google),396
count(caldav),350
);397
);351
for failure in failures {398
for failure in failures {352
line.push_str(&format!(399
line.push_str(&format!(@@ -358,6 +405,20 @@ pub(crate) fn load_summary(358
line405
line359
}406
}360
407
408
fn home_calendar(accounts: &store::CalendarAccounts) -> Option<chatsvc::HomeCalendar<'_>> {409
use store::CalendarProvider;410
let source = match accounts.home.provider {411
CalendarProvider::Outlook => CalendarSource::Outlook,412
CalendarProvider::Google => CalendarSource::Google,413
CalendarProvider::CalDav => CalendarSource::CalDav,414
};415
Some(chatsvc::HomeCalendar {416
source,417
account_id: accounts.home.account_id.as_str(),418
calendar_id: accounts.home.calendar_id.as_str(),419
})420
}421
361
fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {422
fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {362
for event in events {423
for event in events {363
let Some(old) = previous424
let Some(old) = previous@@ -633,6 +694,24 @@ mod tests {633
assert_eq!(ids, ["google-new"]);694
assert_eq!(ids, ["google-new"]);634
}695
}635
696
697
#[test]698
fn a_partial_source_failure_does_not_duplicate_fresh_events() {699
let previous = vec![700
event("caldav-old-a", CalendarSource::CalDav, 9),701
event("caldav-old-b", CalendarSource::CalDav, 10),702
];703
let fresh = vec![event("caldav-new", CalendarSource::CalDav, 8)];704
let failures = [CalendarLoadFailure {705
source: CalendarSource::CalDav,706
message: "CalDAV Work: timeout".into(),707
}];708
let ids: Vec<_> = keep_failed_sources(&previous, fresh, &failures)709
.into_iter()710
.map(|event| event.object_id)711
.collect();712
assert_eq!(ids, ["caldav-new"]);713
}714
636
#[test]715
#[test]637
fn the_load_summary_names_counts_and_failures() {716
fn the_load_summary_names_counts_and_failures() {638
let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();717
let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();@@ -642,8 +721,8 @@ mod tests {642
message: "client_secret is missing".into(),721
message: "client_secret is missing".into(),643
}];722
}];644
assert_eq!(723
assert_eq!(645
load_summary(from, to, Some(3), None, 412, &failures),724
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; \725
"calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- caldav=- in 412 ms; \647
Google failed: client_secret is missing"726
Google failed: client_secret is missing"648
);727
);649
}728
}@@ -0,0 +1,165 @@
1
//! Read-only ICS subscriptions (holidays, Proton share links).
2
3
use std::collections::HashSet;
4
use std::time::Duration;
5
6
use chrono::{DateTime, Utc};
7
use store::{CalendarAccounts, IcsSubscription};
8
use uuid::Uuid;
9
10
use chatsvc::{CalendarEvent, CalendarSource, expand_events, object_id_for, parse_calendar};
11
12
const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);
13
14
pub async fn add_ics_subscription(
15
accounts: &mut CalendarAccounts,
16
url: &str,
17
summary: &str,
18
) -> Result<String, String> {
19
let url = normalize_ics_url(url)?;
20
// Smoke-fetch once so a bad URL fails at connect time.
21
let _ = fetch_one(
22
&url,
23
"tmp",
24
summary,
25
Utc::now(),
26
Utc::now() + chrono::Duration::days(1),
27
)
28
.await?;
29
let id = Uuid::new_v4().to_string();
30
accounts.ics_subscriptions.push(IcsSubscription {
31
id: id.clone(),
32
url,
33
summary: if summary.trim().is_empty() {
34
"ICS".into()
35
} else {
36
summary.to_owned()
37
},
38
selected: true,
39
});
40
Ok(id)
41
}
42
43
/// Events plus per-subscription failure messages.
44
pub async fn fetch_ics_events(
45
accounts: &CalendarAccounts,
46
start: DateTime<Utc>,
47
end: DateTime<Utc>,
48
) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {
49
let mut all = Vec::new();
50
let mut failures = Vec::new();
51
for subscription in accounts
52
.ics_subscriptions
53
.iter()
54
.filter(|subscription| subscription.selected)
55
{
56
let url = match normalize_ics_url(&subscription.url) {
57
Ok(url) => url,
58
Err(error) => {
59
failures.push(format!("ICS {}: {error}", subscription.summary));
60
continue;
61
}
62
};
63
match fetch_one(&url, &subscription.id, &subscription.summary, start, end).await {
64
Ok(events) => all.extend(events),
65
Err(error) => failures.push(format!("ICS {}: {error}", subscription.summary)),
66
}
67
}
68
Ok((all, failures))
69
}
70
71
pub fn normalize_ics_url(url: &str) -> Result<String, String> {
72
let trimmed = url.trim();
73
if trimmed.is_empty() {
74
return Err("ICS URL is empty".into());
75
}
76
let lowered = trimmed.to_ascii_lowercase();
77
let with_scheme = if let Some(rest) = lowered.strip_prefix("webcals://") {
78
format!("https://{}", &trimmed[trimmed.len() - rest.len()..])
79
} else if let Some(rest) = lowered.strip_prefix("webcal://") {
80
format!("https://{}", &trimmed[trimmed.len() - rest.len()..])
81
} else if trimmed.contains("://") {
82
trimmed.to_owned()
83
} else {
84
format!("https://{trimmed}")
85
};
86
let parsed = url::Url::parse(&with_scheme).map_err(|e| e.to_string())?;
87
if parsed.scheme() != "https" && parsed.scheme() != "http" {
88
return Err(format!("Unsupported ICS URL scheme: {}", parsed.scheme()));
89
}
90
Ok(parsed.to_string())
91
}
92
93
async fn fetch_one(
94
url: &str,
95
account_id: &str,
96
calendar_name: &str,
97
start: DateTime<Utc>,
98
end: DateTime<Utc>,
99
) -> Result<Vec<CalendarEvent>, String> {
100
let client = reqwest::Client::builder()
101
.timeout(REQUEST_TIMEOUT)
102
.build()
103
.map_err(|e| e.to_string())?;
104
let response = client.get(url).send().await.map_err(|e| e.to_string())?;
105
if !response.status().is_success() {
106
return Err(format!("HTTP {}", response.status()));
107
}
108
let body = response.text().await.map_err(|e| e.to_string())?;
109
let parsed = parse_calendar(&body);
110
let series_uids: HashSet<String> = parsed
111
.iter()
112
.filter(|event| {
113
event.rrule.is_some() || !event.rdates.is_empty() || event.recurrence_id.is_some()
114
})
115
.map(|event| event.uid.clone())
116
.collect();
117
let expanded = expand_events(parsed, start, end);
118
Ok(expanded
119
.into_iter()
120
.map(|item| {
121
let series = series_uids.contains(&item.uid) || item.recurrence_id.is_some();
122
let object_id =
123
object_id_for(&format!("ics:{account_id}"), &item.uid, series, item.start);
124
CalendarEvent {
125
object_id,
126
subject: item.summary,
127
start: item.start,
128
end: item.end,
129
all_day: item.all_day,
130
cancelled: item.cancelled,
131
online: item.join_url.is_some(),
132
join_url: item.join_url,
133
ical_uid: Some(item.uid),
134
source: CalendarSource::Ics,
135
account_id: Some(account_id.to_owned()),
136
calendar_id: Some(url.to_owned()),
137
sources: vec![CalendarSource::Ics],
138
location: item.location,
139
body_preview: item.description.clone(),
140
body_html: item.description,
141
reminders: item.reminders_minutes,
142
calendar_name: Some(calendar_name.to_owned()),
143
series,
144
..Default::default()
145
}
146
})
147
.collect())
148
}
149
150
#[cfg(test)]
151
mod tests {
152
use super::*;
153
154
#[test]
155
fn webcal_becomes_https() {
156
assert_eq!(
157
normalize_ics_url("webcal://calendar.example/feed.ics").unwrap(),
158
"https://calendar.example/feed.ics"
159
);
160
assert_eq!(
161
normalize_ics_url("webcals://calendar.example/feed.ics").unwrap(),
162
"https://calendar.example/feed.ics"
163
);
164
}
165
}
@@ -0,0 +1,165 @@1
//! Read-only ICS subscriptions (holidays, Proton share links).2
3
use std::collections::HashSet;4
use std::time::Duration;5
6
use chrono::{DateTime, Utc};7
use store::{CalendarAccounts, IcsSubscription};8
use uuid::Uuid;9
10
use chatsvc::{CalendarEvent, CalendarSource, expand_events, object_id_for, parse_calendar};11
12
const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);13
14
pub async fn add_ics_subscription(15
accounts: &mut CalendarAccounts,16
url: &str,17
summary: &str,18
) -> Result<String, String> {19
let url = normalize_ics_url(url)?;20
// Smoke-fetch once so a bad URL fails at connect time.21
let _ = fetch_one(22
&url,23
"tmp",24
summary,25
Utc::now(),26
Utc::now() + chrono::Duration::days(1),27
)28
.await?;29
let id = Uuid::new_v4().to_string();30
accounts.ics_subscriptions.push(IcsSubscription {31
id: id.clone(),32
url,33
summary: if summary.trim().is_empty() {34
"ICS".into()35
} else {36
summary.to_owned()37
},38
selected: true,39
});40
Ok(id)41
}42
43
/// Events plus per-subscription failure messages.44
pub async fn fetch_ics_events(45
accounts: &CalendarAccounts,46
start: DateTime<Utc>,47
end: DateTime<Utc>,48
) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {49
let mut all = Vec::new();50
let mut failures = Vec::new();51
for subscription in accounts52
.ics_subscriptions53
.iter()54
.filter(|subscription| subscription.selected)55
{56
let url = match normalize_ics_url(&subscription.url) {57
Ok(url) => url,58
Err(error) => {59
failures.push(format!("ICS {}: {error}", subscription.summary));60
continue;61
}62
};63
match fetch_one(&url, &subscription.id, &subscription.summary, start, end).await {64
Ok(events) => all.extend(events),65
Err(error) => failures.push(format!("ICS {}: {error}", subscription.summary)),66
}67
}68
Ok((all, failures))69
}70
71
pub fn normalize_ics_url(url: &str) -> Result<String, String> {72
let trimmed = url.trim();73
if trimmed.is_empty() {74
return Err("ICS URL is empty".into());75
}76
let lowered = trimmed.to_ascii_lowercase();77
let with_scheme = if let Some(rest) = lowered.strip_prefix("webcals://") {78
format!("https://{}", &trimmed[trimmed.len() - rest.len()..])79
} else if let Some(rest) = lowered.strip_prefix("webcal://") {80
format!("https://{}", &trimmed[trimmed.len() - rest.len()..])81
} else if trimmed.contains("://") {82
trimmed.to_owned()83
} else {84
format!("https://{trimmed}")85
};86
let parsed = url::Url::parse(&with_scheme).map_err(|e| e.to_string())?;87
if parsed.scheme() != "https" && parsed.scheme() != "http" {88
return Err(format!("Unsupported ICS URL scheme: {}", parsed.scheme()));89
}90
Ok(parsed.to_string())91
}92
93
async fn fetch_one(94
url: &str,95
account_id: &str,96
calendar_name: &str,97
start: DateTime<Utc>,98
end: DateTime<Utc>,99
) -> Result<Vec<CalendarEvent>, String> {100
let client = reqwest::Client::builder()101
.timeout(REQUEST_TIMEOUT)102
.build()103
.map_err(|e| e.to_string())?;104
let response = client.get(url).send().await.map_err(|e| e.to_string())?;105
if !response.status().is_success() {106
return Err(format!("HTTP {}", response.status()));107
}108
let body = response.text().await.map_err(|e| e.to_string())?;109
let parsed = parse_calendar(&body);110
let series_uids: HashSet<String> = parsed111
.iter()112
.filter(|event| {113
event.rrule.is_some() || !event.rdates.is_empty() || event.recurrence_id.is_some()114
})115
.map(|event| event.uid.clone())116
.collect();117
let expanded = expand_events(parsed, start, end);118
Ok(expanded119
.into_iter()120
.map(|item| {121
let series = series_uids.contains(&item.uid) || item.recurrence_id.is_some();122
let object_id =123
object_id_for(&format!("ics:{account_id}"), &item.uid, series, item.start);124
CalendarEvent {125
object_id,126
subject: item.summary,127
start: item.start,128
end: item.end,129
all_day: item.all_day,130
cancelled: item.cancelled,131
online: item.join_url.is_some(),132
join_url: item.join_url,133
ical_uid: Some(item.uid),134
source: CalendarSource::Ics,135
account_id: Some(account_id.to_owned()),136
calendar_id: Some(url.to_owned()),137
sources: vec![CalendarSource::Ics],138
location: item.location,139
body_preview: item.description.clone(),140
body_html: item.description,141
reminders: item.reminders_minutes,142
calendar_name: Some(calendar_name.to_owned()),143
series,144
..Default::default()145
}146
})147
.collect())148
}149
150
#[cfg(test)]151
mod tests {152
use super::*;153
154
#[test]155
fn webcal_becomes_https() {156
assert_eq!(157
normalize_ics_url("webcal://calendar.example/feed.ics").unwrap(),158
"https://calendar.example/feed.ics"159
);160
assert_eq!(161
normalize_ics_url("webcals://calendar.example/feed.ics").unwrap(),162
"https://calendar.example/feed.ics"163
);164
}165
}@@ -6,6 +6,8 @@ pub mod app_state;
6
6
pub mod backend;
7
7
pub mod banner_image;
8
8
pub mod browser_sign_in;
9
pub mod caldav_credentials;
10
pub mod caldav_sync;
9
11
pub mod calendar_accounts_actions;
10
12
pub mod call;
11
13
pub mod call_rows;
@@ -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;
@@ -6,6 +6,8 @@ pub mod app_state;6
pub mod backend;6
pub mod backend;7
pub mod banner_image;7
pub mod banner_image;8
pub mod browser_sign_in;8
pub mod browser_sign_in;9
pub mod caldav_credentials;10
pub mod caldav_sync;9
pub mod calendar_accounts_actions;11
pub mod calendar_accounts_actions;10
pub mod call;12
pub mod call;11
pub mod call_rows;13
pub mod call_rows;@@ -32,6 +34,7 @@ pub mod find_in_chat;32
pub mod forward_selection;34
pub mod forward_selection;33
pub mod gifs;35
pub mod gifs;34
pub mod google_calendar_sync;36
pub mod google_calendar_sync;37
pub mod ics_sync;35
pub mod image_view_gallery;38
pub mod image_view_gallery;36
pub mod importance;39
pub mod importance;37
pub mod local_previews;40
pub mod local_previews;@@ -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,@@ -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
@@ -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,@@ -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 @@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
}@@ -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, Weekend18
use crate::i18n::tr;18
use crate::i18n::tr;19
use crate::theme;19
use crate::theme;20
20
21
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {21
pub 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
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
.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 = body62
body = body39
.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
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 = accounts261
.write_targets262
.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
block303
}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
fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {341
fn 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) -> D248
);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
choices404
choices252
}405
}253
406
@@ -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};6
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::prelude::FluentBuilder as _;7
use gpui_kit::*;7
use gpui_kit::*;8
8
9
use super::caldav_form::{CalDavForm, IcsForm};9
use super::devices::DevicesView;10
use super::devices::DevicesView;10
use super::help::HelpView;11
use super::help::HelpView;11
use super::mcp::McpView;12
use 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 => self229
SettingsSection::Devices => self208
.devices230
.devices209
.clone()231
.clone()@@ -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 @@1
mod about;1
mod about;2
mod account;2
mod account;3
mod appearance;3
mod appearance;4
mod caldav_form;4
mod calendar;5
mod calendar;5
mod calls;6
mod calls;6
mod chats;7
mod chats;@@ -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.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
pub fn toggle_row(153
pub fn toggle_row(120
id: impl Into<ElementId>,154
id: impl Into<ElementId>,121
title: impl Into<SharedString>,155
title: impl Into<SharedString>,@@ -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 _};10
use gpui_kit::component::{h_flex, v_flex};10
use gpui_kit::component::{h_flex, v_flex};11
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::*;12
use gpui_kit::*;13
use store::{CalendarAccounts, GoogleAccount};13
use store::{CalDavAccount, CalendarAccounts, GoogleAccount, IcsSubscription};14
14
15
use super::calendar_mini_month::mini_month_grid;15
use super::calendar_mini_month::mini_month_grid;16
use crate::app_state::AppState;16
use 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
column82
column72
}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
body286
body276
}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> = account296
.calendars297
.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 = accounts321
.google_accounts322
.iter()323
.map(|account| account.calendars.len())324
.sum::<usize>()325
+ 1326
+ accounts327
.caldav_accounts328
.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
body345
}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
/// 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.279
fn group(364
fn group(280
id: String,365
id: String,@@ -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 = true8
[dependencies]8
[dependencies]9
base64.workspace = true9
base64.workspace = true10
chrono.workspace = true10
chrono.workspace = true11
chrono-tz = "0.10"11
iana-time-zone = "0.1"12
iana-time-zone = "0.1"12
futures-util.workspace = true13
futures-util.workspace = true13
percent-encoding.workspace = true14
percent-encoding.workspace = true15
quick-xml = "0.37"14
rand = "0.9"16
rand = "0.9"15
reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }17
reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }18
rrule = "0.14"16
serde.workspace = true19
serde.workspace = true17
serde_json.workspace = true20
serde_json.workspace = true18
session.workspace = true21
session.workspace = true@@ -0,0 +1,527 @@
1
use std::collections::HashSet;
2
use std::time::Duration;
3
4
use chrono::{DateTime, Utc};
5
use reqwest::{Client, Method, StatusCode, header};
6
use uuid::Uuid;
7
8
use crate::calendar::{
9
AttendeeResponseCounts, CalendarEvent, CalendarSource, EventAttendee, ResponseType, ShowAs,
10
};
11
use crate::error::{Error, Result};
12
use crate::ical::{CalDavEventDraft, exclude_occurrence_from_ics, expand_events, parse_calendar};
13
14
use super::discovery::{DiscoverResult, discover, reject_https_downgrade, resolve_url};
15
use super::xml::{calendar_query_body, parse_calendar_query, parse_multistatus, propfind_body};
16
17
const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);
18
19
#[derive(Debug, Clone)]
20
pub struct ListedCalendar {
21
pub href: String,
22
pub summary: String,
23
pub color: Option<String>,
24
pub writable: bool,
25
}
26
27
#[derive(Debug, Clone)]
28
pub struct CalDavEvent {
29
pub event: CalendarEvent,
30
pub href: String,
31
pub etag: Option<String>,
32
}
33
34
pub struct CalDavClient {
35
http: Client,
36
username: String,
37
password: String,
38
}
39
40
impl CalDavClient {
41
pub fn new(username: impl Into<String>, password: impl Into<String>) -> Result<Self> {
42
let http = Client::builder()
43
.timeout(REQUEST_TIMEOUT)
44
.redirect(reqwest::redirect::Policy::custom(|attempt| {
45
let previous = attempt.previous().last().map(|u| u.as_str()).unwrap_or("");
46
let next = attempt.url().as_str();
47
if previous.starts_with("https://") && next.starts_with("http://") {
48
attempt.error(std::io::Error::other("https downgrade"))
49
} else if attempt.previous().len() > 10 {
50
attempt.stop()
51
} else {
52
attempt.follow()
53
}
54
}))
55
.build()
56
.map_err(map_reqwest)?;
57
Ok(CalDavClient {
58
http,
59
username: username.into(),
60
password: password.into(),
61
})
62
}
63
64
pub async fn discover(&self, url: &str) -> Result<DiscoverResult> {
65
discover(self, url).await
66
}
67
68
pub async fn list_calendars(&self, home_set: &str) -> Result<Vec<ListedCalendar>> {
69
let body = propfind_body(&[
70
"<d:displayname/>",
71
"<d:resourcetype/>",
72
"<d:current-user-privilege-set/>",
73
"<c:supported-calendar-component-set/>",
74
"<x:calendar-color/>",
75
]);
76
let xml = self.propfind(home_set, "1", &body).await?;
77
let mut calendars = Vec::new();
78
for response in parse_multistatus(&xml) {
79
if !response.resource_type_calendar {
80
continue;
81
}
82
// Prefer VEVENT; if component set absent, still include calendar collections.
83
if !response.supports_vevent
84
&& xml.contains("supported-calendar-component-set")
85
&& response.href.contains("todo")
86
{
87
continue;
88
}
89
let href = resolve_url(home_set, &response.href)?;
90
calendars.push(ListedCalendar {
91
href,
92
summary: response
93
.displayname
94
.unwrap_or_else(|| "Calendar".to_owned()),
95
color: response.calendar_color,
96
writable: response.writable,
97
});
98
}
99
Ok(calendars)
100
}
101
102
pub async fn fetch_events(
103
&self,
104
calendar_href: &str,
105
account_id: &str,
106
calendar_name: Option<&str>,
107
from: DateTime<Utc>,
108
to: DateTime<Utc>,
109
) -> Result<Vec<CalDavEvent>> {
110
let start = from.format("%Y%m%dT%H%M%SZ").to_string();
111
let end = to.format("%Y%m%dT%H%M%SZ").to_string();
112
let mut resources = self.calendar_query(calendar_href, &start, &end, true).await;
113
if resources.is_err() {
114
resources = self
115
.calendar_query(calendar_href, &start, &end, false)
116
.await;
117
}
118
let resources = resources?;
119
let mut out = Vec::new();
120
for (href, etag, data) in resources {
121
let absolute = resolve_url(calendar_href, &href).unwrap_or(href);
122
let parsed = parse_calendar(&data);
123
let series_uids: HashSet<String> = parsed
124
.iter()
125
.filter(|event| {
126
event.rrule.is_some()
127
|| !event.rdates.is_empty()
128
|| event.recurrence_id.is_some()
129
})
130
.map(|event| event.uid.clone())
131
.collect();
132
let expanded = expand_events(parsed, from, to);
133
for item in expanded {
134
let mut event = to_calendar_event(&item, account_id, &absolute, calendar_name);
135
let uid = event.ical_uid.clone().unwrap_or_default();
136
let series = series_uids.contains(&uid) || item.recurrence_id.is_some();
137
event.series = series;
138
event.object_id = object_id_for(&absolute, &uid, series, item.start);
139
out.push(CalDavEvent {
140
event,
141
href: absolute.clone(),
142
etag: etag.clone(),
143
});
144
}
145
}
146
Ok(out)
147
}
148
149
pub async fn put_event(
150
&self,
151
calendar_href: &str,
152
draft: &CalDavEventDraft,
153
stamp: DateTime<Utc>,
154
) -> Result<String> {
155
let href = format!("{}{}.ics", ensure_trailing_slash(calendar_href), draft.uid);
156
let body = crate::ical::build_vevent(draft, stamp);
157
let response = self
158
.http
159
.put(&href)
160
.basic_auth(&self.username, Some(&self.password))
161
.header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")
162
.header(header::IF_NONE_MATCH, "*")
163
.body(body)
164
.send()
165
.await
166
.map_err(map_reqwest)?;
167
ensure_auth(response.status())?;
168
if !response.status().is_success() {
169
return Err(Error::UnexpectedAnswer(format!(
170
"CalDAV PUT failed: {}",
171
response.status()
172
)));
173
}
174
Ok(href)
175
}
176
177
pub async fn delete(&self, href: &str, etag: Option<&str>) -> Result<()> {
178
let mut request = self
179
.http
180
.delete(href)
181
.basic_auth(&self.username, Some(&self.password));
182
if let Some(etag) = etag {
183
request = request.header(header::IF_MATCH, format!("\"{etag}\""));
184
}
185
let response = request.send().await.map_err(map_reqwest)?;
186
ensure_auth(response.status())?;
187
if response.status() == StatusCode::NOT_FOUND || response.status().is_success() {
188
return Ok(());
189
}
190
Err(Error::UnexpectedAnswer(format!(
191
"CalDAV DELETE failed: {}",
192
response.status()
193
)))
194
}
195
196
/// Exclude one occurrence by EXDATE on the master; does not DELETE the series href.
197
pub async fn exclude_occurrence(
198
&self,
199
href: &str,
200
occurrence: DateTime<Utc>,
201
etag: Option<&str>,
202
) -> Result<()> {
203
let response = self
204
.http
205
.get(href)
206
.basic_auth(&self.username, Some(&self.password))
207
.send()
208
.await
209
.map_err(map_reqwest)?;
210
ensure_auth(response.status())?;
211
let fresh_etag = response
212
.headers()
213
.get(header::ETAG)
214
.and_then(|v| v.to_str().ok())
215
.map(|v| v.trim_matches('"').to_owned());
216
let body = response.text().await.map_err(map_reqwest)?;
217
let updated =
218
exclude_occurrence_from_ics(&body, occurrence).map_err(Error::UnexpectedAnswer)?;
219
let match_etag = etag.or(fresh_etag.as_deref());
220
let mut request = self
221
.http
222
.put(href)
223
.basic_auth(&self.username, Some(&self.password))
224
.header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")
225
.body(updated);
226
if let Some(etag) = match_etag {
227
request = request.header(header::IF_MATCH, format!("\"{etag}\""));
228
}
229
let response = request.send().await.map_err(map_reqwest)?;
230
if response.status() == StatusCode::PRECONDITION_FAILED {
231
return Err(Error::UnexpectedAnswer(
232
"CalDAV event changed on the server; reload and try again".into(),
233
));
234
}
235
ensure_auth(response.status())?;
236
if !response.status().is_success() {
237
return Err(Error::UnexpectedAnswer(format!(
238
"CalDAV EXDATE failed: {}",
239
response.status()
240
)));
241
}
242
Ok(())
243
}
244
245
pub async fn update_partstat(
246
&self,
247
href: &str,
248
etag: Option<&str>,
249
mailto: &str,
250
partstat: &str,
251
) -> Result<()> {
252
let response = self
253
.http
254
.get(href)
255
.basic_auth(&self.username, Some(&self.password))
256
.send()
257
.await
258
.map_err(map_reqwest)?;
259
ensure_auth(response.status())?;
260
let fresh_etag = response
261
.headers()
262
.get(header::ETAG)
263
.and_then(|v| v.to_str().ok())
264
.map(|v| v.trim_matches('"').to_owned());
265
let body = response.text().await.map_err(map_reqwest)?;
266
let updated = patch_partstat(&body, mailto, partstat);
267
let match_etag = etag.or(fresh_etag.as_deref());
268
let mut request = self
269
.http
270
.put(href)
271
.basic_auth(&self.username, Some(&self.password))
272
.header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")
273
.body(updated);
274
if let Some(etag) = match_etag {
275
request = request.header(header::IF_MATCH, format!("\"{etag}\""));
276
}
277
let response = request.send().await.map_err(map_reqwest)?;
278
if response.status() == StatusCode::PRECONDITION_FAILED {
279
return Err(Error::UnexpectedAnswer(
280
"CalDAV event changed on the server; reload and try again".into(),
281
));
282
}
283
ensure_auth(response.status())?;
284
if !response.status().is_success() {
285
return Err(Error::UnexpectedAnswer(format!(
286
"CalDAV RSVP failed: {}",
287
response.status()
288
)));
289
}
290
Ok(())
291
}
292
293
pub async fn propfind(&self, url: &str, depth: &str, body: &str) -> Result<String> {
294
let method = Method::from_bytes(b"PROPFIND").unwrap();
295
let response = self
296
.http
297
.request(method, url)
298
.basic_auth(&self.username, Some(&self.password))
299
.header("Depth", depth)
300
.header(header::CONTENT_TYPE, "application/xml; charset=utf-8")
301
.body(body.to_owned())
302
.send()
303
.await
304
.map_err(map_reqwest)?;
305
reject_https_downgrade(url, response.url().as_str())?;
306
if response.status() == StatusCode::UNAUTHORIZED {
307
let www = response
308
.headers()
309
.get(header::WWW_AUTHENTICATE)
310
.and_then(|v| v.to_str().ok())
311
.unwrap_or("");
312
if www.to_ascii_lowercase().contains("digest") {
313
return Err(Error::UnexpectedAnswer(
314
"CalDAV Digest authentication is not supported; enable Basic auth or use an app password with Basic".into(),
315
));
316
}
317
return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into()));
318
}
319
if !response.status().is_success() && response.status().as_u16() != 207 {
320
return Err(Error::UnexpectedAnswer(format!(
321
"CalDAV PROPFIND failed: {}",
322
response.status()
323
)));
324
}
325
response.text().await.map_err(map_reqwest)
326
}
327
328
async fn calendar_query(
329
&self,
330
url: &str,
331
start: &str,
332
end: &str,
333
expand: bool,
334
) -> Result<Vec<(String, Option<String>, String)>> {
335
let method = Method::from_bytes(b"REPORT").unwrap();
336
let body = calendar_query_body(start, end, expand);
337
let response = self
338
.http
339
.request(method, url)
340
.basic_auth(&self.username, Some(&self.password))
341
.header("Depth", "1")
342
.header(header::CONTENT_TYPE, "application/xml; charset=utf-8")
343
.body(body)
344
.send()
345
.await
346
.map_err(map_reqwest)?;
347
ensure_auth(response.status())?;
348
if !response.status().is_success() && response.status().as_u16() != 207 {
349
return Err(Error::UnexpectedAnswer(format!(
350
"CalDAV REPORT failed: {}",
351
response.status()
352
)));
353
}
354
let text = response.text().await.map_err(map_reqwest)?;
355
Ok(parse_calendar_query(&text))
356
}
357
}
358
359
fn to_calendar_event(
360
parsed: &crate::ical::ParsedEvent,
361
account_id: &str,
362
calendar_id: &str,
363
calendar_name: Option<&str>,
364
) -> CalendarEvent {
365
let response = own_response(parsed);
366
CalendarEvent {
367
object_id: parsed.uid.clone(),
368
subject: parsed.summary.clone(),
369
start: parsed.start,
370
end: parsed.end,
371
all_day: parsed.all_day,
372
cancelled: parsed.cancelled,
373
online: parsed.join_url.is_some(),
374
join_url: parsed.join_url.clone(),
375
thread_id: None,
376
organizer_name: parsed.organizer.as_ref().map(|(n, _)| n.clone()),
377
organizer_address: parsed.organizer.as_ref().and_then(|(_, a)| a.clone()),
378
ical_uid: Some(parsed.uid.clone()),
379
response,
380
show_as: if parsed.transparent {
381
ShowAs::Free
382
} else {
383
ShowAs::Busy
384
},
385
dial_in: None,
386
source: CalendarSource::CalDav,
387
account_id: Some(account_id.to_owned()),
388
calendar_id: Some(calendar_id.to_owned()),
389
sources: vec![CalendarSource::CalDav],
390
location: parsed.location.clone(),
391
body_preview: parsed.description.clone().map(|d| {
392
if d.chars().count() > 280 {
393
d.chars().take(280).collect()
394
} else {
395
d
396
}
397
}),
398
body_html: parsed.description.clone(),
399
// Overridden by fetch_events after expansion (RRULE is cleared on occurrences).
400
series: parsed.rrule.is_some()
401
|| !parsed.rdates.is_empty()
402
|| parsed.recurrence_id.is_some(),
403
series_master_id: None,
404
response_counts: None::<AttendeeResponseCounts>,
405
attendees: parsed
406
.attendees
407
.iter()
408
.map(|a| EventAttendee {
409
name: a.cn.clone().unwrap_or_else(|| a.mailto.clone()),
410
address: Some(a.mailto.clone()),
411
response: partstat_to_response(a.partstat.as_deref().unwrap_or("NEEDS-ACTION")),
412
required: a
413
.role
414
.as_deref()
415
.map(|r| !r.eq_ignore_ascii_case("OPT-PARTICIPANT"))
416
.unwrap_or(true),
417
})
418
.collect(),
419
reminders: parsed.reminders_minutes.clone(),
420
source_link: None,
421
web_link: None,
422
calendar_name: calendar_name.map(str::to_owned),
423
}
424
}
425
426
fn own_response(parsed: &crate::ical::ParsedEvent) -> ResponseType {
427
parsed
428
.attendees
429
.iter()
430
.find_map(|a| a.partstat.as_deref().map(partstat_to_response))
431
.unwrap_or(ResponseType::NotResponded)
432
}
433
434
fn partstat_to_response(partstat: &str) -> ResponseType {
435
match partstat.to_ascii_uppercase().as_str() {
436
"ACCEPTED" => ResponseType::Accepted,
437
"TENTATIVE" => ResponseType::Tentative,
438
"DECLINED" => ResponseType::Declined,
439
"DELEGATED" => ResponseType::NotResponded,
440
_ => ResponseType::NotResponded,
441
}
442
}
443
444
pub fn partstat_for_reply(reply: crate::calendar::Reply) -> &'static str {
445
match reply {
446
crate::calendar::Reply::Accept => "ACCEPTED",
447
crate::calendar::Reply::Tentative => "TENTATIVE",
448
crate::calendar::Reply::Decline => "DECLINED",
449
}
450
}
451
452
fn patch_partstat(ics: &str, mailto: &str, partstat: &str) -> String {
453
let target = mailto.trim_start_matches("mailto:").to_ascii_lowercase();
454
let mut out = String::with_capacity(ics.len() + 32);
455
for line in ics.lines() {
456
if line.to_ascii_uppercase().starts_with("ATTENDEE")
457
&& line.to_ascii_lowercase().contains(&target)
458
{
459
let mut rewritten = line.to_owned();
460
if let Some(start) = rewritten.to_ascii_uppercase().find("PARTSTAT=") {
461
let rest = &rewritten[start + 9..];
462
let end = rest.find([';', ':']).unwrap_or(rest.len());
463
rewritten.replace_range(start + 9..start + 9 + end, partstat);
464
} else if let Some(idx) = rewritten.find(':') {
465
rewritten.insert_str(idx, &format!(";PARTSTAT={partstat}"));
466
}
467
out.push_str(&rewritten);
468
out.push_str("\r\n");
469
} else {
470
out.push_str(line);
471
out.push_str("\r\n");
472
}
473
}
474
out
475
}
476
477
fn ensure_trailing_slash(url: &str) -> String {
478
if url.ends_with('/') {
479
url.to_owned()
480
} else {
481
format!("{url}/")
482
}
483
}
484
485
fn ensure_auth(status: StatusCode) -> Result<()> {
486
if status == StatusCode::UNAUTHORIZED {
487
return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into()));
488
}
489
Ok(())
490
}
491
492
fn map_reqwest(error: reqwest::Error) -> Error {
493
Error::UnexpectedAnswer(error.to_string())
494
}
495
496
pub fn new_event_uid() -> String {
497
format!("{}@rusty-teams", Uuid::new_v4())
498
}
499
500
pub fn object_id_for(href: &str, uid: &str, series: bool, start: DateTime<Utc>) -> String {
501
if series {
502
format!("{href}#{uid}#{}", start.format("%Y%m%dT%H%M%SZ"))
503
} else {
504
format!("{href}#{uid}")
505
}
506
}
507
508
pub fn href_from_object_id(object_id: &str) -> &str {
509
object_id.split('#').next().unwrap_or(object_id)
510
}
511
512
#[cfg(test)]
513
mod object_id_tests {
514
use super::*;
515
use chrono::TimeZone;
516
517
#[test]
518
fn series_occurrences_get_distinct_ids() {
519
let start_a = Utc.with_ymd_and_hms(2026, 1, 5, 9, 0, 0).unwrap();
520
let start_b = Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap();
521
let a = object_id_for("https://dav.example/cal/evt.ics", "series", true, start_a);
522
let b = object_id_for("https://dav.example/cal/evt.ics", "series", true, start_b);
523
assert_ne!(a, b);
524
assert!(a.ends_with("#20260105T090000Z"));
525
assert_eq!(href_from_object_id(&a), "https://dav.example/cal/evt.ics");
526
}
527
}
@@ -0,0 +1,527 @@1
use std::collections::HashSet;2
use std::time::Duration;3
4
use chrono::{DateTime, Utc};5
use reqwest::{Client, Method, StatusCode, header};6
use uuid::Uuid;7
8
use crate::calendar::{9
AttendeeResponseCounts, CalendarEvent, CalendarSource, EventAttendee, ResponseType, ShowAs,10
};11
use crate::error::{Error, Result};12
use crate::ical::{CalDavEventDraft, exclude_occurrence_from_ics, expand_events, parse_calendar};13
14
use super::discovery::{DiscoverResult, discover, reject_https_downgrade, resolve_url};15
use super::xml::{calendar_query_body, parse_calendar_query, parse_multistatus, propfind_body};16
17
const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);18
19
#[derive(Debug, Clone)]20
pub struct ListedCalendar {21
pub href: String,22
pub summary: String,23
pub color: Option<String>,24
pub writable: bool,25
}26
27
#[derive(Debug, Clone)]28
pub struct CalDavEvent {29
pub event: CalendarEvent,30
pub href: String,31
pub etag: Option<String>,32
}33
34
pub struct CalDavClient {35
http: Client,36
username: String,37
password: String,38
}39
40
impl CalDavClient {41
pub fn new(username: impl Into<String>, password: impl Into<String>) -> Result<Self> {42
let http = Client::builder()43
.timeout(REQUEST_TIMEOUT)44
.redirect(reqwest::redirect::Policy::custom(|attempt| {45
let previous = attempt.previous().last().map(|u| u.as_str()).unwrap_or("");46
let next = attempt.url().as_str();47
if previous.starts_with("https://") && next.starts_with("http://") {48
attempt.error(std::io::Error::other("https downgrade"))49
} else if attempt.previous().len() > 10 {50
attempt.stop()51
} else {52
attempt.follow()53
}54
}))55
.build()56
.map_err(map_reqwest)?;57
Ok(CalDavClient {58
http,59
username: username.into(),60
password: password.into(),61
})62
}63
64
pub async fn discover(&self, url: &str) -> Result<DiscoverResult> {65
discover(self, url).await66
}67
68
pub async fn list_calendars(&self, home_set: &str) -> Result<Vec<ListedCalendar>> {69
let body = propfind_body(&[70
"<d:displayname/>",71
"<d:resourcetype/>",72
"<d:current-user-privilege-set/>",73
"<c:supported-calendar-component-set/>",74
"<x:calendar-color/>",75
]);76
let xml = self.propfind(home_set, "1", &body).await?;77
let mut calendars = Vec::new();78
for response in parse_multistatus(&xml) {79
if !response.resource_type_calendar {80
continue;81
}82
// Prefer VEVENT; if component set absent, still include calendar collections.83
if !response.supports_vevent84
&& xml.contains("supported-calendar-component-set")85
&& response.href.contains("todo")86
{87
continue;88
}89
let href = resolve_url(home_set, &response.href)?;90
calendars.push(ListedCalendar {91
href,92
summary: response93
.displayname94
.unwrap_or_else(|| "Calendar".to_owned()),95
color: response.calendar_color,96
writable: response.writable,97
});98
}99
Ok(calendars)100
}101
102
pub async fn fetch_events(103
&self,104
calendar_href: &str,105
account_id: &str,106
calendar_name: Option<&str>,107
from: DateTime<Utc>,108
to: DateTime<Utc>,109
) -> Result<Vec<CalDavEvent>> {110
let start = from.format("%Y%m%dT%H%M%SZ").to_string();111
let end = to.format("%Y%m%dT%H%M%SZ").to_string();112
let mut resources = self.calendar_query(calendar_href, &start, &end, true).await;113
if resources.is_err() {114
resources = self115
.calendar_query(calendar_href, &start, &end, false)116
.await;117
}118
let resources = resources?;119
let mut out = Vec::new();120
for (href, etag, data) in resources {121
let absolute = resolve_url(calendar_href, &href).unwrap_or(href);122
let parsed = parse_calendar(&data);123
let series_uids: HashSet<String> = parsed124
.iter()125
.filter(|event| {126
event.rrule.is_some()127
|| !event.rdates.is_empty()128
|| event.recurrence_id.is_some()129
})130
.map(|event| event.uid.clone())131
.collect();132
let expanded = expand_events(parsed, from, to);133
for item in expanded {134
let mut event = to_calendar_event(&item, account_id, &absolute, calendar_name);135
let uid = event.ical_uid.clone().unwrap_or_default();136
let series = series_uids.contains(&uid) || item.recurrence_id.is_some();137
event.series = series;138
event.object_id = object_id_for(&absolute, &uid, series, item.start);139
out.push(CalDavEvent {140
event,141
href: absolute.clone(),142
etag: etag.clone(),143
});144
}145
}146
Ok(out)147
}148
149
pub async fn put_event(150
&self,151
calendar_href: &str,152
draft: &CalDavEventDraft,153
stamp: DateTime<Utc>,154
) -> Result<String> {155
let href = format!("{}{}.ics", ensure_trailing_slash(calendar_href), draft.uid);156
let body = crate::ical::build_vevent(draft, stamp);157
let response = self158
.http159
.put(&href)160
.basic_auth(&self.username, Some(&self.password))161
.header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")162
.header(header::IF_NONE_MATCH, "*")163
.body(body)164
.send()165
.await166
.map_err(map_reqwest)?;167
ensure_auth(response.status())?;168
if !response.status().is_success() {169
return Err(Error::UnexpectedAnswer(format!(170
"CalDAV PUT failed: {}",171
response.status()172
)));173
}174
Ok(href)175
}176
177
pub async fn delete(&self, href: &str, etag: Option<&str>) -> Result<()> {178
let mut request = self179
.http180
.delete(href)181
.basic_auth(&self.username, Some(&self.password));182
if let Some(etag) = etag {183
request = request.header(header::IF_MATCH, format!("\"{etag}\""));184
}185
let response = request.send().await.map_err(map_reqwest)?;186
ensure_auth(response.status())?;187
if response.status() == StatusCode::NOT_FOUND || response.status().is_success() {188
return Ok(());189
}190
Err(Error::UnexpectedAnswer(format!(191
"CalDAV DELETE failed: {}",192
response.status()193
)))194
}195
196
/// Exclude one occurrence by EXDATE on the master; does not DELETE the series href.197
pub async fn exclude_occurrence(198
&self,199
href: &str,200
occurrence: DateTime<Utc>,201
etag: Option<&str>,202
) -> Result<()> {203
let response = self204
.http205
.get(href)206
.basic_auth(&self.username, Some(&self.password))207
.send()208
.await209
.map_err(map_reqwest)?;210
ensure_auth(response.status())?;211
let fresh_etag = response212
.headers()213
.get(header::ETAG)214
.and_then(|v| v.to_str().ok())215
.map(|v| v.trim_matches('"').to_owned());216
let body = response.text().await.map_err(map_reqwest)?;217
let updated =218
exclude_occurrence_from_ics(&body, occurrence).map_err(Error::UnexpectedAnswer)?;219
let match_etag = etag.or(fresh_etag.as_deref());220
let mut request = self221
.http222
.put(href)223
.basic_auth(&self.username, Some(&self.password))224
.header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")225
.body(updated);226
if let Some(etag) = match_etag {227
request = request.header(header::IF_MATCH, format!("\"{etag}\""));228
}229
let response = request.send().await.map_err(map_reqwest)?;230
if response.status() == StatusCode::PRECONDITION_FAILED {231
return Err(Error::UnexpectedAnswer(232
"CalDAV event changed on the server; reload and try again".into(),233
));234
}235
ensure_auth(response.status())?;236
if !response.status().is_success() {237
return Err(Error::UnexpectedAnswer(format!(238
"CalDAV EXDATE failed: {}",239
response.status()240
)));241
}242
Ok(())243
}244
245
pub async fn update_partstat(246
&self,247
href: &str,248
etag: Option<&str>,249
mailto: &str,250
partstat: &str,251
) -> Result<()> {252
let response = self253
.http254
.get(href)255
.basic_auth(&self.username, Some(&self.password))256
.send()257
.await258
.map_err(map_reqwest)?;259
ensure_auth(response.status())?;260
let fresh_etag = response261
.headers()262
.get(header::ETAG)263
.and_then(|v| v.to_str().ok())264
.map(|v| v.trim_matches('"').to_owned());265
let body = response.text().await.map_err(map_reqwest)?;266
let updated = patch_partstat(&body, mailto, partstat);267
let match_etag = etag.or(fresh_etag.as_deref());268
let mut request = self269
.http270
.put(href)271
.basic_auth(&self.username, Some(&self.password))272
.header(header::CONTENT_TYPE, "text/calendar; charset=utf-8")273
.body(updated);274
if let Some(etag) = match_etag {275
request = request.header(header::IF_MATCH, format!("\"{etag}\""));276
}277
let response = request.send().await.map_err(map_reqwest)?;278
if response.status() == StatusCode::PRECONDITION_FAILED {279
return Err(Error::UnexpectedAnswer(280
"CalDAV event changed on the server; reload and try again".into(),281
));282
}283
ensure_auth(response.status())?;284
if !response.status().is_success() {285
return Err(Error::UnexpectedAnswer(format!(286
"CalDAV RSVP failed: {}",287
response.status()288
)));289
}290
Ok(())291
}292
293
pub async fn propfind(&self, url: &str, depth: &str, body: &str) -> Result<String> {294
let method = Method::from_bytes(b"PROPFIND").unwrap();295
let response = self296
.http297
.request(method, url)298
.basic_auth(&self.username, Some(&self.password))299
.header("Depth", depth)300
.header(header::CONTENT_TYPE, "application/xml; charset=utf-8")301
.body(body.to_owned())302
.send()303
.await304
.map_err(map_reqwest)?;305
reject_https_downgrade(url, response.url().as_str())?;306
if response.status() == StatusCode::UNAUTHORIZED {307
let www = response308
.headers()309
.get(header::WWW_AUTHENTICATE)310
.and_then(|v| v.to_str().ok())311
.unwrap_or("");312
if www.to_ascii_lowercase().contains("digest") {313
return Err(Error::UnexpectedAnswer(314
"CalDAV Digest authentication is not supported; enable Basic auth or use an app password with Basic".into(),315
));316
}317
return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into()));318
}319
if !response.status().is_success() && response.status().as_u16() != 207 {320
return Err(Error::UnexpectedAnswer(format!(321
"CalDAV PROPFIND failed: {}",322
response.status()323
)));324
}325
response.text().await.map_err(map_reqwest)326
}327
328
async fn calendar_query(329
&self,330
url: &str,331
start: &str,332
end: &str,333
expand: bool,334
) -> Result<Vec<(String, Option<String>, String)>> {335
let method = Method::from_bytes(b"REPORT").unwrap();336
let body = calendar_query_body(start, end, expand);337
let response = self338
.http339
.request(method, url)340
.basic_auth(&self.username, Some(&self.password))341
.header("Depth", "1")342
.header(header::CONTENT_TYPE, "application/xml; charset=utf-8")343
.body(body)344
.send()345
.await346
.map_err(map_reqwest)?;347
ensure_auth(response.status())?;348
if !response.status().is_success() && response.status().as_u16() != 207 {349
return Err(Error::UnexpectedAnswer(format!(350
"CalDAV REPORT failed: {}",351
response.status()352
)));353
}354
let text = response.text().await.map_err(map_reqwest)?;355
Ok(parse_calendar_query(&text))356
}357
}358
359
fn to_calendar_event(360
parsed: &crate::ical::ParsedEvent,361
account_id: &str,362
calendar_id: &str,363
calendar_name: Option<&str>,364
) -> CalendarEvent {365
let response = own_response(parsed);366
CalendarEvent {367
object_id: parsed.uid.clone(),368
subject: parsed.summary.clone(),369
start: parsed.start,370
end: parsed.end,371
all_day: parsed.all_day,372
cancelled: parsed.cancelled,373
online: parsed.join_url.is_some(),374
join_url: parsed.join_url.clone(),375
thread_id: None,376
organizer_name: parsed.organizer.as_ref().map(|(n, _)| n.clone()),377
organizer_address: parsed.organizer.as_ref().and_then(|(_, a)| a.clone()),378
ical_uid: Some(parsed.uid.clone()),379
response,380
show_as: if parsed.transparent {381
ShowAs::Free382
} else {383
ShowAs::Busy384
},385
dial_in: None,386
source: CalendarSource::CalDav,387
account_id: Some(account_id.to_owned()),388
calendar_id: Some(calendar_id.to_owned()),389
sources: vec![CalendarSource::CalDav],390
location: parsed.location.clone(),391
body_preview: parsed.description.clone().map(|d| {392
if d.chars().count() > 280 {393
d.chars().take(280).collect()394
} else {395
d396
}397
}),398
body_html: parsed.description.clone(),399
// Overridden by fetch_events after expansion (RRULE is cleared on occurrences).400
series: parsed.rrule.is_some()401
|| !parsed.rdates.is_empty()402
|| parsed.recurrence_id.is_some(),403
series_master_id: None,404
response_counts: None::<AttendeeResponseCounts>,405
attendees: parsed406
.attendees407
.iter()408
.map(|a| EventAttendee {409
name: a.cn.clone().unwrap_or_else(|| a.mailto.clone()),410
address: Some(a.mailto.clone()),411
response: partstat_to_response(a.partstat.as_deref().unwrap_or("NEEDS-ACTION")),412
required: a413
.role414
.as_deref()415
.map(|r| !r.eq_ignore_ascii_case("OPT-PARTICIPANT"))416
.unwrap_or(true),417
})418
.collect(),419
reminders: parsed.reminders_minutes.clone(),420
source_link: None,421
web_link: None,422
calendar_name: calendar_name.map(str::to_owned),423
}424
}425
426
fn own_response(parsed: &crate::ical::ParsedEvent) -> ResponseType {427
parsed428
.attendees429
.iter()430
.find_map(|a| a.partstat.as_deref().map(partstat_to_response))431
.unwrap_or(ResponseType::NotResponded)432
}433
434
fn partstat_to_response(partstat: &str) -> ResponseType {435
match partstat.to_ascii_uppercase().as_str() {436
"ACCEPTED" => ResponseType::Accepted,437
"TENTATIVE" => ResponseType::Tentative,438
"DECLINED" => ResponseType::Declined,439
"DELEGATED" => ResponseType::NotResponded,440
_ => ResponseType::NotResponded,441
}442
}443
444
pub fn partstat_for_reply(reply: crate::calendar::Reply) -> &'static str {445
match reply {446
crate::calendar::Reply::Accept => "ACCEPTED",447
crate::calendar::Reply::Tentative => "TENTATIVE",448
crate::calendar::Reply::Decline => "DECLINED",449
}450
}451
452
fn patch_partstat(ics: &str, mailto: &str, partstat: &str) -> String {453
let target = mailto.trim_start_matches("mailto:").to_ascii_lowercase();454
let mut out = String::with_capacity(ics.len() + 32);455
for line in ics.lines() {456
if line.to_ascii_uppercase().starts_with("ATTENDEE")457
&& line.to_ascii_lowercase().contains(&target)458
{459
let mut rewritten = line.to_owned();460
if let Some(start) = rewritten.to_ascii_uppercase().find("PARTSTAT=") {461
let rest = &rewritten[start + 9..];462
let end = rest.find([';', ':']).unwrap_or(rest.len());463
rewritten.replace_range(start + 9..start + 9 + end, partstat);464
} else if let Some(idx) = rewritten.find(':') {465
rewritten.insert_str(idx, &format!(";PARTSTAT={partstat}"));466
}467
out.push_str(&rewritten);468
out.push_str("\r\n");469
} else {470
out.push_str(line);471
out.push_str("\r\n");472
}473
}474
out475
}476
477
fn ensure_trailing_slash(url: &str) -> String {478
if url.ends_with('/') {479
url.to_owned()480
} else {481
format!("{url}/")482
}483
}484
485
fn ensure_auth(status: StatusCode) -> Result<()> {486
if status == StatusCode::UNAUTHORIZED {487
return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into()));488
}489
Ok(())490
}491
492
fn map_reqwest(error: reqwest::Error) -> Error {493
Error::UnexpectedAnswer(error.to_string())494
}495
496
pub fn new_event_uid() -> String {497
format!("{}@rusty-teams", Uuid::new_v4())498
}499
500
pub fn object_id_for(href: &str, uid: &str, series: bool, start: DateTime<Utc>) -> String {501
if series {502
format!("{href}#{uid}#{}", start.format("%Y%m%dT%H%M%SZ"))503
} else {504
format!("{href}#{uid}")505
}506
}507
508
pub fn href_from_object_id(object_id: &str) -> &str {509
object_id.split('#').next().unwrap_or(object_id)510
}511
512
#[cfg(test)]513
mod object_id_tests {514
use super::*;515
use chrono::TimeZone;516
517
#[test]518
fn series_occurrences_get_distinct_ids() {519
let start_a = Utc.with_ymd_and_hms(2026, 1, 5, 9, 0, 0).unwrap();520
let start_b = Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap();521
let a = object_id_for("https://dav.example/cal/evt.ics", "series", true, start_a);522
let b = object_id_for("https://dav.example/cal/evt.ics", "series", true, start_b);523
assert_ne!(a, b);524
assert!(a.ends_with("#20260105T090000Z"));525
assert_eq!(href_from_object_id(&a), "https://dav.example/cal/evt.ics");526
}527
}@@ -0,0 +1,96 @@
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(&["<c:calendar-user-address-set/>", "<c:schedule-outbox-URL/>"]);
66
let xml = client.propfind(principal, "0", &body).await?;
67
let mut addresses = Vec::new();
68
let mut outbox = None;
69
for response in parse_multistatus(&xml) {
70
addresses.extend(response.calendar_user_addresses);
71
if outbox.is_none() {
72
outbox = response.schedule_outbox;
73
}
74
}
75
Ok((addresses, outbox))
76
}
77
78
pub fn resolve_url(base: &str, href: &str) -> Result<String> {
79
if href.starts_with("http://") || href.starts_with("https://") {
80
return Ok(href.to_owned());
81
}
82
let base = Url::parse(base).map_err(|e| Error::UnexpectedAnswer(e.to_string()))?;
83
Ok(base
84
.join(href)
85
.map_err(|e| Error::UnexpectedAnswer(e.to_string()))?
86
.to_string())
87
}
88
89
pub fn reject_https_downgrade(from: &str, to: &str) -> Result<()> {
90
if from.starts_with("https://") && to.starts_with("http://") {
91
return Err(Error::UnexpectedAnswer(
92
"CalDAV refused HTTPS to HTTP redirect (credentials would be sent in cleartext)".into(),
93
));
94
}
95
Ok(())
96
}
@@ -0,0 +1,96 @@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(&["<c:calendar-user-address-set/>", "<c:schedule-outbox-URL/>"]);66
let xml = client.propfind(principal, "0", &body).await?;67
let mut addresses = Vec::new();68
let mut outbox = None;69
for response in parse_multistatus(&xml) {70
addresses.extend(response.calendar_user_addresses);71
if outbox.is_none() {72
outbox = response.schedule_outbox;73
}74
}75
Ok((addresses, outbox))76
}77
78
pub fn resolve_url(base: &str, href: &str) -> Result<String> {79
if href.starts_with("http://") || href.starts_with("https://") {80
return Ok(href.to_owned());81
}82
let base = Url::parse(base).map_err(|e| Error::UnexpectedAnswer(e.to_string()))?;83
Ok(base84
.join(href)85
.map_err(|e| Error::UnexpectedAnswer(e.to_string()))?86
.to_string())87
}88
89
pub fn reject_https_downgrade(from: &str, to: &str) -> Result<()> {90
if from.starts_with("https://") && to.starts_with("http://") {91
return Err(Error::UnexpectedAnswer(92
"CalDAV refused HTTPS to HTTP redirect (credentials would be sent in cleartext)".into(),93
));94
}95
Ok(())96
}@@ -0,0 +1,13 @@
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::{
10
CalDavClient, CalDavEvent, ListedCalendar, href_from_object_id, new_event_uid, object_id_for,
11
partstat_for_reply,
12
};
13
pub use discovery::{DiscoverResult, discover};
@@ -0,0 +1,13 @@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::{10
CalDavClient, CalDavEvent, ListedCalendar, href_from_object_id, new_event_uid, object_id_for,11
partstat_for_reply,12
};13
pub use discovery::{DiscoverResult, discover};@@ -0,0 +1,232 @@
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
43
.unescape_value()
44
.map(|v| v.eq_ignore_ascii_case("VEVENT"))
45
.unwrap_or(false)
46
{
47
current.supports_vevent = true;
48
}
49
}
50
}
51
}
52
Ok(Event::Empty(e)) => {
53
let local = local_name(&e.name().as_ref());
54
if local == "calendar" && path.iter().any(|p| p == "resourcetype") {
55
current.resource_type_calendar = true;
56
}
57
if local == "comp" {
58
for attr in e.attributes().flatten() {
59
if local_name(attr.key.as_ref()) == "name"
60
&& attr
61
.unescape_value()
62
.map(|v| v.eq_ignore_ascii_case("VEVENT"))
63
.unwrap_or(false)
64
{
65
current.supports_vevent = true;
66
}
67
}
68
}
69
if local == "write" || local == "write-content" || local == "all" {
70
if path.iter().any(|p| p == "current-user-privilege-set") {
71
current.writable = true;
72
}
73
}
74
}
75
Ok(Event::Text(t)) => {
76
let text = t.unescape().unwrap_or_default().to_string();
77
let leaf = path.last().cloned().unwrap_or_default();
78
if !in_response {
79
continue;
80
}
81
match leaf.as_str() {
82
"href" => {
83
if path.iter().any(|p| p == "current-user-principal") {
84
current.current_user_principal = Some(text);
85
} else if path.iter().any(|p| p == "calendar-home-set") {
86
current.calendar_home_set = Some(text);
87
} else if path.iter().any(|p| p == "calendar-user-address-set") {
88
current.calendar_user_addresses.push(text);
89
} else if path.iter().any(|p| p == "schedule-outbox-URL") {
90
current.schedule_outbox = Some(text);
91
} else if current.href.is_empty() {
92
current.href = text;
93
}
94
}
95
"displayname" => current.displayname = Some(text),
96
"calendar-color" | "color" => current.calendar_color = Some(text),
97
"getctag" | "getetag" => {
98
current.getctag = Some(text.trim_matches('"').to_owned())
99
}
100
_ => {}
101
}
102
}
103
Ok(Event::End(e)) => {
104
let local = local_name(&e.name().as_ref());
105
if local == "response" && in_response {
106
responses.push(std::mem::take(&mut current));
107
in_response = false;
108
}
109
path.pop();
110
}
111
Ok(Event::Eof) => break,
112
Err(_) => break,
113
_ => {}
114
}
115
buf.clear();
116
}
117
responses
118
}
119
120
pub fn parse_calendar_query(xml: &str) -> Vec<(String, Option<String>, String)> {
121
// href, etag, calendar-data
122
let mut reader = Reader::from_str(xml);
123
reader.config_mut().trim_text(true);
124
let mut out = Vec::new();
125
let mut href = String::new();
126
let mut etag = None;
127
let mut data = String::new();
128
let mut in_response = false;
129
let mut path: Vec<String> = Vec::new();
130
let mut buf = Vec::new();
131
loop {
132
match reader.read_event_into(&mut buf) {
133
Ok(Event::Start(e)) => {
134
let local = local_name(&e.name().as_ref());
135
path.push(local.clone());
136
if local == "response" {
137
in_response = true;
138
href.clear();
139
etag = None;
140
data.clear();
141
}
142
}
143
Ok(Event::Text(t)) => {
144
if !in_response {
145
continue;
146
}
147
let text = t.unescape().unwrap_or_default().to_string();
148
let leaf = path.last().cloned().unwrap_or_default();
149
match leaf.as_str() {
150
"href" if href.is_empty() => href = text,
151
"getetag" => etag = Some(text.trim_matches('"').to_owned()),
152
"calendar-data" => data.push_str(&text),
153
_ => {}
154
}
155
}
156
Ok(Event::CData(t)) => {
157
if path.last().map(|s| s.as_str()) == Some("calendar-data") {
158
data.push_str(&String::from_utf8_lossy(&t));
159
}
160
}
161
Ok(Event::End(e)) => {
162
let local = local_name(&e.name().as_ref());
163
if local == "response" && in_response {
164
if !data.is_empty() {
165
out.push((href.clone(), etag.clone(), data.clone()));
166
}
167
in_response = false;
168
}
169
path.pop();
170
}
171
Ok(Event::Eof) => break,
172
Err(_) => break,
173
_ => {}
174
}
175
buf.clear();
176
}
177
out
178
}
179
180
fn local_name(name: &[u8]) -> String {
181
let full = String::from_utf8_lossy(name);
182
let after_ns = full.rsplit('}').next().unwrap_or(&full);
183
after_ns
184
.rsplit(':')
185
.next()
186
.unwrap_or(after_ns)
187
.to_ascii_lowercase()
188
}
189
190
pub fn propfind_body(props: &[&str]) -> String {
191
let mut body = String::from(
192
r#"<?xml version="1.0" encoding="utf-8"?>
193
<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/">
194
<d:prop>
195
"#,
196
);
197
for prop in props {
198
body.push_str(" ");
199
body.push_str(prop);
200
body.push('\n');
201
}
202
body.push_str(" </d:prop>\n</d:propfind>");
203
body
204
}
205
206
pub fn calendar_query_body(start: &str, end: &str, expand: bool) -> String {
207
let expand_xml = if expand {
208
format!(
209
r#" <c:expand start="{start}" end="{end}"/>
210
"#
211
)
212
} else {
213
String::new()
214
};
215
format!(
216
r#"<?xml version="1.0" encoding="utf-8"?>
217
<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
218
<d:prop>
219
<d:getetag/>
220
<c:calendar-data>
221
{expand_xml} </c:calendar-data>
222
</d:prop>
223
<c:filter>
224
<c:comp-filter name="VCALENDAR">
225
<c:comp-filter name="VEVENT">
226
<c:time-range start="{start}" end="{end}"/>
227
</c:comp-filter>
228
</c:comp-filter>
229
</c:filter>
230
</c:calendar-query>"#
231
)
232
}
@@ -0,0 +1,232 @@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
&& attr43
.unescape_value()44
.map(|v| v.eq_ignore_ascii_case("VEVENT"))45
.unwrap_or(false)46
{47
current.supports_vevent = true;48
}49
}50
}51
}52
Ok(Event::Empty(e)) => {53
let local = local_name(&e.name().as_ref());54
if local == "calendar" && path.iter().any(|p| p == "resourcetype") {55
current.resource_type_calendar = true;56
}57
if local == "comp" {58
for attr in e.attributes().flatten() {59
if local_name(attr.key.as_ref()) == "name"60
&& attr61
.unescape_value()62
.map(|v| v.eq_ignore_ascii_case("VEVENT"))63
.unwrap_or(false)64
{65
current.supports_vevent = true;66
}67
}68
}69
if local == "write" || local == "write-content" || local == "all" {70
if path.iter().any(|p| p == "current-user-privilege-set") {71
current.writable = true;72
}73
}74
}75
Ok(Event::Text(t)) => {76
let text = t.unescape().unwrap_or_default().to_string();77
let leaf = path.last().cloned().unwrap_or_default();78
if !in_response {79
continue;80
}81
match leaf.as_str() {82
"href" => {83
if path.iter().any(|p| p == "current-user-principal") {84
current.current_user_principal = Some(text);85
} else if path.iter().any(|p| p == "calendar-home-set") {86
current.calendar_home_set = Some(text);87
} else if path.iter().any(|p| p == "calendar-user-address-set") {88
current.calendar_user_addresses.push(text);89
} else if path.iter().any(|p| p == "schedule-outbox-URL") {90
current.schedule_outbox = Some(text);91
} else if current.href.is_empty() {92
current.href = text;93
}94
}95
"displayname" => current.displayname = Some(text),96
"calendar-color" | "color" => current.calendar_color = Some(text),97
"getctag" | "getetag" => {98
current.getctag = Some(text.trim_matches('"').to_owned())99
}100
_ => {}101
}102
}103
Ok(Event::End(e)) => {104
let local = local_name(&e.name().as_ref());105
if local == "response" && in_response {106
responses.push(std::mem::take(&mut current));107
in_response = false;108
}109
path.pop();110
}111
Ok(Event::Eof) => break,112
Err(_) => break,113
_ => {}114
}115
buf.clear();116
}117
responses118
}119
120
pub fn parse_calendar_query(xml: &str) -> Vec<(String, Option<String>, String)> {121
// href, etag, calendar-data122
let mut reader = Reader::from_str(xml);123
reader.config_mut().trim_text(true);124
let mut out = Vec::new();125
let mut href = String::new();126
let mut etag = None;127
let mut data = String::new();128
let mut in_response = false;129
let mut path: Vec<String> = Vec::new();130
let mut buf = Vec::new();131
loop {132
match reader.read_event_into(&mut buf) {133
Ok(Event::Start(e)) => {134
let local = local_name(&e.name().as_ref());135
path.push(local.clone());136
if local == "response" {137
in_response = true;138
href.clear();139
etag = None;140
data.clear();141
}142
}143
Ok(Event::Text(t)) => {144
if !in_response {145
continue;146
}147
let text = t.unescape().unwrap_or_default().to_string();148
let leaf = path.last().cloned().unwrap_or_default();149
match leaf.as_str() {150
"href" if href.is_empty() => href = text,151
"getetag" => etag = Some(text.trim_matches('"').to_owned()),152
"calendar-data" => data.push_str(&text),153
_ => {}154
}155
}156
Ok(Event::CData(t)) => {157
if path.last().map(|s| s.as_str()) == Some("calendar-data") {158
data.push_str(&String::from_utf8_lossy(&t));159
}160
}161
Ok(Event::End(e)) => {162
let local = local_name(&e.name().as_ref());163
if local == "response" && in_response {164
if !data.is_empty() {165
out.push((href.clone(), etag.clone(), data.clone()));166
}167
in_response = false;168
}169
path.pop();170
}171
Ok(Event::Eof) => break,172
Err(_) => break,173
_ => {}174
}175
buf.clear();176
}177
out178
}179
180
fn local_name(name: &[u8]) -> String {181
let full = String::from_utf8_lossy(name);182
let after_ns = full.rsplit('}').next().unwrap_or(&full);183
after_ns184
.rsplit(':')185
.next()186
.unwrap_or(after_ns)187
.to_ascii_lowercase()188
}189
190
pub fn propfind_body(props: &[&str]) -> String {191
let mut body = String::from(192
r#"<?xml version="1.0" encoding="utf-8"?>193
<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/">194
<d:prop>195
"#,196
);197
for prop in props {198
body.push_str(" ");199
body.push_str(prop);200
body.push('\n');201
}202
body.push_str(" </d:prop>\n</d:propfind>");203
body204
}205
206
pub fn calendar_query_body(start: &str, end: &str, expand: bool) -> String {207
let expand_xml = if expand {208
format!(209
r#" <c:expand start="{start}" end="{end}"/>210
"#211
)212
} else {213
String::new()214
};215
format!(216
r#"<?xml version="1.0" encoding="utf-8"?>217
<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">218
<d:prop>219
<d:getetag/>220
<c:calendar-data>221
{expand_xml} </c:calendar-data>222
</d:prop>223
<c:filter>224
<c:comp-filter name="VCALENDAR">225
<c:comp-filter name="VEVENT">226
<c:time-range start="{start}" end="{end}"/>227
</c:comp-filter>228
</c:comp-filter>229
</c:filter>230
</c:calendar-query>"#231
)232
}@@ -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)]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:VCALENDAR43
BEGIN:VEVENT44
UID:145
SUMMARY:Hi46
DTSTART:20260101T100000Z47
DTEND:20260101T110000Z48
END:VEVENT49
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
}@@ -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, space6
use crate::error::{Error, Result};6
use crate::error::{Error, Result};7
7
8
mod availability;8
mod availability;9
mod merge;9
mod reminders;10
mod reminders;10
mod schedule;11
mod schedule;11
12
12
pub use availability::{BusyTime, PersonSchedule, parse_schedules};13
pub use availability::{BusyTime, PersonSchedule, parse_schedules};13
14
pub use merge::{HomeCalendar, merge_calendar_events, normalize_join_url};14
pub use reminders::{Reminder, parse_reminders};15
pub use reminders::{Reminder, parse_reminders};15
pub use schedule::{16
pub 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
50
impl CalendarSource {54
impl 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)]@@ -0,0 +1,267 @@
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![
230
event("o1", CalendarSource::Outlook, Some("uid"), join),
231
next_day,
232
],
233
None,
234
);
235
assert_eq!(merged.len(), 2);
236
}
237
238
#[test]
239
fn merges_on_normalized_join_url() {
240
let merged = merge_calendar_events(
241
vec![
242
event(
243
"o1",
244
CalendarSource::Outlook,
245
None,
246
Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),
247
),
248
event(
249
"g1",
250
CalendarSource::Google,
251
None,
252
Some("https://teams.microsoft.com/l/meetup-join/x/"),
253
),
254
],
255
None,
256
);
257
assert_eq!(merged.len(), 1);
258
}
259
260
#[test]
261
fn does_not_merge_on_title_and_time_alone() {
262
let a = event("a", CalendarSource::Outlook, Some("a"), None);
263
let mut b = event("b", CalendarSource::Google, Some("b"), None);
264
b.subject = a.subject.clone();
265
assert_eq!(merge_calendar_events(vec![a, b], None).len(), 2);
266
}
267
}
@@ -0,0 +1,267 @@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 keep14
/// 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) = merged22
.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
merged77
}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
false98
}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_day122
&& right.all_day123
&& (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::Utc163
.with_ymd_and_hms(2026, 11, 11, 10, 0, 0)164
.unwrap(),165
end: chrono::Utc166
.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![230
event("o1", CalendarSource::Outlook, Some("uid"), join),231
next_day,232
],233
None,234
);235
assert_eq!(merged.len(), 2);236
}237
238
#[test]239
fn merges_on_normalized_join_url() {240
let merged = merge_calendar_events(241
vec![242
event(243
"o1",244
CalendarSource::Outlook,245
None,246
Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),247
),248
event(249
"g1",250
CalendarSource::Google,251
None,252
Some("https://teams.microsoft.com/l/meetup-join/x/"),253
),254
],255
None,256
);257
assert_eq!(merged.len(), 1);258
}259
260
#[test]261
fn does_not_merge_on_title_and_time_alone() {262
let a = event("a", CalendarSource::Outlook, Some("a"), None);263
let mut b = event("b", CalendarSource::Google, Some("b"), None);264
b.subject = a.subject.clone();265
assert_eq!(merge_calendar_events(vec![a, b], None).len(), 2);266
}267
}@@ -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 @@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.3
pub use crate::{merge_calendar_events, normalize_join_url};4
pub fn merge_calendar_events(events: Vec<CalendarEvent>) -> Vec<CalendarEvent> {5
let mut merged: Vec<CalendarEvent> = Vec::new();6
for event in events {7
if let Some(existing) = merged8
.iter_mut()9
.find(|candidate| same_meeting(candidate, &event))10
{11
if !existing.sources.contains(&event.source) {12
existing.sources.push(event.source);13
}14
if existing.join_url.is_none() {15
existing.join_url = event.join_url.clone();16
existing.online = existing.online || event.online;17
}18
if existing.thread_id.is_none() {19
existing.thread_id = event.thread_id.clone();20
}21
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::Outlook56
{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
merged70
}71
72
fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {73
let same_all_day = left.all_day74
&& right.all_day75
&& (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::Utc115
.with_ymd_and_hms(2026, 11, 11, 10, 0, 0)116
.unwrap(),117
end: chrono::Utc118
.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
}@@ -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 @@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.uid35
&& over36
.recurrence_id37
.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
out57
}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::UTC70
.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
!master87
.exdates88
.iter()89
.any(|ex| (*ex - *start).num_seconds().abs() < 60)90
});91
starts.sort();92
starts.dedup();93
starts94
}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,68 @@
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(|| {
12
url.filter(|value| looks_like_teams(value))
13
.map(str::to_owned)
14
})
15
.or_else(|| {
16
location
17
.filter(|value| looks_like_teams(value))
18
.map(str::to_owned)
19
})
20
.or_else(|| description.and_then(find_in_text))
21
}
22
23
fn looks_like_teams(value: &str) -> bool {
24
value.contains("teams.microsoft.com") || value.contains("teams.live.com")
25
}
26
27
fn find_in_text(text: &str) -> Option<String> {
28
text.split_whitespace()
29
.find(|token| looks_like_teams(token))
30
.map(|token| {
31
token
32
.trim_end_matches(|c: char| matches!(c, '.' | ',' | ')' | ']' | '>' | '"'))
33
.to_owned()
34
})
35
}
36
37
#[cfg(test)]
38
mod tests {
39
use super::*;
40
41
#[test]
42
fn prefers_skype_property() {
43
let url = teams_join_url(
44
Some("https://teams.microsoft.com/l/meetup-join/a"),
45
Some("https://example.com"),
46
None,
47
Some("https://teams.microsoft.com/l/meetup-join/b"),
48
);
49
assert_eq!(
50
url.as_deref(),
51
Some("https://teams.microsoft.com/l/meetup-join/a")
52
);
53
}
54
55
#[test]
56
fn finds_link_in_description() {
57
let url = teams_join_url(
58
None,
59
None,
60
None,
61
Some("Join: https://teams.microsoft.com/l/meetup-join/x?a=1."),
62
);
63
assert_eq!(
64
url.as_deref(),
65
Some("https://teams.microsoft.com/l/meetup-join/x?a=1")
66
);
67
}
68
}
@@ -0,0 +1,68 @@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_url9
.filter(|value| looks_like_teams(value))10
.map(str::to_owned)11
.or_else(|| {12
url.filter(|value| looks_like_teams(value))13
.map(str::to_owned)14
})15
.or_else(|| {16
location17
.filter(|value| looks_like_teams(value))18
.map(str::to_owned)19
})20
.or_else(|| description.and_then(find_in_text))21
}22
23
fn looks_like_teams(value: &str) -> bool {24
value.contains("teams.microsoft.com") || value.contains("teams.live.com")25
}26
27
fn find_in_text(text: &str) -> Option<String> {28
text.split_whitespace()29
.find(|token| looks_like_teams(token))30
.map(|token| {31
token32
.trim_end_matches(|c: char| matches!(c, '.' | ',' | ')' | ']' | '>' | '"'))33
.to_owned()34
})35
}36
37
#[cfg(test)]38
mod tests {39
use super::*;40
41
#[test]42
fn prefers_skype_property() {43
let url = teams_join_url(44
Some("https://teams.microsoft.com/l/meetup-join/a"),45
Some("https://example.com"),46
None,47
Some("https://teams.microsoft.com/l/meetup-join/b"),48
);49
assert_eq!(50
url.as_deref(),51
Some("https://teams.microsoft.com/l/meetup-join/a")52
);53
}54
55
#[test]56
fn finds_link_in_description() {57
let url = teams_join_url(58
None,59
None,60
None,61
Some("Join: https://teams.microsoft.com/l/meetup-join/x?a=1."),62
);63
assert_eq!(64
url.as_deref(),65
Some("https://teams.microsoft.com/l/meetup-join/x?a=1")66
);67
}68
}@@ -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, exclude_occurrence_from_ics};
@@ -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, exclude_occurrence_from_ics};@@ -0,0 +1,423 @@
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(¶ms, &value)?;
130
start = Some(dt);
131
all_day = day;
132
}
133
"DTEND" => {
134
let (dt, day) = parse_date_value(¶ms, &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(¶ms, &value)),
151
"EXDATE" => exdates.extend(parse_multi_dates(¶ms, &value)),
152
"RECURRENCE-ID" => {
153
if let Some((dt, _)) = parse_date_value(¶ms, &value) {
154
recurrence_id = Some(dt);
155
}
156
}
157
"SEQUENCE" => sequence = value.parse().unwrap_or(0),
158
"ORGANIZER" => organizer = Some(parse_cal_address(¶ms, &value)),
159
"ATTENDEE" => attendees.push(parse_attendee(¶ms, &value)),
160
_ => {}
161
}
162
}
163
164
let start = start?;
165
let end = end
166
.or_else(|| duration.map(|d| start + d))
167
.unwrap_or_else(|| {
168
if all_day {
169
start + Duration::days(1)
170
} else {
171
start + Duration::hours(1)
172
}
173
});
174
let join = teams_join_url(
175
skype.as_deref(),
176
url.as_deref(),
177
location.as_deref(),
178
description.as_deref(),
179
);
180
Some(ParsedEvent {
181
uid,
182
href_hint: None,
183
summary,
184
start,
185
end,
186
all_day,
187
cancelled,
188
transparent,
189
description,
190
location: location.filter(|value| {
191
!value.contains("teams.microsoft.com") && !value.contains("teams.live.com")
192
}),
193
join_url: join,
194
organizer,
195
attendees,
196
reminders_minutes: reminders,
197
rrule,
198
rdates,
199
exdates,
200
recurrence_id,
201
sequence,
202
status,
203
})
204
}
205
206
fn split_property(line: &str) -> (String, Vec<(String, String)>, String) {
207
let (left, value) = match line.split_once(':') {
208
Some((l, v)) => (l, v.to_owned()),
209
None => (line, String::new()),
210
};
211
let mut parts = left.split(';');
212
let name = parts.next().unwrap_or("").to_owned();
213
let mut params = Vec::new();
214
for part in parts {
215
if let Some((k, v)) = part.split_once('=') {
216
params.push((k.to_ascii_uppercase(), v.trim_matches('"').to_owned()));
217
}
218
}
219
(name, params, value)
220
}
221
222
fn param<'a>(params: &'a [(String, String)], key: &str) -> Option<&'a str> {
223
params
224
.iter()
225
.find(|(k, _)| k.eq_ignore_ascii_case(key))
226
.map(|(_, v)| v.as_str())
227
}
228
229
fn parse_date_value(params: &[(String, String)], value: &str) -> Option<(DateTime<Utc>, bool)> {
230
let value_param = param(params, "VALUE").unwrap_or("");
231
let tzid = param(params, "TZID");
232
if value_param.eq_ignore_ascii_case("DATE") || (value.len() == 8 && !value.contains('T')) {
233
let date = NaiveDate::parse_from_str(value, "%Y%m%d").ok()?;
234
let start = date.and_hms_opt(0, 0, 0)?;
235
return Some((Utc.from_utc_datetime(&start), true));
236
}
237
let floating = !value.ends_with('Z') && tzid.is_none();
238
let naive = if value.ends_with('Z') {
239
NaiveDateTime::parse_from_str(value.trim_end_matches('Z'), "%Y%m%dT%H%M%S").ok()?
240
} else {
241
NaiveDateTime::parse_from_str(value, "%Y%m%dT%H%M%S")
242
.or_else(|_| NaiveDateTime::parse_from_str(value, "%Y%m%dT%H%M%S%.f"))
243
.ok()?
244
};
245
if value.ends_with('Z') {
246
return Some((Utc.from_utc_datetime(&naive), false));
247
}
248
if let Some(tzid) = tzid
249
&& let Some(tz) = resolve_tzid(tzid)
250
{
251
return Some((
252
tz.from_local_datetime(&naive)
253
.single()
254
.or_else(|| tz.from_local_datetime(&naive).earliest())?
255
.with_timezone(&Utc),
256
false,
257
));
258
}
259
if floating {
260
// Treat floating as local wall time interpreted via host offset later; store as UTC naive.
261
return Some((Utc.from_utc_datetime(&naive), false));
262
}
263
Some((Utc.from_utc_datetime(&naive), false))
264
}
265
266
fn parse_multi_dates(params: &[(String, String)], value: &str) -> Vec<DateTime<Utc>> {
267
value
268
.split(',')
269
.filter_map(|part| parse_date_value(params, part.trim()).map(|(dt, _)| dt))
270
.collect()
271
}
272
273
fn parse_duration(value: &str) -> Option<Duration> {
274
// PTnHnMnS / PnD subset
275
let mut rest = value.trim().trim_start_matches('+');
276
let negative = rest.starts_with('-');
277
if negative {
278
rest = &rest[1..];
279
}
280
if !rest.starts_with('P') {
281
return None;
282
}
283
rest = &rest[1..];
284
let mut total = Duration::zero();
285
if let Some((date, time)) = rest.split_once('T') {
286
total += parse_duration_date(date)?;
287
total += parse_duration_time(time)?;
288
} else if rest.contains('T') {
289
total += parse_duration_time(rest.trim_start_matches('T'))?;
290
} else {
291
total += parse_duration_date(rest)?;
292
}
293
Some(if negative { -total } else { total })
294
}
295
296
fn parse_duration_date(value: &str) -> Option<Duration> {
297
if value.is_empty() {
298
return Some(Duration::zero());
299
}
300
let mut num = String::new();
301
let mut total = Duration::zero();
302
for ch in value.chars() {
303
if ch.is_ascii_digit() {
304
num.push(ch);
305
continue;
306
}
307
let n: i64 = num.parse().ok()?;
308
num.clear();
309
total += match ch {
310
'D' => Duration::days(n),
311
'W' => Duration::weeks(n),
312
_ => return None,
313
};
314
}
315
Some(total)
316
}
317
318
fn parse_duration_time(value: &str) -> Option<Duration> {
319
let mut num = String::new();
320
let mut total = Duration::zero();
321
for ch in value.chars() {
322
if ch.is_ascii_digit() {
323
num.push(ch);
324
continue;
325
}
326
let n: i64 = num.parse().ok()?;
327
num.clear();
328
total += match ch {
329
'H' => Duration::hours(n),
330
'M' => Duration::minutes(n),
331
'S' => Duration::seconds(n),
332
_ => return None,
333
};
334
}
335
Some(total)
336
}
337
338
fn parse_trigger_minutes(value: &str) -> Option<u32> {
339
let duration = parse_duration(value)?;
340
let minutes = duration.num_minutes().unsigned_abs() as u32;
341
Some(minutes)
342
}
343
344
fn parse_cal_address(params: &[(String, String)], value: &str) -> (String, Option<String>) {
345
let mailto = value
346
.trim()
347
.trim_start_matches("mailto:")
348
.trim_start_matches("MAILTO:")
349
.to_owned();
350
let cn = param(params, "CN").map(str::to_owned);
351
(cn.unwrap_or_else(|| mailto.clone()), Some(mailto))
352
}
353
354
fn parse_attendee(params: &[(String, String)], value: &str) -> ParsedAttendee {
355
let mailto = value
356
.trim()
357
.trim_start_matches("mailto:")
358
.trim_start_matches("MAILTO:")
359
.to_owned();
360
ParsedAttendee {
361
cn: param(params, "CN").map(str::to_owned),
362
mailto,
363
partstat: param(params, "PARTSTAT").map(str::to_owned),
364
role: param(params, "ROLE").map(str::to_owned),
365
}
366
}
367
368
fn unescape(value: &str) -> String {
369
let mut out = String::with_capacity(value.len());
370
let mut chars = value.chars();
371
while let Some(ch) = chars.next() {
372
if ch == '\\' {
373
match chars.next() {
374
Some('n') | Some('N') => out.push('\n'),
375
Some(',') => out.push(','),
376
Some(';') => out.push(';'),
377
Some('\\') => out.push('\\'),
378
Some(other) => out.push(other),
379
None => out.push('\\'),
380
}
381
} else {
382
out.push(ch);
383
}
384
}
385
out
386
}
387
388
#[cfg(test)]
389
mod tests {
390
use super::*;
391
392
#[test]
393
fn unfolds_and_parses_all_day_exclusive_end() {
394
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";
395
let events = parse_calendar(ics);
396
assert_eq!(events.len(), 1);
397
assert!(events[0].all_day);
398
assert_eq!(
399
events[0].start,
400
Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap()
401
);
402
assert_eq!(
403
events[0].end,
404
Utc.with_ymd_and_hms(2026, 1, 2, 0, 0, 0).unwrap()
405
);
406
}
407
408
#[test]
409
fn folds_long_summary() {
410
let ics = "BEGIN:VEVENT\nUID:1\nSUMMARY:Hello\n world\nDTSTART:20260101T100000Z\nDTEND:20260101T110000Z\nEND:VEVENT\n";
411
let events = parse_calendar(ics);
412
assert_eq!(events[0].summary, "Hello world");
413
}
414
415
#[test]
416
fn groups_override_separately() {
417
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";
418
let events = parse_calendar(ics);
419
assert_eq!(events.len(), 2);
420
assert!(events[0].rrule.is_some());
421
assert!(events[1].recurrence_id.is_some());
422
}
423
}
@@ -0,0 +1,423 @@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
events58
}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
out78
}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(¶ms, &value)?;130
start = Some(dt);131
all_day = day;132
}133
"DTEND" => {134
let (dt, day) = parse_date_value(¶ms, &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(¶ms, &value)),151
"EXDATE" => exdates.extend(parse_multi_dates(¶ms, &value)),152
"RECURRENCE-ID" => {153
if let Some((dt, _)) = parse_date_value(¶ms, &value) {154
recurrence_id = Some(dt);155
}156
}157
"SEQUENCE" => sequence = value.parse().unwrap_or(0),158
"ORGANIZER" => organizer = Some(parse_cal_address(¶ms, &value)),159
"ATTENDEE" => attendees.push(parse_attendee(¶ms, &value)),160
_ => {}161
}162
}163
164
let start = start?;165
let end = end166
.or_else(|| duration.map(|d| start + d))167
.unwrap_or_else(|| {168
if all_day {169
start + Duration::days(1)170
} else {171
start + Duration::hours(1)172
}173
});174
let join = teams_join_url(175
skype.as_deref(),176
url.as_deref(),177
location.as_deref(),178
description.as_deref(),179
);180
Some(ParsedEvent {181
uid,182
href_hint: None,183
summary,184
start,185
end,186
all_day,187
cancelled,188
transparent,189
description,190
location: location.filter(|value| {191
!value.contains("teams.microsoft.com") && !value.contains("teams.live.com")192
}),193
join_url: join,194
organizer,195
attendees,196
reminders_minutes: reminders,197
rrule,198
rdates,199
exdates,200
recurrence_id,201
sequence,202
status,203
})204
}205
206
fn split_property(line: &str) -> (String, Vec<(String, String)>, String) {207
let (left, value) = match line.split_once(':') {208
Some((l, v)) => (l, v.to_owned()),209
None => (line, String::new()),210
};211
let mut parts = left.split(';');212
let name = parts.next().unwrap_or("").to_owned();213
let mut params = Vec::new();214
for part in parts {215
if let Some((k, v)) = part.split_once('=') {216
params.push((k.to_ascii_uppercase(), v.trim_matches('"').to_owned()));217
}218
}219
(name, params, value)220
}221
222
fn param<'a>(params: &'a [(String, String)], key: &str) -> Option<&'a str> {223
params224
.iter()225
.find(|(k, _)| k.eq_ignore_ascii_case(key))226
.map(|(_, v)| v.as_str())227
}228
229
fn parse_date_value(params: &[(String, String)], value: &str) -> Option<(DateTime<Utc>, bool)> {230
let value_param = param(params, "VALUE").unwrap_or("");231
let tzid = param(params, "TZID");232
if value_param.eq_ignore_ascii_case("DATE") || (value.len() == 8 && !value.contains('T')) {233
let date = NaiveDate::parse_from_str(value, "%Y%m%d").ok()?;234
let start = date.and_hms_opt(0, 0, 0)?;235
return Some((Utc.from_utc_datetime(&start), true));236
}237
let floating = !value.ends_with('Z') && tzid.is_none();238
let naive = if value.ends_with('Z') {239
NaiveDateTime::parse_from_str(value.trim_end_matches('Z'), "%Y%m%dT%H%M%S").ok()?240
} else {241
NaiveDateTime::parse_from_str(value, "%Y%m%dT%H%M%S")242
.or_else(|_| NaiveDateTime::parse_from_str(value, "%Y%m%dT%H%M%S%.f"))243
.ok()?244
};245
if value.ends_with('Z') {246
return Some((Utc.from_utc_datetime(&naive), false));247
}248
if let Some(tzid) = tzid249
&& let Some(tz) = resolve_tzid(tzid)250
{251
return Some((252
tz.from_local_datetime(&naive)253
.single()254
.or_else(|| tz.from_local_datetime(&naive).earliest())?255
.with_timezone(&Utc),256
false,257
));258
}259
if floating {260
// Treat floating as local wall time interpreted via host offset later; store as UTC naive.261
return Some((Utc.from_utc_datetime(&naive), false));262
}263
Some((Utc.from_utc_datetime(&naive), false))264
}265
266
fn parse_multi_dates(params: &[(String, String)], value: &str) -> Vec<DateTime<Utc>> {267
value268
.split(',')269
.filter_map(|part| parse_date_value(params, part.trim()).map(|(dt, _)| dt))270
.collect()271
}272
273
fn parse_duration(value: &str) -> Option<Duration> {274
// PTnHnMnS / PnD subset275
let mut rest = value.trim().trim_start_matches('+');276
let negative = rest.starts_with('-');277
if negative {278
rest = &rest[1..];279
}280
if !rest.starts_with('P') {281
return None;282
}283
rest = &rest[1..];284
let mut total = Duration::zero();285
if let Some((date, time)) = rest.split_once('T') {286
total += parse_duration_date(date)?;287
total += parse_duration_time(time)?;288
} else if rest.contains('T') {289
total += parse_duration_time(rest.trim_start_matches('T'))?;290
} else {291
total += parse_duration_date(rest)?;292
}293
Some(if negative { -total } else { total })294
}295
296
fn parse_duration_date(value: &str) -> Option<Duration> {297
if value.is_empty() {298
return Some(Duration::zero());299
}300
let mut num = String::new();301
let mut total = Duration::zero();302
for ch in value.chars() {303
if ch.is_ascii_digit() {304
num.push(ch);305
continue;306
}307
let n: i64 = num.parse().ok()?;308
num.clear();309
total += match ch {310
'D' => Duration::days(n),311
'W' => Duration::weeks(n),312
_ => return None,313
};314
}315
Some(total)316
}317
318
fn parse_duration_time(value: &str) -> Option<Duration> {319
let mut num = String::new();320
let mut total = Duration::zero();321
for ch in value.chars() {322
if ch.is_ascii_digit() {323
num.push(ch);324
continue;325
}326
let n: i64 = num.parse().ok()?;327
num.clear();328
total += match ch {329
'H' => Duration::hours(n),330
'M' => Duration::minutes(n),331
'S' => Duration::seconds(n),332
_ => return None,333
};334
}335
Some(total)336
}337
338
fn parse_trigger_minutes(value: &str) -> Option<u32> {339
let duration = parse_duration(value)?;340
let minutes = duration.num_minutes().unsigned_abs() as u32;341
Some(minutes)342
}343
344
fn parse_cal_address(params: &[(String, String)], value: &str) -> (String, Option<String>) {345
let mailto = value346
.trim()347
.trim_start_matches("mailto:")348
.trim_start_matches("MAILTO:")349
.to_owned();350
let cn = param(params, "CN").map(str::to_owned);351
(cn.unwrap_or_else(|| mailto.clone()), Some(mailto))352
}353
354
fn parse_attendee(params: &[(String, String)], value: &str) -> ParsedAttendee {355
let mailto = value356
.trim()357
.trim_start_matches("mailto:")358
.trim_start_matches("MAILTO:")359
.to_owned();360
ParsedAttendee {361
cn: param(params, "CN").map(str::to_owned),362
mailto,363
partstat: param(params, "PARTSTAT").map(str::to_owned),364
role: param(params, "ROLE").map(str::to_owned),365
}366
}367
368
fn unescape(value: &str) -> String {369
let mut out = String::with_capacity(value.len());370
let mut chars = value.chars();371
while let Some(ch) = chars.next() {372
if ch == '\\' {373
match chars.next() {374
Some('n') | Some('N') => out.push('\n'),375
Some(',') => out.push(','),376
Some(';') => out.push(';'),377
Some('\\') => out.push('\\'),378
Some(other) => out.push(other),379
None => out.push('\\'),380
}381
} else {382
out.push(ch);383
}384
}385
out386
}387
388
#[cfg(test)]389
mod tests {390
use super::*;391
392
#[test]393
fn unfolds_and_parses_all_day_exclusive_end() {394
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";395
let events = parse_calendar(ics);396
assert_eq!(events.len(), 1);397
assert!(events[0].all_day);398
assert_eq!(399
events[0].start,400
Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap()401
);402
assert_eq!(403
events[0].end,404
Utc.with_ymd_and_hms(2026, 1, 2, 0, 0, 0).unwrap()405
);406
}407
408
#[test]409
fn folds_long_summary() {410
let ics = "BEGIN:VEVENT\nUID:1\nSUMMARY:Hello\n world\nDTSTART:20260101T100000Z\nDTEND:20260101T110000Z\nEND:VEVENT\n";411
let events = parse_calendar(ics);412
assert_eq!(events[0].summary, "Hello world");413
}414
415
#[test]416
fn groups_override_separately() {417
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";418
let events = parse_calendar(ics);419
assert_eq!(events.len(), 2);420
assert!(events[0].rrule.is_some());421
assert!(events[1].recurrence_id.is_some());422
}423
}@@ -0,0 +1,54 @@
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!(
50
resolve_tzid("Europe/Zurich"),
51
Some(chrono_tz::Europe::Zurich)
52
);
53
}
54
}
@@ -0,0 +1,54 @@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!(50
resolve_tzid("Europe/Zurich"),51
Some(chrono_tz::Europe::Zurich)52
);53
}54
}@@ -0,0 +1,210 @@
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
/// Add EXDATE for one occurrence on the series master and bump SEQUENCE.
71
/// Leaves overrides and other VEVENT blocks untouched.
72
pub fn exclude_occurrence_from_ics(ics: &str, occurrence: DateTime<Utc>) -> Result<String, String> {
73
let stamp = format_utc(occurrence);
74
let mut out = Vec::new();
75
let mut in_event = false;
76
let mut is_master = false;
77
let mut event_lines: Vec<String> = Vec::new();
78
let mut patched = false;
79
80
for raw in ics.lines() {
81
let line = raw.trim_end_matches('\r').to_owned();
82
let upper = line.to_ascii_uppercase();
83
if upper == "BEGIN:VEVENT" {
84
in_event = true;
85
is_master = false;
86
event_lines = vec![line];
87
continue;
88
}
89
if !in_event {
90
out.push(line);
91
continue;
92
}
93
if upper == "END:VEVENT" {
94
event_lines.push(line);
95
if is_master {
96
out.extend(patch_master_exdate(event_lines, &stamp)?);
97
patched = true;
98
} else {
99
out.extend(event_lines);
100
}
101
in_event = false;
102
event_lines = Vec::new();
103
continue;
104
}
105
if upper.starts_with("RRULE") || upper.starts_with("RDATE") {
106
is_master = true;
107
}
108
event_lines.push(line);
109
}
110
if !patched {
111
return Err("CalDAV series master with RRULE/RDATE not found".into());
112
}
113
Ok(out.join("\r\n") + "\r\n")
114
}
115
116
fn patch_master_exdate(mut lines: Vec<String>, stamp: &str) -> Result<Vec<String>, String> {
117
let mut sequence_bumped = false;
118
let mut exdate_added = false;
119
for line in &mut lines {
120
let upper = line.to_ascii_uppercase();
121
if upper.starts_with("SEQUENCE:") {
122
let value = line.split_once(':').map(|(_, v)| v).unwrap_or("0");
123
let next = value.trim().parse::<u32>().unwrap_or(0).saturating_add(1);
124
*line = format!("SEQUENCE:{next}");
125
sequence_bumped = true;
126
}
127
if upper.starts_with("EXDATE") {
128
if line.contains(stamp) {
129
exdate_added = true;
130
} else if let Some((name, value)) = line.split_once(':') {
131
*line = format!("{name}:{value},{stamp}");
132
exdate_added = true;
133
}
134
}
135
}
136
if !sequence_bumped {
137
if let Some(idx) = lines
138
.iter()
139
.position(|l| l.to_ascii_uppercase().starts_with("UID:"))
140
{
141
lines.insert(idx + 1, "SEQUENCE:1".to_owned());
142
} else {
143
lines.insert(1, "SEQUENCE:1".to_owned());
144
}
145
}
146
if !exdate_added {
147
if let Some(idx) = lines.iter().position(|l| {
148
l.to_ascii_uppercase().starts_with("RRULE")
149
|| l.to_ascii_uppercase().starts_with("RDATE")
150
}) {
151
lines.insert(idx + 1, format!("EXDATE:{stamp}"));
152
} else {
153
return Err("CalDAV series master missing RRULE/RDATE".into());
154
}
155
}
156
Ok(lines)
157
}
158
159
fn format_utc(dt: DateTime<Utc>) -> String {
160
dt.format("%Y%m%dT%H%M%SZ").to_string()
161
}
162
163
fn escape(value: &str) -> String {
164
value
165
.replace('\\', "\\\\")
166
.replace('\n', "\\n")
167
.replace(',', "\\,")
168
.replace(';', "\\;")
169
}
170
171
#[cfg(test)]
172
mod tests {
173
use super::*;
174
use chrono::TimeZone;
175
176
#[test]
177
fn builds_without_method() {
178
let ics = build_vevent(
179
&CalDavEventDraft {
180
uid: "u1".into(),
181
summary: "Meet".into(),
182
start: Utc.with_ymd_and_hms(2026, 1, 1, 10, 0, 0).unwrap(),
183
end: Utc.with_ymd_and_hms(2026, 1, 1, 11, 0, 0).unwrap(),
184
all_day: false,
185
description: None,
186
location: None,
187
join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
188
attendees: vec!["a@b.c".into()],
189
repeat: Repeat::Never,
190
sequence: 0,
191
},
192
Utc.with_ymd_and_hms(2026, 1, 1, 9, 0, 0).unwrap(),
193
);
194
assert!(ics.contains("BEGIN:VCALENDAR"));
195
assert!(!ics.contains("METHOD:"));
196
assert!(ics.contains("URL:https://teams.microsoft.com/l/meetup-join/x"));
197
assert!(ics.contains("ATTENDEE:mailto:a@b.c"));
198
}
199
200
#[test]
201
fn exclude_occurrence_adds_exdate_and_keeps_rrule() {
202
let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:series\r\nSEQUENCE:2\r\nDTSTART:20260105T090000Z\r\nDTEND:20260105T100000Z\r\nRRULE:FREQ=WEEKLY\r\nSUMMARY:Standup\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
203
let patched =
204
exclude_occurrence_from_ics(ics, Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap())
205
.unwrap();
206
assert!(patched.contains("RRULE:FREQ=WEEKLY"));
207
assert!(patched.contains("EXDATE:20260112T090000Z"));
208
assert!(patched.contains("SEQUENCE:3"));
209
}
210
}
@@ -0,0 +1,210 @@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
/// Add EXDATE for one occurrence on the series master and bump SEQUENCE.71
/// Leaves overrides and other VEVENT blocks untouched.72
pub fn exclude_occurrence_from_ics(ics: &str, occurrence: DateTime<Utc>) -> Result<String, String> {73
let stamp = format_utc(occurrence);74
let mut out = Vec::new();75
let mut in_event = false;76
let mut is_master = false;77
let mut event_lines: Vec<String> = Vec::new();78
let mut patched = false;79
80
for raw in ics.lines() {81
let line = raw.trim_end_matches('\r').to_owned();82
let upper = line.to_ascii_uppercase();83
if upper == "BEGIN:VEVENT" {84
in_event = true;85
is_master = false;86
event_lines = vec![line];87
continue;88
}89
if !in_event {90
out.push(line);91
continue;92
}93
if upper == "END:VEVENT" {94
event_lines.push(line);95
if is_master {96
out.extend(patch_master_exdate(event_lines, &stamp)?);97
patched = true;98
} else {99
out.extend(event_lines);100
}101
in_event = false;102
event_lines = Vec::new();103
continue;104
}105
if upper.starts_with("RRULE") || upper.starts_with("RDATE") {106
is_master = true;107
}108
event_lines.push(line);109
}110
if !patched {111
return Err("CalDAV series master with RRULE/RDATE not found".into());112
}113
Ok(out.join("\r\n") + "\r\n")114
}115
116
fn patch_master_exdate(mut lines: Vec<String>, stamp: &str) -> Result<Vec<String>, String> {117
let mut sequence_bumped = false;118
let mut exdate_added = false;119
for line in &mut lines {120
let upper = line.to_ascii_uppercase();121
if upper.starts_with("SEQUENCE:") {122
let value = line.split_once(':').map(|(_, v)| v).unwrap_or("0");123
let next = value.trim().parse::<u32>().unwrap_or(0).saturating_add(1);124
*line = format!("SEQUENCE:{next}");125
sequence_bumped = true;126
}127
if upper.starts_with("EXDATE") {128
if line.contains(stamp) {129
exdate_added = true;130
} else if let Some((name, value)) = line.split_once(':') {131
*line = format!("{name}:{value},{stamp}");132
exdate_added = true;133
}134
}135
}136
if !sequence_bumped {137
if let Some(idx) = lines138
.iter()139
.position(|l| l.to_ascii_uppercase().starts_with("UID:"))140
{141
lines.insert(idx + 1, "SEQUENCE:1".to_owned());142
} else {143
lines.insert(1, "SEQUENCE:1".to_owned());144
}145
}146
if !exdate_added {147
if let Some(idx) = lines.iter().position(|l| {148
l.to_ascii_uppercase().starts_with("RRULE")149
|| l.to_ascii_uppercase().starts_with("RDATE")150
}) {151
lines.insert(idx + 1, format!("EXDATE:{stamp}"));152
} else {153
return Err("CalDAV series master missing RRULE/RDATE".into());154
}155
}156
Ok(lines)157
}158
159
fn format_utc(dt: DateTime<Utc>) -> String {160
dt.format("%Y%m%dT%H%M%SZ").to_string()161
}162
163
fn escape(value: &str) -> String {164
value165
.replace('\\', "\\\\")166
.replace('\n', "\\n")167
.replace(',', "\\,")168
.replace(';', "\\;")169
}170
171
#[cfg(test)]172
mod tests {173
use super::*;174
use chrono::TimeZone;175
176
#[test]177
fn builds_without_method() {178
let ics = build_vevent(179
&CalDavEventDraft {180
uid: "u1".into(),181
summary: "Meet".into(),182
start: Utc.with_ymd_and_hms(2026, 1, 1, 10, 0, 0).unwrap(),183
end: Utc.with_ymd_and_hms(2026, 1, 1, 11, 0, 0).unwrap(),184
all_day: false,185
description: None,186
location: None,187
join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),188
attendees: vec!["a@b.c".into()],189
repeat: Repeat::Never,190
sequence: 0,191
},192
Utc.with_ymd_and_hms(2026, 1, 1, 9, 0, 0).unwrap(),193
);194
assert!(ics.contains("BEGIN:VCALENDAR"));195
assert!(!ics.contains("METHOD:"));196
assert!(ics.contains("URL:https://teams.microsoft.com/l/meetup-join/x"));197
assert!(ics.contains("ATTENDEE:mailto:a@b.c"));198
}199
200
#[test]201
fn exclude_occurrence_adds_exdate_and_keeps_rrule() {202
let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:series\r\nSEQUENCE:2\r\nDTSTART:20260105T090000Z\r\nDTEND:20260105T100000Z\r\nRRULE:FREQ=WEEKLY\r\nSUMMARY:Standup\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";203
let patched =204
exclude_occurrence_from_ics(ics, Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap())205
.unwrap();206
assert!(patched.contains("RRULE:FREQ=WEEKLY"));207
assert!(patched.contains("EXDATE:20260112T090000Z"));208
assert!(patched.contains("SEQUENCE:3"));209
}210
}@@ -2,6 +2,7 @@ pub mod activity_feed;
2
2
pub mod activity_mentions;
3
3
pub mod ams;
4
4
pub mod bot_profiles;
5
pub mod caldav;
5
6
pub mod calendar;
6
7
pub mod calllog;
7
8
pub mod cards;
@@ -20,6 +21,7 @@ pub mod forward;
20
21
pub mod gifs;
21
22
pub mod google_calendar;
22
23
pub mod graph_events;
24
pub mod ical;
23
25
mod json_id;
24
26
pub use json_id::id_text;
25
27
pub mod language_settings;
@@ -56,12 +58,16 @@ pub use activity_feed::{
56
58
};
57
59
pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};
58
60
pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
61
pub use caldav::{
62
CalDavClient, CalDavEvent, ListedCalendar, discover as discover_caldav, href_from_object_id,
63
new_event_uid, object_id_for, partstat_for_reply,
64
};
59
65
pub use calendar::{
60
66
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,
67
CreatedEvent, DialIn, EventAttendee, HomeCalendar, NewEvent, PersonSchedule, Reminder, Repeat,
68
Reply, ResponseType, ShowAs, apply_event_details, join_info_text, meet_now_join_url,
69
merge_calendar_events, new_event_body, new_event_body_with_join, normalize_join_url,
70
parse_calendar_events, parse_created_event, strip_html, truncate_preview,
65
71
};
66
72
pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
67
73
pub use cards::{
@@ -85,8 +91,12 @@ pub use gifs::{Gif, Gifs};
85
91
pub use google_calendar::{
86
92
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
87
93
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,
94
parse_calendar_list, parse_google_events, refresh_access_token, rrule_for_repeat,
95
wait_for_code,
96
};
97
pub use ical::{
98
CalDavEventDraft, build_vevent, exclude_occurrence_from_ics, expand_events, parse_calendar,
99
teams_join_url,
90
100
};
91
101
pub use language_settings::{
92
102
LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,
@@ -2,6 +2,7 @@ pub mod activity_feed;2
pub mod activity_mentions;2
pub mod activity_mentions;3
pub mod ams;3
pub mod ams;4
pub mod bot_profiles;4
pub mod bot_profiles;5
pub mod caldav;5
pub mod calendar;6
pub mod calendar;6
pub mod calllog;7
pub mod calllog;7
pub mod cards;8
pub mod cards;@@ -20,6 +21,7 @@ pub mod forward;20
pub mod gifs;21
pub mod gifs;21
pub mod google_calendar;22
pub mod google_calendar;22
pub mod graph_events;23
pub mod graph_events;24
pub mod ical;23
mod json_id;25
mod json_id;24
pub use json_id::id_text;26
pub use json_id::id_text;25
pub mod language_settings;27
pub mod language_settings;@@ -56,12 +58,16 @@ pub use activity_feed::{56
};58
};57
pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};59
pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};58
pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};60
pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};61
pub use caldav::{62
CalDavClient, CalDavEvent, ListedCalendar, discover as discover_caldav, href_from_object_id,63
new_event_uid, object_id_for, partstat_for_reply,64
};59
pub use calendar::{65
pub use calendar::{60
Attendee, AttendeeResponseCounts, BusyTime, Calendar, CalendarEvent, CalendarSource,66
Attendee, AttendeeResponseCounts, BusyTime, Calendar, CalendarEvent, CalendarSource,61
CreatedEvent, DialIn, EventAttendee, NewEvent, PersonSchedule, Reminder, Repeat, Reply,67
CreatedEvent, DialIn, EventAttendee, HomeCalendar, NewEvent, PersonSchedule, Reminder, Repeat,62
ResponseType, ShowAs, apply_event_details, join_info_text, meet_now_join_url, new_event_body,68
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,69
merge_calendar_events, new_event_body, new_event_body_with_join, normalize_join_url,64
truncate_preview,70
parse_calendar_events, parse_created_event, strip_html, truncate_preview,65
};71
};66
pub use calllog::{CallDirection, CallLogEntry, CallOutcome};72
pub use calllog::{CallDirection, CallLogEntry, CallOutcome};67
pub use cards::{73
pub use cards::{@@ -85,8 +91,12 @@ pub use gifs::{Gif, Gifs};85
pub use google_calendar::{91
pub use google_calendar::{86
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,92
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,87
client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,93
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,94
parse_calendar_list, parse_google_events, refresh_access_token, rrule_for_repeat,89
refresh_access_token, rrule_for_repeat, wait_for_code,95
wait_for_code,96
};97
pub use ical::{98
CalDavEventDraft, build_vevent, exclude_occurrence_from_ics, expand_events, parse_calendar,99
teams_join_url,90
};100
};91
pub use language_settings::{101
pub use language_settings::{92
LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,102
LanguageSettings, LanguageSettingsClient, TranslationBehavior, authoring_patch, behavior_patch,@@ -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, ¤t)?;
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_id63
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)]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
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]143
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]95
pub struct CalendarAccounts {144
pub 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
108
impl Default for CalendarAccounts {161
impl 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_accounts211
.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_accounts216
self.google_accounts144
.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_accounts223
.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_subscriptions229
.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_targets149
!(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.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.summary307
|| fresh_cal.writable != calendar.writable308
|| 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, ¤t)?;320
}321
Ok(())322
}323
203
#[cfg(test)]324
#[cfg(test)]204
mod tests {325
mod 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();@@ -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;26
mod time;26
mod time;27
27
28
pub use calendar_accounts::{28
pub 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
};33
pub use error::{Error, Result};33
pub use error::{Error, Result};34
pub use image_files::ImageFileCache;34
pub use image_files::ImageFileCache;@@ -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
---2
status: accepted3
date: 2026-11-164
---5
6
# ADR 0019: CalDAV with app password and OS keyring7
8
## Context9
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
## Decision15
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
## Consequences23
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.@@ -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
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`.