feat(calendar): optional Google Calendar accounts beside Outlook
OAuth Desktop + PKCE (TEAMS_GOOGLE_CLIENT_ID). Merge week/month by iCal UID or Teams join URL, home calendar + dual-write targets, source-routed RSVP/delete. Without the env vars the calendar stays Outlook-only.
@@ -111,8 +111,9 @@ dependencies = [
111
111
112
112
[[package]]
113
113
name = "agents"
114
version = "0.1.0"
114
version = "0.3.0"
115
115
dependencies = [
116
"reqwest 0.13.5",
116
117
"serde",
117
118
"serde_json",
118
119
"tempfile",
@@ -273,13 +274,14 @@ checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
273
274
274
275
[[package]]
275
276
name = "app"
276
version = "0.1.0"
277
version = "0.3.0"
277
278
dependencies = [
278
279
"agents",
279
280
"app-base",
280
281
"app-call-model",
281
282
"app-state",
282
283
"app-ui-kit",
284
"browser",
283
285
"calling",
284
286
"chatsvc",
285
287
"chrono",
@@ -305,7 +307,7 @@ dependencies = [
305
307
306
308
[[package]]
307
309
name = "app-base"
308
version = "0.1.0"
310
version = "0.3.0"
309
311
dependencies = [
310
312
"agents",
311
313
"calling",
@@ -322,11 +324,13 @@ dependencies = [
322
324
"raw-window-handle",
323
325
"resvg 0.46.0",
324
326
"rodio",
327
"rust-i18n",
325
328
"serde",
326
329
"serde_json",
327
330
"session",
328
331
"sha2 0.10.9",
329
332
"store",
333
"sys-locale",
330
334
"teams-core",
331
335
"tempfile",
332
336
"tokio",
@@ -337,7 +341,7 @@ dependencies = [
337
341
338
342
[[package]]
339
343
name = "app-call-model"
340
version = "0.1.0"
344
version = "0.3.0"
341
345
dependencies = [
342
346
"agents",
343
347
"app-base",
@@ -363,7 +367,7 @@ dependencies = [
363
367
364
368
[[package]]
365
369
name = "app-state"
366
version = "0.1.0"
370
version = "0.3.0"
367
371
dependencies = [
368
372
"agents",
369
373
"app-base",
@@ -392,7 +396,7 @@ dependencies = [
392
396
393
397
[[package]]
394
398
name = "app-ui-kit"
395
version = "0.1.0"
399
version = "0.3.0"
396
400
dependencies = [
397
401
"app-base",
398
402
"gpui-kit",
@@ -1086,7 +1090,7 @@ dependencies = [
1086
1090
1087
1091
[[package]]
1088
1092
name = "browser"
1089
version = "0.1.0"
1093
version = "0.3.0"
1090
1094
dependencies = [
1091
1095
"directories",
1092
1096
"futures-util",
@@ -1195,7 +1199,7 @@ dependencies = [
1195
1199
1196
1200
[[package]]
1197
1201
name = "calling"
1198
version = "0.1.0"
1202
version = "0.3.0"
1199
1203
dependencies = [
1200
1204
"base64 0.22.1",
1201
1205
"chatsvc",
@@ -1221,6 +1225,8 @@ dependencies = [
1221
1225
"webview",
1222
1226
"windows 0.62.2",
1223
1227
"windows-core 0.62.2",
1228
"zune-core 0.5.3",
1229
"zune-jpeg 0.5.15",
1224
1230
]
1225
1231
1226
1232
[[package]]
@@ -1361,18 +1367,22 @@ dependencies = [
1361
1367
1362
1368
[[package]]
1363
1369
name = "chatsvc"
1364
version = "0.1.0"
1370
version = "0.3.0"
1365
1371
dependencies = [
1366
1372
"base64 0.22.1",
1367
1373
"chrono",
1368
1374
"futures-util",
1369
1375
"percent-encoding",
1376
"rand 0.9.5",
1377
"reqwest 0.13.5",
1370
1378
"serde",
1371
1379
"serde_json",
1372
1380
"session",
1381
"sha2 0.10.9",
1373
1382
"thiserror 2.0.21",
1374
1383
"tokio",
1375
1384
"tokio-tungstenite",
1385
"url",
1376
1386
"uuid",
1377
1387
]
1378
1388
@@ -1454,7 +1464,7 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
1454
1464
1455
1465
[[package]]
1456
1466
name = "cli"
1457
version = "0.1.0"
1467
version = "0.3.0"
1458
1468
dependencies = [
1459
1469
"chrono",
1460
1470
"clap",
@@ -4050,8 +4060,6 @@ dependencies = [
4050
4060
[[package]]
4051
4061
name = "gpui-pre-wgpu"
4052
4062
version = "0.3.8"
4053
source = "registry+https://github.com/rust-lang/crates.io-index"
4054
checksum = "439c5421cafe1a7cf68d0c0ae5cc82b26fad6b0e6345ac98d20acaf1f2463914"
4055
4063
dependencies = [
4056
4064
"anyhow",
4057
4065
"bytemuck",
@@ -4147,7 +4155,7 @@ dependencies = [
4147
4155
4148
4156
[[package]]
4149
4157
name = "graph"
4150
version = "0.1.0"
4158
version = "0.3.0"
4151
4159
dependencies = [
4152
4160
"base64 0.22.1",
4153
4161
"chrono",
@@ -5188,8 +5196,6 @@ dependencies = [
5188
5196
[[package]]
5189
5197
name = "libwebrtc"
5190
5198
version = "0.3.51"
5191
source = "registry+https://github.com/rust-lang/crates.io-index"
5192
checksum = "14f9145a63a8439508a9b5b51dffa4b1c12f812f49fcc4310ebae3d467f639ab"
5193
5199
dependencies = [
5194
5200
"cxx",
5195
5201
"glib 0.21.5",
@@ -5493,7 +5499,7 @@ dependencies = [
5493
5499
5494
5500
[[package]]
5495
5501
name = "mcp"
5496
version = "0.1.0"
5502
version = "0.3.0"
5497
5503
dependencies = [
5498
5504
"axum",
5499
5505
"base64 0.22.1",
@@ -7702,6 +7708,7 @@ dependencies = [
7702
7708
"rustls-platform-verifier",
7703
7709
"serde",
7704
7710
"serde_json",
7711
"serde_urlencoded",
7705
7712
"sync_wrapper",
7706
7713
"tokio",
7707
7714
"tokio-rustls",
@@ -8474,9 +8481,12 @@ dependencies = [
8474
8481
8475
8482
[[package]]
8476
8483
name = "session"
8477
version = "0.1.0"
8484
version = "0.3.0"
8478
8485
dependencies = [
8486
"base64 0.22.1",
8479
8487
"futures-util",
8488
"reqwest 0.13.5",
8489
"rustls",
8480
8490
"serde",
8481
8491
"serde_json",
8482
8492
"thiserror 2.0.21",
@@ -8741,12 +8751,13 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
8741
8751
8742
8752
[[package]]
8743
8753
name = "store"
8744
version = "0.1.0"
8754
version = "0.3.0"
8745
8755
dependencies = [
8746
8756
"chrono",
8747
8757
"directories",
8748
8758
"rusqlite",
8749
8759
"scraper",
8760
"serde",
8750
8761
"serde_json",
8751
8762
"tempfile",
8752
8763
"thiserror 2.0.21",
@@ -9188,12 +9199,13 @@ dependencies = [
9188
9199
9189
9200
[[package]]
9190
9201
name = "teams-core"
9191
version = "0.1.0"
9202
version = "0.3.0"
9192
9203
dependencies = [
9193
9204
"chatsvc",
9194
9205
"chrono",
9195
9206
"futures-util",
9196
9207
"graph",
9208
"iana-time-zone",
9197
9209
"percent-encoding",
9198
9210
"regex",
9199
9211
"scraper",
@@ -9442,7 +9454,11 @@ checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"
9442
9454
dependencies = [
9443
9455
"futures-util",
9444
9456
"log",
9457
"rustls",
9458
"rustls-native-certs",
9459
"rustls-pki-types",
9445
9460
"tokio",
9461
"tokio-rustls",
9446
9462
"tungstenite",
9447
9463
]
9448
9464
@@ -9940,6 +9956,8 @@ dependencies = [
9940
9956
"httparse",
9941
9957
"log",
9942
9958
"rand 0.9.5",
9959
"rustls",
9960
"rustls-pki-types",
9943
9961
"sha1",
9944
9962
"thiserror 2.0.21",
9945
9963
"utf-8",
@@ -10576,7 +10594,7 @@ dependencies = [
10576
10594
10577
10595
[[package]]
10578
10596
name = "webview"
10579
version = "0.1.0"
10597
version = "0.3.0"
10580
10598
dependencies = [
10581
10599
"serde_json",
10582
10600
"session",
@@ -111,8 +111,9 @@ dependencies = [111
111
112
[[package]]112
[[package]]113
name = "agents"113
name = "agents"114
version = "0.1.0"114
version = "0.3.0"115
dependencies = [115
dependencies = [116
"reqwest 0.13.5",116
"serde",117
"serde",117
"serde_json",118
"serde_json",118
"tempfile",119
"tempfile",@@ -273,13 +274,14 @@ checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"273
274
274
[[package]]275
[[package]]275
name = "app"276
name = "app"276
version = "0.1.0"277
version = "0.3.0"277
dependencies = [278
dependencies = [278
"agents",279
"agents",279
"app-base",280
"app-base",280
"app-call-model",281
"app-call-model",281
"app-state",282
"app-state",282
"app-ui-kit",283
"app-ui-kit",284
"browser",283
"calling",285
"calling",284
"chatsvc",286
"chatsvc",285
"chrono",287
"chrono",@@ -305,7 +307,7 @@ dependencies = [305
307
306
[[package]]308
[[package]]307
name = "app-base"309
name = "app-base"308
version = "0.1.0"310
version = "0.3.0"309
dependencies = [311
dependencies = [310
"agents",312
"agents",311
"calling",313
"calling",@@ -322,11 +324,13 @@ dependencies = [322
"raw-window-handle",324
"raw-window-handle",323
"resvg 0.46.0",325
"resvg 0.46.0",324
"rodio",326
"rodio",327
"rust-i18n",325
"serde",328
"serde",326
"serde_json",329
"serde_json",327
"session",330
"session",328
"sha2 0.10.9",331
"sha2 0.10.9",329
"store",332
"store",333
"sys-locale",330
"teams-core",334
"teams-core",331
"tempfile",335
"tempfile",332
"tokio",336
"tokio",@@ -337,7 +341,7 @@ dependencies = [337
341
338
[[package]]342
[[package]]339
name = "app-call-model"343
name = "app-call-model"340
version = "0.1.0"344
version = "0.3.0"341
dependencies = [345
dependencies = [342
"agents",346
"agents",343
"app-base",347
"app-base",@@ -363,7 +367,7 @@ dependencies = [363
367
364
[[package]]368
[[package]]365
name = "app-state"369
name = "app-state"366
version = "0.1.0"370
version = "0.3.0"367
dependencies = [371
dependencies = [368
"agents",372
"agents",369
"app-base",373
"app-base",@@ -392,7 +396,7 @@ dependencies = [392
396
393
[[package]]397
[[package]]394
name = "app-ui-kit"398
name = "app-ui-kit"395
version = "0.1.0"399
version = "0.3.0"396
dependencies = [400
dependencies = [397
"app-base",401
"app-base",398
"gpui-kit",402
"gpui-kit",@@ -1086,7 +1090,7 @@ dependencies = [1086
1090
1087
[[package]]1091
[[package]]1088
name = "browser"1092
name = "browser"1089
version = "0.1.0"1093
version = "0.3.0"1090
dependencies = [1094
dependencies = [1091
"directories",1095
"directories",1092
"futures-util",1096
"futures-util",@@ -1195,7 +1199,7 @@ dependencies = [1195
1199
1196
[[package]]1200
[[package]]1197
name = "calling"1201
name = "calling"1198
version = "0.1.0"1202
version = "0.3.0"1199
dependencies = [1203
dependencies = [1200
"base64 0.22.1",1204
"base64 0.22.1",1201
"chatsvc",1205
"chatsvc",@@ -1221,6 +1225,8 @@ dependencies = [1221
"webview",1225
"webview",1222
"windows 0.62.2",1226
"windows 0.62.2",1223
"windows-core 0.62.2",1227
"windows-core 0.62.2",1228
"zune-core 0.5.3",1229
"zune-jpeg 0.5.15",1224
]1230
]1225
1231
1226
[[package]]1232
[[package]]@@ -1361,18 +1367,22 @@ dependencies = [1361
1367
1362
[[package]]1368
[[package]]1363
name = "chatsvc"1369
name = "chatsvc"1364
version = "0.1.0"1370
version = "0.3.0"1365
dependencies = [1371
dependencies = [1366
"base64 0.22.1",1372
"base64 0.22.1",1367
"chrono",1373
"chrono",1368
"futures-util",1374
"futures-util",1369
"percent-encoding",1375
"percent-encoding",1376
"rand 0.9.5",1377
"reqwest 0.13.5",1370
"serde",1378
"serde",1371
"serde_json",1379
"serde_json",1372
"session",1380
"session",1381
"sha2 0.10.9",1373
"thiserror 2.0.21",1382
"thiserror 2.0.21",1374
"tokio",1383
"tokio",1375
"tokio-tungstenite",1384
"tokio-tungstenite",1385
"url",1376
"uuid",1386
"uuid",1377
]1387
]1378
1388
@@ -1454,7 +1464,7 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"1454
1464
1455
[[package]]1465
[[package]]1456
name = "cli"1466
name = "cli"1457
version = "0.1.0"1467
version = "0.3.0"1458
dependencies = [1468
dependencies = [1459
"chrono",1469
"chrono",1460
"clap",1470
"clap",@@ -4050,8 +4060,6 @@ dependencies = [4050
[[package]]4060
[[package]]4051
name = "gpui-pre-wgpu"4061
name = "gpui-pre-wgpu"4052
version = "0.3.8"4062
version = "0.3.8"4053
source = "registry+https://github.com/rust-lang/crates.io-index"4054
checksum = "439c5421cafe1a7cf68d0c0ae5cc82b26fad6b0e6345ac98d20acaf1f2463914"4055
dependencies = [4063
dependencies = [4056
"anyhow",4064
"anyhow",4057
"bytemuck",4065
"bytemuck",@@ -4147,7 +4155,7 @@ dependencies = [4147
4155
4148
[[package]]4156
[[package]]4149
name = "graph"4157
name = "graph"4150
version = "0.1.0"4158
version = "0.3.0"4151
dependencies = [4159
dependencies = [4152
"base64 0.22.1",4160
"base64 0.22.1",4153
"chrono",4161
"chrono",@@ -5188,8 +5196,6 @@ dependencies = [5188
[[package]]5196
[[package]]5189
name = "libwebrtc"5197
name = "libwebrtc"5190
version = "0.3.51"5198
version = "0.3.51"5191
source = "registry+https://github.com/rust-lang/crates.io-index"5192
checksum = "14f9145a63a8439508a9b5b51dffa4b1c12f812f49fcc4310ebae3d467f639ab"5193
dependencies = [5199
dependencies = [5194
"cxx",5200
"cxx",5195
"glib 0.21.5",5201
"glib 0.21.5",@@ -5493,7 +5499,7 @@ dependencies = [5493
5499
5494
[[package]]5500
[[package]]5495
name = "mcp"5501
name = "mcp"5496
version = "0.1.0"5502
version = "0.3.0"5497
dependencies = [5503
dependencies = [5498
"axum",5504
"axum",5499
"base64 0.22.1",5505
"base64 0.22.1",@@ -7702,6 +7708,7 @@ dependencies = [7702
"rustls-platform-verifier",7708
"rustls-platform-verifier",7703
"serde",7709
"serde",7704
"serde_json",7710
"serde_json",7711
"serde_urlencoded",7705
"sync_wrapper",7712
"sync_wrapper",7706
"tokio",7713
"tokio",7707
"tokio-rustls",7714
"tokio-rustls",@@ -8474,9 +8481,12 @@ dependencies = [8474
8481
8475
[[package]]8482
[[package]]8476
name = "session"8483
name = "session"8477
version = "0.1.0"8484
version = "0.3.0"8478
dependencies = [8485
dependencies = [8486
"base64 0.22.1",8479
"futures-util",8487
"futures-util",8488
"reqwest 0.13.5",8489
"rustls",8480
"serde",8490
"serde",8481
"serde_json",8491
"serde_json",8482
"thiserror 2.0.21",8492
"thiserror 2.0.21",@@ -8741,12 +8751,13 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"8741
8751
8742
[[package]]8752
[[package]]8743
name = "store"8753
name = "store"8744
version = "0.1.0"8754
version = "0.3.0"8745
dependencies = [8755
dependencies = [8746
"chrono",8756
"chrono",8747
"directories",8757
"directories",8748
"rusqlite",8758
"rusqlite",8749
"scraper",8759
"scraper",8760
"serde",8750
"serde_json",8761
"serde_json",8751
"tempfile",8762
"tempfile",8752
"thiserror 2.0.21",8763
"thiserror 2.0.21",@@ -9188,12 +9199,13 @@ dependencies = [9188
9199
9189
[[package]]9200
[[package]]9190
name = "teams-core"9201
name = "teams-core"9191
version = "0.1.0"9202
version = "0.3.0"9192
dependencies = [9203
dependencies = [9193
"chatsvc",9204
"chatsvc",9194
"chrono",9205
"chrono",9195
"futures-util",9206
"futures-util",9196
"graph",9207
"graph",9208
"iana-time-zone",9197
"percent-encoding",9209
"percent-encoding",9198
"regex",9210
"regex",9199
"scraper",9211
"scraper",@@ -9442,7 +9454,11 @@ checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"9442
dependencies = [9454
dependencies = [9443
"futures-util",9455
"futures-util",9444
"log",9456
"log",9457
"rustls",9458
"rustls-native-certs",9459
"rustls-pki-types",9445
"tokio",9460
"tokio",9461
"tokio-rustls",9446
"tungstenite",9462
"tungstenite",9447
]9463
]9448
9464
@@ -9940,6 +9956,8 @@ dependencies = [9940
"httparse",9956
"httparse",9941
"log",9957
"log",9942
"rand 0.9.5",9958
"rand 0.9.5",9959
"rustls",9960
"rustls-pki-types",9943
"sha1",9961
"sha1",9944
"thiserror 2.0.21",9962
"thiserror 2.0.21",9945
"utf-8",9963
"utf-8",@@ -10576,7 +10594,7 @@ dependencies = [10576
10594
10577
[[package]]10595
[[package]]10578
name = "webview"10596
name = "webview"10579
version = "0.1.0"10597
version = "0.3.0"10580
dependencies = [10598
dependencies = [10581
"serde_json",10599
"serde_json",10582
"session",10600
"session",@@ -43,6 +43,7 @@ reqwest_client = { package = "gpui-pre-reqwest-client", version = "=0.3.8" }
43
43
calling = { path = "crates/calling" }
44
44
chatsvc = { path = "crates/chatsvc" }
45
45
webview = { path = "crates/webview" }
46
browser = { path = "crates/browser" }
46
47
47
48
[patch.crates-io]
48
49
gpui-base = { path = "vendor/gpui-base" }
@@ -43,6 +43,7 @@ reqwest_client = { package = "gpui-pre-reqwest-client", version = "=0.3.8" }43
calling = { path = "crates/calling" }43
calling = { path = "crates/calling" }44
chatsvc = { path = "crates/chatsvc" }44
chatsvc = { path = "crates/chatsvc" }45
webview = { path = "crates/webview" }45
webview = { path = "crates/webview" }46
browser = { path = "crates/browser" }46
47
47
[patch.crates-io]48
[patch.crates-io]48
gpui-base = { path = "vendor/gpui-base" }49
gpui-base = { path = "vendor/gpui-base" }@@ -61,7 +61,7 @@
61
61
**Calls**
62
62
- Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
63
63
- Phone button in 1:1 and group chat headers: callee tiles show Calling and Ringing, Cancel while ringing, notices like "Bea declined" or "No answer"
64
- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time
64
- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time. On Wayland, sharing opens the desktop ScreenCast portal dialog, including on KDE, GNOME and Hyprland
65
65
- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
66
66
- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
67
67
- After every call a pseudonymized test report (JSON and Markdown, newest 30) is saved to the app data folder `call-reports`; toast "Test report saved" with Open folder, Settings > Devices switch
@@ -74,6 +74,11 @@
74
74
- One-click install for Claude Code, Codex CLI, Copilot CLI, VS Code and Cursor, Windows and WSL. WSL needs `networkingMode=mirrored`
75
75
- Delegate a message to a coding-agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar: progress chip, Agents page, toast when it finishes, Open session
76
76
77
**Calendar (fork)**
78
- Outlook calendar as today, plus optional Google Calendar accounts (Settings > Calendar)
79
- Merge by iCal UID / Teams join URL; New meeting writes to the home calendar and optional extra targets
80
- Google OAuth Desktop (PKCE): set `TEAMS_GOOGLE_CLIENT_ID` and optionally `TEAMS_GOOGLE_CLIENT_SECRET` before Connect
81
77
82
**App**
78
83
- Dark theme, opens instantly from the cache
79
84
- Self-update from an update folder
@@ -84,8 +89,8 @@
84
89
| Platform | State |
85
90
|---|---|
86
91
| 🪟 Windows | Main target. Login through an embedded WebView2 |
87
| 🐧 Linux | Connects to a Chrome started with `--remote-debugging-port=9222` and signed in to Teams on the web. The app opens an Outlook on the web tab next to it when missing (some tenants grant chat scopes only to Outlook). Built-in login is planned |
88
| 🍎 macOS | Experimental. Universal arm64 + x86_64 binary, connects to a Chrome like Linux |
92
| 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. The app opens an Outlook on the web tab next to Teams when missing (some tenants grant chat scopes only to Outlook). Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Built-in login without Chrome is planned |
93
| 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
89
94
90
95
The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
91
96
@@ -97,6 +102,21 @@ Try it with demo data, no account needed:
97
102
cargo run -p app -- --demo
98
103
```
99
104
105
### Google Calendar (optional)
106
107
1. Create an OAuth Desktop client in Google Cloud Console with redirect `http://127.0.0.1:<port>/` (loopback; the app picks a free port).
108
2. Export before starting the app:
109
110
```bash
111
export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"
112
# only if the client has a secret:
113
export TEAMS_GOOGLE_CLIENT_SECRET="…"
114
```
115
116
3. Settings > Calendar > Connect Google, then choose home calendar and optional dual-write targets.
117
118
Without these env vars the calendar stays Outlook-only.
119
100
120
| Task | Command |
101
121
|---|---|
102
122
| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |
@@ -61,7 +61,7 @@61
**Calls**61
**Calls**62
- Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats62
- Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats63
- Phone button in 1:1 and group chat headers: callee tiles show Calling and Ringing, Cancel while ringing, notices like "Bea declined" or "No answer"63
- Phone button in 1:1 and group chat headers: callee tiles show Calling and Ringing, Cancel while ringing, notices like "Bea declined" or "No answer"64
- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time64
- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time. On Wayland, sharing opens the desktop ScreenCast portal dialog, including on KDE, GNOME and Hyprland65
- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity65
- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity66
- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer66
- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer67
- After every call a pseudonymized test report (JSON and Markdown, newest 30) is saved to the app data folder `call-reports`; toast "Test report saved" with Open folder, Settings > Devices switch67
- After every call a pseudonymized test report (JSON and Markdown, newest 30) is saved to the app data folder `call-reports`; toast "Test report saved" with Open folder, Settings > Devices switch@@ -74,6 +74,11 @@74
- One-click install for Claude Code, Codex CLI, Copilot CLI, VS Code and Cursor, Windows and WSL. WSL needs `networkingMode=mirrored`74
- One-click install for Claude Code, Codex CLI, Copilot CLI, VS Code and Cursor, Windows and WSL. WSL needs `networkingMode=mirrored`75
- Delegate a message to a coding-agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar: progress chip, Agents page, toast when it finishes, Open session75
- Delegate a message to a coding-agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar: progress chip, Agents page, toast when it finishes, Open session76
76
77
**Calendar (fork)**78
- Outlook calendar as today, plus optional Google Calendar accounts (Settings > Calendar)79
- Merge by iCal UID / Teams join URL; New meeting writes to the home calendar and optional extra targets80
- Google OAuth Desktop (PKCE): set `TEAMS_GOOGLE_CLIENT_ID` and optionally `TEAMS_GOOGLE_CLIENT_SECRET` before Connect81
77
**App**82
**App**78
- Dark theme, opens instantly from the cache83
- Dark theme, opens instantly from the cache79
- Self-update from an update folder84
- Self-update from an update folder@@ -84,8 +89,8 @@84
| Platform | State |89
| Platform | State |85
|---|---|90
|---|---|86
| 🪟 Windows | Main target. Login through an embedded WebView2 |91
| 🪟 Windows | Main target. Login through an embedded WebView2 |87
| 🐧 Linux | Connects to a Chrome started with `--remote-debugging-port=9222` and signed in to Teams on the web. The app opens an Outlook on the web tab next to it when missing (some tenants grant chat scopes only to Outlook). Built-in login is planned |92
| 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. The app opens an Outlook on the web tab next to Teams when missing (some tenants grant chat scopes only to Outlook). Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Built-in login without Chrome is planned |88
| 🍎 macOS | Experimental. Universal arm64 + x86_64 binary, connects to a Chrome like Linux |93
| 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |89
94
90
The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).95
The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).91
96
@@ -97,6 +102,21 @@ Try it with demo data, no account needed:97
cargo run -p app -- --demo102
cargo run -p app -- --demo98
```103
```99
104
105
### Google Calendar (optional)106
107
1. Create an OAuth Desktop client in Google Cloud Console with redirect `http://127.0.0.1:<port>/` (loopback; the app picks a free port).108
2. Export before starting the app:109
110
```bash111
export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"112
# only if the client has a secret:113
export TEAMS_GOOGLE_CLIENT_SECRET="…"114
```115
116
3. Settings > Calendar > Connect Google, then choose home calendar and optional dual-write targets.117
118
Without these env vars the calendar stays Outlook-only.119
100
| Task | Command |120
| Task | Command |101
|---|---|121
|---|---|102
| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |122
| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |@@ -34,7 +34,7 @@ Feature parity with the Microsoft Teams desktop client.
34
34
| Start from the local cache, no spinner | Done | |
35
35
| Self-update | Done | |
36
36
| Tray icon, close to tray | Done | |
37
| Sign in on Linux without starting Chrome by hand | Partial | Works with a Chrome on a debug port |
37
| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
38
38
| Single instance, second start brings the window to front | Done | |
39
39
40
40
## Chat list
@@ -181,7 +181,7 @@ Feature parity with the Microsoft Teams desktop client.
181
181
| Recording | Done | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video, audio only, transcription only and every stop variant run live; a stop sent while the recorder still settles is retried. Consent needs a tenant with the policy on |
182
182
| Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; occurrences, details and delete run live against real recordings. Transcription-only sessions (item media source `Transcript`) show the transcript without a recording card. "Audio only" comes from the chat event (`videoContent="CurtainOnly"`), with the video size check as fallback. Both signals read live on real recordings, fixtures unit tested; the transcript-only path was not run live |
183
183
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |
184
| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto (device track with WebRTC echo cancellation, AGC, NS plus RNNoise ML suppression), Low (same without RNNoise) or Off, Music mode keeps echo cancellation only. No High level. Off and Music mode run a cpal mic through our own APM; checked with synthetic sources only, not with a real mic in a call |
184
| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto and Low on Linux keep the Pulse ADM device track (same path as Web Teams); on Windows Auto runs the software chain with DeepFilterNet. Off and Music mode run a cpal mic through our own APM. No High level. Checked with synthetic sources; Linux Auto aligned with Pulse after the mic-quality fix |
185
185
| Push to talk | Partial | Hold Ctrl+Space while muted to talk, release to mute; main window focused, not inside text fields; hint chip on the stage. Unit tested, not tried on the Windows build |
186
186
| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |
187
187
| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |
@@ -193,9 +193,10 @@ Feature parity with the Microsoft Teams desktop client.
193
193
| Calls in chat history | Done | Card per call in the chat on the caller's side: "Call ended" with duration and end time, red "Missed call" with Call back, "Meeting started" / "Meeting ended", live start with Join. Started card hides once the call ended. From Graph call events, cached chats refetch once. Missed incoming call not seen live yet |
194
194
| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |
195
195
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
196
| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Graph `POST /me/events` with `isOnlineMeeting` and `teamsForBusiness`, local wall time in the own mailbox time zone (series keep their time across DST, weekday from the local date). Body building unit tested; never run against a real calendar |
197
| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Graph `accept`, `tentativelyAccept`, `decline`, falls back to the iCalUId lookup when the Teams id is not a Graph id. Not run against a real invitation |
198
| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Snooze and X are saved to the Outlook reminder (Graph snoozeReminder / dismissReminder, occurrence id); reminders snoozed or dismissed in Outlook or on another device are read from reminderView every 60 s near a meeting and are not shown again. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar; push event 128 not wired (the realtime layer does not receive it) |
196
| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Outlook-only home keeps Graph `POST /me/events` with `isOnlineMeeting`. With Google home or extra write targets: Teams join link first, then inserts per target (Outlook with join in location; Google `events.insert`). Settings > Calendar chooses home + dual-write. Body builders unit tested; live Google create needs `TEAMS_GOOGLE_CLIENT_ID` |
197
| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Outlook: Graph `accept` / `tentativelyAccept` / `decline` (+ iCalUId fallback). Google: Calendar API attendee `responseStatus` patch with `sendUpdates`. Source shown on calendar blocks |
198
| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Outlook: Snooze and X go to Graph snoozeReminder / dismissReminder; reminderView every 60 s near a meeting. Google: snooze/dismiss stay local only. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar (Outlook + optional Google merge); push event 128 not wired |
199
| Google Calendar accounts | Partial | Settings > Calendar: Connect Google (OAuth Desktop + PKCE, env `TEAMS_GOOGLE_CLIENT_ID` / optional secret), list calendars, home calendar, extra write targets. Poll merges with Outlook by iCal UID / Teams join URL. Disconnect clears tokens. Manual smoke still needed against a real Google account |
199
200
| Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |
200
201
| Narrow windows in a call | Done | Controls that do not fit move into "..." (View, Reactions, Raise hand, People, Chat; mic, camera, share, "..." and Leave always stay). Below 960 px, or when a side panel would leave the call under 720 px, the chat list hides; still too narrow, the panel overlays the call. Layout guard checks 640x480, 1280x800, 1920x1080 |
201
202
| Give and take control | Missing | Protocol known (main-channel data channel, action codes 0-11); needs a second person and a security review |
@@ -34,7 +34,7 @@ Feature parity with the Microsoft Teams desktop client.34
| Start from the local cache, no spinner | Done | |34
| Start from the local cache, no spinner | Done | |35
| Self-update | Done | |35
| Self-update | Done | |36
| Tray icon, close to tray | Done | |36
| Tray icon, close to tray | Done | |37
| Sign in on Linux without starting Chrome by hand | Partial | Works with a Chrome on a debug port |37
| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |38
| Single instance, second start brings the window to front | Done | |38
| Single instance, second start brings the window to front | Done | |39
39
40
## Chat list40
## Chat list@@ -181,7 +181,7 @@ Feature parity with the Microsoft Teams desktop client.181
| Recording | Done | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video, audio only, transcription only and every stop variant run live; a stop sent while the recorder still settles is retried. Consent needs a tenant with the policy on |181
| Recording | Done | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video, audio only, transcription only and every stop variant run live; a stop sent while the recorder still settles is retried. Consent needs a tenant with the policy on |182
| Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; occurrences, details and delete run live against real recordings. Transcription-only sessions (item media source `Transcript`) show the transcript without a recording card. "Audio only" comes from the chat event (`videoContent="CurtainOnly"`), with the video size check as fallback. Both signals read live on real recordings, fixtures unit tested; the transcript-only path was not run live |182
| Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; occurrences, details and delete run live against real recordings. Transcription-only sessions (item media source `Transcript`) show the transcript without a recording card. "Audio only" comes from the chat event (`videoContent="CurtainOnly"`), with the video size check as fallback. Both signals read live on real recordings, fixtures unit tested; the transcript-only path was not run live |183
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |183
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |184
| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto (device track with WebRTC echo cancellation, AGC, NS plus RNNoise ML suppression), Low (same without RNNoise) or Off, Music mode keeps echo cancellation only. No High level. Off and Music mode run a cpal mic through our own APM; checked with synthetic sources only, not with a real mic in a call |184
| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto and Low on Linux keep the Pulse ADM device track (same path as Web Teams); on Windows Auto runs the software chain with DeepFilterNet. Off and Music mode run a cpal mic through our own APM. No High level. Checked with synthetic sources; Linux Auto aligned with Pulse after the mic-quality fix |185
| Push to talk | Partial | Hold Ctrl+Space while muted to talk, release to mute; main window focused, not inside text fields; hint chip on the stage. Unit tested, not tried on the Windows build |185
| Push to talk | Partial | Hold Ctrl+Space while muted to talk, release to mute; main window focused, not inside text fields; hint chip on the stage. Unit tested, not tried on the Windows build |186
| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |186
| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |187
| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |187
| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |@@ -193,9 +193,10 @@ Feature parity with the Microsoft Teams desktop client.193
| Calls in chat history | Done | Card per call in the chat on the caller's side: "Call ended" with duration and end time, red "Missed call" with Call back, "Meeting started" / "Meeting ended", live start with Join. Started card hides once the call ended. From Graph call events, cached chats refetch once. Missed incoming call not seen live yet |193
| Calls in chat history | Done | Card per call in the chat on the caller's side: "Call ended" with duration and end time, red "Missed call" with Call back, "Meeting started" / "Meeting ended", live start with Join. Started card hides once the call ended. From Graph call events, cached chats refetch once. Missed incoming call not seen live yet |194
| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |194
| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |195
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |195
| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |196
| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Graph `POST /me/events` with `isOnlineMeeting` and `teamsForBusiness`, local wall time in the own mailbox time zone (series keep their time across DST, weekday from the local date). Body building unit tested; never run against a real calendar |196
| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Outlook-only home keeps Graph `POST /me/events` with `isOnlineMeeting`. With Google home or extra write targets: Teams join link first, then inserts per target (Outlook with join in location; Google `events.insert`). Settings > Calendar chooses home + dual-write. Body builders unit tested; live Google create needs `TEAMS_GOOGLE_CLIENT_ID` |197
| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Graph `accept`, `tentativelyAccept`, `decline`, falls back to the iCalUId lookup when the Teams id is not a Graph id. Not run against a real invitation |197
| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Outlook: Graph `accept` / `tentativelyAccept` / `decline` (+ iCalUId fallback). Google: Calendar API attendee `responseStatus` patch with `sendUpdates`. Source shown on calendar blocks |198
| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Snooze and X are saved to the Outlook reminder (Graph snoozeReminder / dismissReminder, occurrence id); reminders snoozed or dismissed in Outlook or on another device are read from reminderView every 60 s near a meeting and are not shown again. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar; push event 128 not wired (the realtime layer does not receive it) |198
| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Outlook: Snooze and X go to Graph snoozeReminder / dismissReminder; reminderView every 60 s near a meeting. Google: snooze/dismiss stay local only. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar (Outlook + optional Google merge); push event 128 not wired |199
| Google Calendar accounts | Partial | Settings > Calendar: Connect Google (OAuth Desktop + PKCE, env `TEAMS_GOOGLE_CLIENT_ID` / optional secret), list calendars, home calendar, extra write targets. Poll merges with Outlook by iCal UID / Teams join URL. Disconnect clears tokens. Manual smoke still needed against a real Google account |199
| Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |200
| Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |200
| Narrow windows in a call | Done | Controls that do not fit move into "..." (View, Reactions, Raise hand, People, Chat; mic, camera, share, "..." and Leave always stay). Below 960 px, or when a side panel would leave the call under 720 px, the chat list hides; still too narrow, the panel overlays the call. Layout guard checks 640x480, 1280x800, 1920x1080 |201
| Narrow windows in a call | Done | Controls that do not fit move into "..." (View, Reactions, Raise hand, People, Chat; mic, camera, share, "..." and Leave always stay). Below 960 px, or when a side panel would leave the call under 720 px, the chat list hides; still too narrow, the panel overlays the call. Layout guard checks 640x480, 1280x800, 1920x1080 |201
| Give and take control | Missing | Protocol known (main-channel data channel, action codes 0-11); needs a second person and a security review |202
| Give and take control | Missing | Protocol known (main-channel data channel, action codes 0-11); needs a second person and a security review |@@ -1,6 +1,8 @@
1
1
use chatsvc::{CalendarEvent, ResponseType};
2
2
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
3
3
4
use crate::week_grid::is_effective_all_day;
5
4
6
const JOIN_LEAD_MINUTES: i64 = 5;
5
7
const AGENDA_DAYS: i64 = 7;
6
8
const ALL_DAY_LABEL: &str = "All day";
@@ -73,17 +75,25 @@ fn detail_label(event: &CalendarEvent) -> String {
73
75
}
74
76
75
77
fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {
76
if event.all_day {
78
if is_effective_all_day(event, offset) {
77
79
return ALL_DAY_LABEL.to_owned();
78
80
}
79
81
format!(
80
82
"{} - {}",
81
event.start.with_timezone(&offset).format(app_base::format::clock_format()),
82
event.end.with_timezone(&offset).format(app_base::format::clock_format())
83
event
84
.start
85
.with_timezone(&offset)
86
.format(app_base::format::clock_format()),
87
event
88
.end
89
.with_timezone(&offset)
90
.format(app_base::format::clock_format())
83
91
)
84
92
}
85
93
86
94
fn agenda_day(event: &CalendarEvent, today: NaiveDate, offset: FixedOffset) -> NaiveDate {
95
// Flagged all-day (`date`) uses the UTC calendar date; midnight-span
96
// dateTime events use the local calendar day.
87
97
let start_day = if event.all_day {
88
98
event.start.date_naive()
89
99
} else {
@@ -104,7 +114,7 @@ fn agenda_row(event: &CalendarEvent, offset: FixedOffset) -> AgendaRow {
104
114
detail: detail_label(event),
105
115
response: event.response,
106
116
can_respond: event.response != ResponseType::Organizer && event.organizer_name.is_some(),
107
all_day: event.all_day,
117
all_day: is_effective_all_day(event, offset),
108
118
join_url: event.join_url.clone().filter(|_| event.online),
109
119
thread_id: event.thread_id.clone(),
110
120
start: event.start,
@@ -154,22 +164,30 @@ pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
154
164
minutes_from_now: i64,
155
165
length_minutes: i64,
156
166
organizer: &str,
157
response: ResponseType| CalendarEvent {
158
object_id: id.to_owned(),
159
subject: subject.to_owned(),
160
start: now + Duration::minutes(minutes_from_now),
161
end: now + Duration::minutes(minutes_from_now + length_minutes),
162
all_day: false,
163
cancelled: false,
164
online: true,
165
join_url: Some(demo_join_url(id)),
166
thread_id: None,
167
organizer_name: Some(organizer.to_owned()),
168
organizer_address: None,
169
ical_uid: None,
170
show_as: Default::default(),
171
dial_in: None,
172
response,
167
response: ResponseType| {
168
let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();
169
CalendarEvent {
170
object_id: id.to_owned(),
171
subject: subject.to_owned(),
172
start: now + Duration::minutes(minutes_from_now),
173
end: now + Duration::minutes(minutes_from_now + length_minutes),
174
all_day: false,
175
cancelled: false,
176
online: true,
177
join_url: Some(demo_join_url(id)),
178
thread_id: None,
179
organizer_name: Some(organizer.to_owned()),
180
organizer_address: None,
181
ical_uid: None,
182
show_as: Default::default(),
183
dial_in: None,
184
response,
185
source,
186
account_id,
187
calendar_id,
188
sources,
189
..Default::default()
190
}
173
191
};
174
192
vec![
175
193
event(
@@ -247,6 +265,7 @@ mod tests {
247
265
show_as: Default::default(),
248
266
dial_in: None,
249
267
response: ResponseType::Accepted,
268
..Default::default()
250
269
}
251
270
}
252
271
@@ -1,6 +1,8 @@1
use chatsvc::{CalendarEvent, ResponseType};1
use chatsvc::{CalendarEvent, ResponseType};2
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};2
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};3
3
4
use crate::week_grid::is_effective_all_day;5
4
const JOIN_LEAD_MINUTES: i64 = 5;6
const JOIN_LEAD_MINUTES: i64 = 5;5
const AGENDA_DAYS: i64 = 7;7
const AGENDA_DAYS: i64 = 7;6
const ALL_DAY_LABEL: &str = "All day";8
const ALL_DAY_LABEL: &str = "All day";@@ -73,17 +75,25 @@ fn detail_label(event: &CalendarEvent) -> String {73
}75
}74
76
75
fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {77
fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {76
if event.all_day {78
if is_effective_all_day(event, offset) {77
return ALL_DAY_LABEL.to_owned();79
return ALL_DAY_LABEL.to_owned();78
}80
}79
format!(81
format!(80
"{} - {}",82
"{} - {}",81
event.start.with_timezone(&offset).format(app_base::format::clock_format()),83
event82
event.end.with_timezone(&offset).format(app_base::format::clock_format())84
.start85
.with_timezone(&offset)86
.format(app_base::format::clock_format()),87
event88
.end89
.with_timezone(&offset)90
.format(app_base::format::clock_format())83
)91
)84
}92
}85
93
86
fn agenda_day(event: &CalendarEvent, today: NaiveDate, offset: FixedOffset) -> NaiveDate {94
fn agenda_day(event: &CalendarEvent, today: NaiveDate, offset: FixedOffset) -> NaiveDate {95
// Flagged all-day (`date`) uses the UTC calendar date; midnight-span96
// dateTime events use the local calendar day.87
let start_day = if event.all_day {97
let start_day = if event.all_day {88
event.start.date_naive()98
event.start.date_naive()89
} else {99
} else {@@ -104,7 +114,7 @@ fn agenda_row(event: &CalendarEvent, offset: FixedOffset) -> AgendaRow {104
detail: detail_label(event),114
detail: detail_label(event),105
response: event.response,115
response: event.response,106
can_respond: event.response != ResponseType::Organizer && event.organizer_name.is_some(),116
can_respond: event.response != ResponseType::Organizer && event.organizer_name.is_some(),107
all_day: event.all_day,117
all_day: is_effective_all_day(event, offset),108
join_url: event.join_url.clone().filter(|_| event.online),118
join_url: event.join_url.clone().filter(|_| event.online),109
thread_id: event.thread_id.clone(),119
thread_id: event.thread_id.clone(),110
start: event.start,120
start: event.start,@@ -154,22 +164,30 @@ pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {154
minutes_from_now: i64,164
minutes_from_now: i64,155
length_minutes: i64,165
length_minutes: i64,156
organizer: &str,166
organizer: &str,157
response: ResponseType| CalendarEvent {167
response: ResponseType| {158
object_id: id.to_owned(),168
let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();159
subject: subject.to_owned(),169
CalendarEvent {160
start: now + Duration::minutes(minutes_from_now),170
object_id: id.to_owned(),161
end: now + Duration::minutes(minutes_from_now + length_minutes),171
subject: subject.to_owned(),162
all_day: false,172
start: now + Duration::minutes(minutes_from_now),163
cancelled: false,173
end: now + Duration::minutes(minutes_from_now + length_minutes),164
online: true,174
all_day: false,165
join_url: Some(demo_join_url(id)),175
cancelled: false,166
thread_id: None,176
online: true,167
organizer_name: Some(organizer.to_owned()),177
join_url: Some(demo_join_url(id)),168
organizer_address: None,178
thread_id: None,169
ical_uid: None,179
organizer_name: Some(organizer.to_owned()),170
show_as: Default::default(),180
organizer_address: None,171
dial_in: None,181
ical_uid: None,172
response,182
show_as: Default::default(),183
dial_in: None,184
response,185
source,186
account_id,187
calendar_id,188
sources,189
..Default::default()190
}173
};191
};174
vec![192
vec![175
event(193
event(@@ -247,6 +265,7 @@ mod tests {247
show_as: Default::default(),265
show_as: Default::default(),248
dial_in: None,266
dial_in: None,249
response: ResponseType::Accepted,267
response: ResponseType::Accepted,268
..Default::default()250
}269
}251
}270
}252
271
@@ -7,7 +7,7 @@ use std::time::{Duration, Instant};
7
7
use calling::{
8
8
AttendeeLimits, CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
9
9
DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingCapability, MeetingRole,
10
MeetingTarget, Progress, Reaction, Replacement, RosterEntry, ShareKind, ShareSource, SpeakingDetector, StatsSample, VideoHub,
10
MeetingTarget, Progress, Reaction, Replacement, RosterEntry, ShareKind, SharePicker, ShareSource, SpeakingDetector, StatsSample, VideoHub,
11
11
VideoWant,
12
12
};
13
13
use teams_core::RecordingPolicy;
@@ -299,6 +299,8 @@ pub struct CallModel {
299
299
pub cameras: Vec<CameraDevice>,
300
300
pub camera: DeviceChoice,
301
301
pub local_share: Option<String>,
302
pub share_picker: SharePicker,
303
pub share_kind: Option<ShareKind>,
302
304
pub share_sources: Vec<ShareSource>,
303
305
pub share_thumbnails: Vec<(ShareSource, Arc<gpui_kit::RenderImage>)>,
304
306
pub last_sample: Option<StatsSample>,
@@ -369,6 +371,8 @@ impl CallModel {
369
371
cameras: Vec::new(),
370
372
camera: DeviceChoice::SystemDefault,
371
373
local_share: None,
374
share_picker: SharePicker::List,
375
share_kind: None,
372
376
share_sources: Vec::new(),
373
377
share_thumbnails: Vec::new(),
374
378
last_sample: None,
@@ -508,6 +512,8 @@ impl CallModel {
508
512
}
509
513
self.local_share = label;
510
514
}
515
CallUpdate::SharePicker(picker) => self.share_picker = picker,
516
CallUpdate::ShareKind(kind) => self.share_kind = kind,
511
517
CallUpdate::ShareSources(sources) => {
512
518
self.share_thumbnails.retain(|(source, _)| sources.contains(source));
513
519
self.share_sources = sources;
@@ -1191,7 +1197,11 @@ impl CallModel {
1191
1197
}
1192
1198
1193
1199
pub fn can_share(&self) -> bool {
1194
!self.share_sources.is_empty() && self.is_live()
1200
self.is_live() && (self.uses_portal_picker() || !self.share_sources.is_empty())
1201
}
1202
1203
pub fn uses_portal_picker(&self) -> bool {
1204
self.share_picker == SharePicker::Portal
1195
1205
}
1196
1206
1197
1207
pub fn is_live(&self) -> bool {
@@ -1948,6 +1958,16 @@ mod tests {
1948
1958
assert!(!model.share_sound);
1949
1959
}
1950
1960
1961
#[test]
1962
fn portal_share_works_without_a_source_list() {
1963
let mut model = connected_model();
1964
assert!(model.share_sources.is_empty());
1965
assert!(!model.can_share());
1966
model.apply(CallUpdate::SharePicker(SharePicker::Portal));
1967
assert!(model.uses_portal_picker());
1968
assert!(model.can_share());
1969
}
1970
1951
1971
#[test]
1952
1972
fn lobby_guests_are_listed_for_organizers_who_may_admit() {
1953
1973
let mut model = meeting_with_me();
@@ -7,7 +7,7 @@ use std::time::{Duration, Instant};7
use calling::{7
use calling::{8
AttendeeLimits, CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,8
AttendeeLimits, CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,9
DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingCapability, MeetingRole,9
DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingCapability, MeetingRole,10
MeetingTarget, Progress, Reaction, Replacement, RosterEntry, ShareKind, ShareSource, SpeakingDetector, StatsSample, VideoHub,10
MeetingTarget, Progress, Reaction, Replacement, RosterEntry, ShareKind, SharePicker, ShareSource, SpeakingDetector, StatsSample, VideoHub,11
VideoWant,11
VideoWant,12
};12
};13
use teams_core::RecordingPolicy;13
use teams_core::RecordingPolicy;@@ -299,6 +299,8 @@ pub struct CallModel {299
pub cameras: Vec<CameraDevice>,299
pub cameras: Vec<CameraDevice>,300
pub camera: DeviceChoice,300
pub camera: DeviceChoice,301
pub local_share: Option<String>,301
pub local_share: Option<String>,302
pub share_picker: SharePicker,303
pub share_kind: Option<ShareKind>,302
pub share_sources: Vec<ShareSource>,304
pub share_sources: Vec<ShareSource>,303
pub share_thumbnails: Vec<(ShareSource, Arc<gpui_kit::RenderImage>)>,305
pub share_thumbnails: Vec<(ShareSource, Arc<gpui_kit::RenderImage>)>,304
pub last_sample: Option<StatsSample>,306
pub last_sample: Option<StatsSample>,@@ -369,6 +371,8 @@ impl CallModel {369
cameras: Vec::new(),371
cameras: Vec::new(),370
camera: DeviceChoice::SystemDefault,372
camera: DeviceChoice::SystemDefault,371
local_share: None,373
local_share: None,374
share_picker: SharePicker::List,375
share_kind: None,372
share_sources: Vec::new(),376
share_sources: Vec::new(),373
share_thumbnails: Vec::new(),377
share_thumbnails: Vec::new(),374
last_sample: None,378
last_sample: None,@@ -508,6 +512,8 @@ impl CallModel {508
}512
}509
self.local_share = label;513
self.local_share = label;510
}514
}515
CallUpdate::SharePicker(picker) => self.share_picker = picker,516
CallUpdate::ShareKind(kind) => self.share_kind = kind,511
CallUpdate::ShareSources(sources) => {517
CallUpdate::ShareSources(sources) => {512
self.share_thumbnails.retain(|(source, _)| sources.contains(source));518
self.share_thumbnails.retain(|(source, _)| sources.contains(source));513
self.share_sources = sources;519
self.share_sources = sources;@@ -1191,7 +1197,11 @@ impl CallModel {1191
}1197
}1192
1198
1193
pub fn can_share(&self) -> bool {1199
pub fn can_share(&self) -> bool {1194
!self.share_sources.is_empty() && self.is_live()1200
self.is_live() && (self.uses_portal_picker() || !self.share_sources.is_empty())1201
}1202
1203
pub fn uses_portal_picker(&self) -> bool {1204
self.share_picker == SharePicker::Portal1195
}1205
}1196
1206
1197
pub fn is_live(&self) -> bool {1207
pub fn is_live(&self) -> bool {@@ -1948,6 +1958,16 @@ mod tests {1948
assert!(!model.share_sound);1958
assert!(!model.share_sound);1949
}1959
}1950
1960
1961
#[test]1962
fn portal_share_works_without_a_source_list() {1963
let mut model = connected_model();1964
assert!(model.share_sources.is_empty());1965
assert!(!model.can_share());1966
model.apply(CallUpdate::SharePicker(SharePicker::Portal));1967
assert!(model.uses_portal_picker());1968
assert!(model.can_share());1969
}1970
1951
#[test]1971
#[test]1952
fn lobby_guests_are_listed_for_organizers_who_may_admit() {1972
fn lobby_guests_are_listed_for_organizers_who_may_admit() {1953
let mut model = meeting_with_me();1973
let mut model = meeting_with_me();@@ -1,5 +1,7 @@
1
1
use chatsvc::{CalendarEvent, ResponseType, ShowAs};
2
use chrono::{DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, Utc, Weekday};
2
use chrono::{
3
DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,
4
};
3
5
4
6
pub const WORK_WEEK_DAYS: i64 = 5;
5
7
pub const MINUTES_PER_DAY: i64 = 24 * 60;
@@ -72,7 +74,9 @@ impl CalendarSpan {
72
74
pub fn shifted(self, start: NaiveDate, steps: i32) -> NaiveDate {
73
75
match self {
74
76
CalendarSpan::Day => start + Duration::days(i64::from(steps)),
75
CalendarSpan::WorkWeek | CalendarSpan::Week => start + Duration::weeks(i64::from(steps)),
77
CalendarSpan::WorkWeek | CalendarSpan::Week => {
78
start + Duration::weeks(i64::from(steps))
79
}
76
80
CalendarSpan::Month => {
77
81
let month = month_shown(start);
78
82
let moved = if steps >= 0 {
@@ -136,6 +140,25 @@ pub fn shown_in_calendar(event: &CalendarEvent) -> bool {
136
140
event.response != ResponseType::Declined
137
141
}
138
142
143
/// True all-day events, plus timed blocks that cover whole local days
144
/// (Google holidays/week markers as 00:00→00:00, or multi-day 00:00→23:59).
145
pub fn is_effective_all_day(event: &CalendarEvent, offset: FixedOffset) -> bool {
146
if event.all_day {
147
return true;
148
}
149
let start = event.start.with_timezone(&offset);
150
let end = event.end.with_timezone(&offset);
151
if start.time() != NaiveTime::MIN || end <= start {
152
return false;
153
}
154
if end.time() == NaiveTime::MIN {
155
return true;
156
}
157
// Multi-day blocks that run from midnight through end-of-day (e.g. 23:59).
158
end.date_naive() > start.date_naive()
159
&& end.time() >= NaiveTime::from_hms_opt(23, 59, 0).unwrap()
160
}
161
139
162
pub fn week_days(
140
163
events: &[CalendarEvent],
141
164
start: NaiveDate,
@@ -152,7 +175,7 @@ pub fn week_days(
152
175
if !shown_in_calendar(event) || event.end <= day_start || event.start >= day_end {
153
176
continue;
154
177
}
155
if event.all_day {
178
if is_effective_all_day(event, offset) {
156
179
all_day.push(index);
157
180
continue;
158
181
}
@@ -267,6 +290,7 @@ mod tests {
267
290
show_as: Default::default(),
268
291
dial_in: None,
269
292
response: ResponseType::Accepted,
293
..Default::default()
270
294
}
271
295
}
272
296
@@ -285,7 +309,10 @@ mod tests {
285
309
assert_eq!(CalendarSpan::Month.title(next), "December 2026");
286
310
let back = CalendarSpan::Month.shifted(start, -11);
287
311
assert_eq!(CalendarSpan::Month.title(back), "December 2025");
288
assert_eq!(CalendarSpan::Week.shifted(date(2), -1), date(2) - Duration::weeks(1));
312
assert_eq!(
313
CalendarSpan::Week.shifted(date(2), -1),
314
date(2) - Duration::weeks(1)
315
);
289
316
}
290
317
291
318
#[test]
@@ -346,6 +373,32 @@ mod tests {
346
373
);
347
374
}
348
375
376
#[test]
377
fn midnight_to_midnight_timed_events_sit_in_the_all_day_row() {
378
// Google holidays / week markers often arrive as dateTime 00:00→00:00.
379
let holiday = event(0, 0, 24 * 60);
380
let meeting = event(9, 30, 60);
381
let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
382
assert!(is_effective_all_day(&holiday, utc()));
383
assert!(!is_effective_all_day(&meeting, utc()));
384
let days = week_days(&[holiday, meeting], monday, 1, utc());
385
assert_eq!(days[0].all_day, [0]);
386
assert_eq!(days[0].blocks.len(), 1);
387
assert_eq!(days[0].blocks[0].event_index, 1);
388
}
389
390
#[test]
391
fn multi_day_midnight_to_end_of_day_is_all_day() {
392
// e.g. KubeCon as 00:00 Mon → 23:59 Thu.
393
let conference = event(0, 0, 4 * 24 * 60 - 1);
394
assert!(is_effective_all_day(&conference, utc()));
395
let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
396
let days = week_days(&[conference], monday, 5, utc());
397
assert!(days.iter().all(|day| day.blocks.is_empty()));
398
assert_eq!(days[0].all_day, [0]);
399
assert_eq!(days[3].all_day, [0]);
400
}
401
349
402
#[test]
350
403
fn spans_start_and_step_like_teams() {
351
404
let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();
@@ -355,7 +408,10 @@ mod tests {
355
408
assert_eq!(CalendarSpan::Week.start_for(wednesday), monday);
356
409
let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
357
410
assert_eq!(CalendarSpan::Week.start_for(sunday), monday);
358
assert_eq!(CalendarSpan::Day.shifted(wednesday, 1), wednesday + Duration::days(1));
411
assert_eq!(
412
CalendarSpan::Day.shifted(wednesday, 1),
413
wednesday + Duration::days(1)
414
);
359
415
assert_eq!(CalendarSpan::Week.days(), 7);
360
416
}
361
417
@@ -1,5 +1,7 @@1
use chatsvc::{CalendarEvent, ResponseType, ShowAs};1
use chatsvc::{CalendarEvent, ResponseType, ShowAs};2
use chrono::{DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, Utc, Weekday};2
use chrono::{3
DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,4
};3
5
4
pub const WORK_WEEK_DAYS: i64 = 5;6
pub const WORK_WEEK_DAYS: i64 = 5;5
pub const MINUTES_PER_DAY: i64 = 24 * 60;7
pub const MINUTES_PER_DAY: i64 = 24 * 60;@@ -72,7 +74,9 @@ impl CalendarSpan {72
pub fn shifted(self, start: NaiveDate, steps: i32) -> NaiveDate {74
pub fn shifted(self, start: NaiveDate, steps: i32) -> NaiveDate {73
match self {75
match self {74
CalendarSpan::Day => start + Duration::days(i64::from(steps)),76
CalendarSpan::Day => start + Duration::days(i64::from(steps)),75
CalendarSpan::WorkWeek | CalendarSpan::Week => start + Duration::weeks(i64::from(steps)),77
CalendarSpan::WorkWeek | CalendarSpan::Week => {78
start + Duration::weeks(i64::from(steps))79
}76
CalendarSpan::Month => {80
CalendarSpan::Month => {77
let month = month_shown(start);81
let month = month_shown(start);78
let moved = if steps >= 0 {82
let moved = if steps >= 0 {@@ -136,6 +140,25 @@ pub fn shown_in_calendar(event: &CalendarEvent) -> bool {136
event.response != ResponseType::Declined140
event.response != ResponseType::Declined137
}141
}138
142
143
/// True all-day events, plus timed blocks that cover whole local days144
/// (Google holidays/week markers as 00:00→00:00, or multi-day 00:00→23:59).145
pub fn is_effective_all_day(event: &CalendarEvent, offset: FixedOffset) -> bool {146
if event.all_day {147
return true;148
}149
let start = event.start.with_timezone(&offset);150
let end = event.end.with_timezone(&offset);151
if start.time() != NaiveTime::MIN || end <= start {152
return false;153
}154
if end.time() == NaiveTime::MIN {155
return true;156
}157
// Multi-day blocks that run from midnight through end-of-day (e.g. 23:59).158
end.date_naive() > start.date_naive()159
&& end.time() >= NaiveTime::from_hms_opt(23, 59, 0).unwrap()160
}161
139
pub fn week_days(162
pub fn week_days(140
events: &[CalendarEvent],163
events: &[CalendarEvent],141
start: NaiveDate,164
start: NaiveDate,@@ -152,7 +175,7 @@ pub fn week_days(152
if !shown_in_calendar(event) || event.end <= day_start || event.start >= day_end {175
if !shown_in_calendar(event) || event.end <= day_start || event.start >= day_end {153
continue;176
continue;154
}177
}155
if event.all_day {178
if is_effective_all_day(event, offset) {156
all_day.push(index);179
all_day.push(index);157
continue;180
continue;158
}181
}@@ -267,6 +290,7 @@ mod tests {267
show_as: Default::default(),290
show_as: Default::default(),268
dial_in: None,291
dial_in: None,269
response: ResponseType::Accepted,292
response: ResponseType::Accepted,293
..Default::default()270
}294
}271
}295
}272
296
@@ -285,7 +309,10 @@ mod tests {285
assert_eq!(CalendarSpan::Month.title(next), "December 2026");309
assert_eq!(CalendarSpan::Month.title(next), "December 2026");286
let back = CalendarSpan::Month.shifted(start, -11);310
let back = CalendarSpan::Month.shifted(start, -11);287
assert_eq!(CalendarSpan::Month.title(back), "December 2025");311
assert_eq!(CalendarSpan::Month.title(back), "December 2025");288
assert_eq!(CalendarSpan::Week.shifted(date(2), -1), date(2) - Duration::weeks(1));312
assert_eq!(313
CalendarSpan::Week.shifted(date(2), -1),314
date(2) - Duration::weeks(1)315
);289
}316
}290
317
291
#[test]318
#[test]@@ -346,6 +373,32 @@ mod tests {346
);373
);347
}374
}348
375
376
#[test]377
fn midnight_to_midnight_timed_events_sit_in_the_all_day_row() {378
// Google holidays / week markers often arrive as dateTime 00:00→00:00.379
let holiday = event(0, 0, 24 * 60);380
let meeting = event(9, 30, 60);381
let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();382
assert!(is_effective_all_day(&holiday, utc()));383
assert!(!is_effective_all_day(&meeting, utc()));384
let days = week_days(&[holiday, meeting], monday, 1, utc());385
assert_eq!(days[0].all_day, [0]);386
assert_eq!(days[0].blocks.len(), 1);387
assert_eq!(days[0].blocks[0].event_index, 1);388
}389
390
#[test]391
fn multi_day_midnight_to_end_of_day_is_all_day() {392
// e.g. KubeCon as 00:00 Mon → 23:59 Thu.393
let conference = event(0, 0, 4 * 24 * 60 - 1);394
assert!(is_effective_all_day(&conference, utc()));395
let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();396
let days = week_days(&[conference], monday, 5, utc());397
assert!(days.iter().all(|day| day.blocks.is_empty()));398
assert_eq!(days[0].all_day, [0]);399
assert_eq!(days[3].all_day, [0]);400
}401
349
#[test]402
#[test]350
fn spans_start_and_step_like_teams() {403
fn spans_start_and_step_like_teams() {351
let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();404
let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();@@ -355,7 +408,10 @@ mod tests {355
assert_eq!(CalendarSpan::Week.start_for(wednesday), monday);408
assert_eq!(CalendarSpan::Week.start_for(wednesday), monday);356
let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();409
let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();357
assert_eq!(CalendarSpan::Week.start_for(sunday), monday);410
assert_eq!(CalendarSpan::Week.start_for(sunday), monday);358
assert_eq!(CalendarSpan::Day.shifted(wednesday, 1), wednesday + Duration::days(1));411
assert_eq!(412
CalendarSpan::Day.shifted(wednesday, 1),413
wednesday + Duration::days(1)414
);359
assert_eq!(CalendarSpan::Week.days(), 7);415
assert_eq!(CalendarSpan::Week.days(), 7);360
}416
}361
417
@@ -204,7 +204,11 @@ async fn supervise(
204
204
link,
205
205
live_retry,
206
206
));
207
tokio::spawn(calendar_loop(session.clone(), events.clone()));
207
tokio::spawn(calendar_loop(
208
session.clone(),
209
store.clone(),
210
events.clone(),
211
));
208
212
tokio::spawn(pins_loop(session, events.clone()));
209
213
tokio::spawn(presence_resubscribe_loop(engine.clone()));
210
214
refresh_loop(engine, events, nudges).await;
@@ -305,9 +309,12 @@ async fn realtime_loop(
305
309
let receipt_engine = engine.clone();
306
310
let receipt_event = message.clone();
307
311
engine.handle_pin_event(&message);
308
if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID) {
312
if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID)
313
{
309
314
let activity_engine = engine.clone();
310
tokio::spawn(async move { activity_engine.refresh_activity().await });
315
tokio::spawn(
316
async move { activity_engine.refresh_activity().await },
317
);
311
318
}
312
319
tokio::spawn(async move {
313
320
receipt_engine.handle_receipt_event(&receipt_event).await
@@ -454,7 +461,7 @@ async fn handle_message_event(
454
461
}
455
462
}
456
463
457
async fn calendar_loop(session: Session, events: EventSender) {
464
async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender) {
458
465
let calendar = Calendar::new(&session);
459
466
let (nudge, mut nudges) = mpsc::unbounded_channel();
460
467
let _ = events.send(BackendEvent::CalendarNudge(nudge));
@@ -480,16 +487,33 @@ async fn calendar_loop(session: Session, events: EventSender) {
480
487
deferred_fetch = None;
481
488
last_fetch = Some(tokio::time::Instant::now());
482
489
let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
483
match calendar.calendar_view(start, end).await {
484
Ok(fetched) => {
485
if events.send(BackendEvent::Calendar(fetched)).is_err() {
486
return;
490
let mut accounts = store::load_calendar_accounts(&store);
491
let mut combined = Vec::new();
492
let mut outlook_failed = false;
493
if accounts.outlook_selected {
494
match calendar.calendar_view(start, end).await {
495
Ok(fetched) => combined.extend(fetched),
496
Err(error) => {
497
outlook_failed = true;
498
crate::diagnostics::record(format!(
499
"calls: outlook calendar not loaded: {}",
500
shorten(&error.to_string())
501
));
487
502
}
488
503
}
489
Err(error) => crate::diagnostics::record(format!(
490
"calls: calendar not loaded: {}",
491
shorten(&error.to_string())
492
)),
504
}
505
if let Ok(google_events) =
506
crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await
507
{
508
let _ = store::save_calendar_accounts(&store, &accounts);
509
combined.extend(google_events);
510
}
511
if combined.is_empty() && outlook_failed && !accounts.has_google() {
512
continue;
513
}
514
let merged = chatsvc::merge_calendar_events(combined);
515
if events.send(BackendEvent::Calendar(merged)).is_err() {
516
return;
493
517
}
494
518
}
495
519
}
@@ -204,7 +204,11 @@ async fn supervise(204
link,204
link,205
live_retry,205
live_retry,206
));206
));207
tokio::spawn(calendar_loop(session.clone(), events.clone()));207
tokio::spawn(calendar_loop(208
session.clone(),209
store.clone(),210
events.clone(),211
));208
tokio::spawn(pins_loop(session, events.clone()));212
tokio::spawn(pins_loop(session, events.clone()));209
tokio::spawn(presence_resubscribe_loop(engine.clone()));213
tokio::spawn(presence_resubscribe_loop(engine.clone()));210
refresh_loop(engine, events, nudges).await;214
refresh_loop(engine, events, nudges).await;@@ -305,9 +309,12 @@ async fn realtime_loop(305
let receipt_engine = engine.clone();309
let receipt_engine = engine.clone();306
let receipt_event = message.clone();310
let receipt_event = message.clone();307
engine.handle_pin_event(&message);311
engine.handle_pin_event(&message);308
if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID) {312
if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID)313
{309
let activity_engine = engine.clone();314
let activity_engine = engine.clone();310
tokio::spawn(async move { activity_engine.refresh_activity().await });315
tokio::spawn(316
async move { activity_engine.refresh_activity().await },317
);311
}318
}312
tokio::spawn(async move {319
tokio::spawn(async move {313
receipt_engine.handle_receipt_event(&receipt_event).await320
receipt_engine.handle_receipt_event(&receipt_event).await@@ -454,7 +461,7 @@ async fn handle_message_event(454
}461
}455
}462
}456
463
457
async fn calendar_loop(session: Session, events: EventSender) {464
async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender) {458
let calendar = Calendar::new(&session);465
let calendar = Calendar::new(&session);459
let (nudge, mut nudges) = mpsc::unbounded_channel();466
let (nudge, mut nudges) = mpsc::unbounded_channel();460
let _ = events.send(BackendEvent::CalendarNudge(nudge));467
let _ = events.send(BackendEvent::CalendarNudge(nudge));@@ -480,16 +487,33 @@ async fn calendar_loop(session: Session, events: EventSender) {480
deferred_fetch = None;487
deferred_fetch = None;481
last_fetch = Some(tokio::time::Instant::now());488
last_fetch = Some(tokio::time::Instant::now());482
let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());489
let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());483
match calendar.calendar_view(start, end).await {490
let mut accounts = store::load_calendar_accounts(&store);484
Ok(fetched) => {491
let mut combined = Vec::new();485
if events.send(BackendEvent::Calendar(fetched)).is_err() {492
let mut outlook_failed = false;486
return;493
if accounts.outlook_selected {494
match calendar.calendar_view(start, end).await {495
Ok(fetched) => combined.extend(fetched),496
Err(error) => {497
outlook_failed = true;498
crate::diagnostics::record(format!(499
"calls: outlook calendar not loaded: {}",500
shorten(&error.to_string())501
));487
}502
}488
}503
}489
Err(error) => crate::diagnostics::record(format!(504
}490
"calls: calendar not loaded: {}",505
if let Ok(google_events) =491
shorten(&error.to_string())506
crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await492
)),507
{508
let _ = store::save_calendar_accounts(&store, &accounts);509
combined.extend(google_events);510
}511
if combined.is_empty() && outlook_failed && !accounts.has_google() {512
continue;513
}514
let merged = chatsvc::merge_calendar_events(combined);515
if events.send(BackendEvent::Calendar(merged)).is_err() {516
return;493
}517
}494
}518
}495
}519
}@@ -0,0 +1,207 @@
1
use chrono::Utc;
2
use gpui_kit::Context;
3
use store::{
4
CalendarAccounts, CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet,
5
load_calendar_accounts, save_calendar_accounts,
6
};
7
use uuid::Uuid;
8
9
use chatsvc::{
10
GoogleCalendar, GoogleOAuth, allocate_redirect_uri, client_id_from_env, exchange_code,
11
parse_calendar_list, wait_for_code,
12
};
13
14
use crate::app_state::AppState;
15
use crate::runtime;
16
17
impl AppState {
18
pub fn calendar_accounts(&self) -> CalendarAccounts {
19
load_calendar_accounts(&self.store)
20
}
21
22
pub fn disconnect_google_account(&mut self, account_id: &str, cx: &mut Context<Self>) {
23
let mut accounts = load_calendar_accounts(&self.store);
24
accounts.disconnect_google(account_id);
25
let _ = save_calendar_accounts(&self.store, &accounts);
26
self.refresh_calendar(cx);
27
self.load_calendar_week(cx);
28
cx.notify();
29
}
30
31
pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {
32
let mut accounts = load_calendar_accounts(&self.store);
33
accounts.home = home;
34
let _ = save_calendar_accounts(&self.store, &accounts);
35
cx.notify();
36
}
37
38
pub fn toggle_write_target(&mut self, target: CalendarRef, cx: &mut Context<Self>) {
39
let mut accounts = load_calendar_accounts(&self.store);
40
if let Some(index) = accounts
41
.write_targets
42
.iter()
43
.position(|existing| existing.key() == target.key())
44
{
45
accounts.write_targets.remove(index);
46
} else if accounts.home.key() != target.key() {
47
accounts.write_targets.push(target);
48
}
49
let _ = save_calendar_accounts(&self.store, &accounts);
50
cx.notify();
51
}
52
53
pub fn toggle_google_calendar_selected(
54
&mut self,
55
account_id: &str,
56
calendar_id: &str,
57
cx: &mut Context<Self>,
58
) {
59
let mut accounts = load_calendar_accounts(&self.store);
60
if let Some(calendar) = accounts.google_account_mut(account_id).and_then(|account| {
61
account
62
.calendars
63
.iter_mut()
64
.find(|calendar| calendar.id == calendar_id)
65
}) {
66
calendar.selected = !calendar.selected;
67
}
68
let _ = save_calendar_accounts(&self.store, &accounts);
69
self.refresh_calendar(cx);
70
self.load_calendar_week(cx);
71
cx.notify();
72
}
73
74
pub fn toggle_outlook_calendar_selected(&mut self, cx: &mut Context<Self>) {
75
let mut accounts = load_calendar_accounts(&self.store);
76
accounts.outlook_selected = !accounts.outlook_selected;
77
let _ = save_calendar_accounts(&self.store, &accounts);
78
self.refresh_calendar(cx);
79
self.load_calendar_week(cx);
80
cx.notify();
81
}
82
83
pub fn connect_google_calendar(&mut self, cx: &mut Context<Self>) {
84
let Some(oauth) = client_id_from_env() else {
85
self.raise_notice(
86
"Set TEAMS_GOOGLE_CLIENT_ID (and optional TEAMS_GOOGLE_CLIENT_SECRET) to connect Google Calendar."
87
.to_owned(),
88
None,
89
cx,
90
);
91
return;
92
};
93
let store = self.store.clone();
94
cx.spawn(async move |this, cx| {
95
let prepared = runtime::spawn({
96
let oauth = oauth.clone();
97
async move {
98
let (redirect_uri, listener) = allocate_redirect_uri()
99
.await
100
.map_err(|error| error.to_string())?;
101
let pending = oauth.begin(&redirect_uri);
102
let authorize_url = pending.authorize_url.clone();
103
Ok::<_, String>((authorize_url, pending, listener, oauth))
104
}
105
});
106
let (authorize_url, pending, listener, oauth) = match prepared.await {
107
Ok(Ok(value)) => value,
108
Ok(Err(error)) => {
109
this.update(cx, |state, cx| state.raise_notice(error, None, cx))
110
.ok();
111
return;
112
}
113
Err(_) => {
114
this.update(cx, |state, cx| {
115
state.raise_notice("Could not start Google sign-in.".to_owned(), None, cx)
116
})
117
.ok();
118
return;
119
}
120
};
121
this.update(cx, |_, cx| cx.open_url(&authorize_url)).ok();
122
let finished = runtime::spawn(async move {
123
finish_google_connect(oauth, pending, listener, store).await
124
});
125
match finished.await {
126
Ok(Ok(email)) => {
127
this.update(cx, |state, cx| {
128
state.raise_notice(
129
format!("Google Calendar connected ({email})."),
130
None,
131
cx,
132
);
133
state.refresh_calendar(cx);
134
cx.notify();
135
})
136
.ok();
137
}
138
Ok(Err(error)) => {
139
this.update(cx, |state, cx| state.raise_notice(error, None, cx))
140
.ok();
141
}
142
Err(_) => {
143
this.update(cx, |state, cx| {
144
state.raise_notice("Google sign-in was cancelled.".to_owned(), None, cx)
145
})
146
.ok();
147
}
148
}
149
})
150
.detach();
151
}
152
}
153
154
async fn finish_google_connect(
155
oauth: GoogleOAuth,
156
pending: chatsvc::AuthPending,
157
listener: tokio::net::TcpListener,
158
store: std::sync::Arc<store::Store>,
159
) -> Result<String, String> {
160
let code = wait_for_code(&pending, listener)
161
.await
162
.map_err(|error| error.to_string())?;
163
let bundle = exchange_code(&oauth, &pending, &code)
164
.await
165
.map_err(|error| error.to_string())?;
166
let client = GoogleCalendar::new(bundle.access_token.clone());
167
let list = client
168
.list_calendars()
169
.await
170
.map_err(|error| error.to_string())?;
171
let mut calendars = parse_calendar_list(&list)
172
.into_iter()
173
.map(|(id, summary, primary)| GoogleCalendarInfo {
174
id,
175
summary,
176
selected: true,
177
primary,
178
})
179
.collect::<Vec<_>>();
180
if calendars.is_empty() {
181
calendars.push(GoogleCalendarInfo {
182
id: "primary".into(),
183
summary: "Primary".into(),
184
selected: true,
185
primary: true,
186
});
187
}
188
let email = calendars
189
.iter()
190
.find(|calendar| calendar.primary)
191
.map(|calendar| calendar.summary.clone())
192
.unwrap_or_else(|| "Google".into());
193
let account = GoogleAccount {
194
id: Uuid::new_v4().to_string(),
195
email: email.clone(),
196
calendars,
197
tokens: GoogleTokenSet {
198
access_token: bundle.access_token,
199
refresh_token: bundle.refresh_token,
200
expires_at: Utc::now().timestamp() + bundle.expires_in.max(60),
201
},
202
};
203
let mut accounts = load_calendar_accounts(&store);
204
accounts.google_accounts.push(account);
205
save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
206
Ok(email)
207
}
@@ -0,0 +1,207 @@1
use chrono::Utc;2
use gpui_kit::Context;3
use store::{4
CalendarAccounts, CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet,5
load_calendar_accounts, save_calendar_accounts,6
};7
use uuid::Uuid;8
9
use chatsvc::{10
GoogleCalendar, GoogleOAuth, allocate_redirect_uri, client_id_from_env, exchange_code,11
parse_calendar_list, wait_for_code,12
};13
14
use crate::app_state::AppState;15
use crate::runtime;16
17
impl AppState {18
pub fn calendar_accounts(&self) -> CalendarAccounts {19
load_calendar_accounts(&self.store)20
}21
22
pub fn disconnect_google_account(&mut self, account_id: &str, cx: &mut Context<Self>) {23
let mut accounts = load_calendar_accounts(&self.store);24
accounts.disconnect_google(account_id);25
let _ = save_calendar_accounts(&self.store, &accounts);26
self.refresh_calendar(cx);27
self.load_calendar_week(cx);28
cx.notify();29
}30
31
pub fn set_home_calendar(&mut self, home: CalendarRef, cx: &mut Context<Self>) {32
let mut accounts = load_calendar_accounts(&self.store);33
accounts.home = home;34
let _ = save_calendar_accounts(&self.store, &accounts);35
cx.notify();36
}37
38
pub fn toggle_write_target(&mut self, target: CalendarRef, cx: &mut Context<Self>) {39
let mut accounts = load_calendar_accounts(&self.store);40
if let Some(index) = accounts41
.write_targets42
.iter()43
.position(|existing| existing.key() == target.key())44
{45
accounts.write_targets.remove(index);46
} else if accounts.home.key() != target.key() {47
accounts.write_targets.push(target);48
}49
let _ = save_calendar_accounts(&self.store, &accounts);50
cx.notify();51
}52
53
pub fn toggle_google_calendar_selected(54
&mut self,55
account_id: &str,56
calendar_id: &str,57
cx: &mut Context<Self>,58
) {59
let mut accounts = load_calendar_accounts(&self.store);60
if let Some(calendar) = accounts.google_account_mut(account_id).and_then(|account| {61
account62
.calendars63
.iter_mut()64
.find(|calendar| calendar.id == calendar_id)65
}) {66
calendar.selected = !calendar.selected;67
}68
let _ = save_calendar_accounts(&self.store, &accounts);69
self.refresh_calendar(cx);70
self.load_calendar_week(cx);71
cx.notify();72
}73
74
pub fn toggle_outlook_calendar_selected(&mut self, cx: &mut Context<Self>) {75
let mut accounts = load_calendar_accounts(&self.store);76
accounts.outlook_selected = !accounts.outlook_selected;77
let _ = save_calendar_accounts(&self.store, &accounts);78
self.refresh_calendar(cx);79
self.load_calendar_week(cx);80
cx.notify();81
}82
83
pub fn connect_google_calendar(&mut self, cx: &mut Context<Self>) {84
let Some(oauth) = client_id_from_env() else {85
self.raise_notice(86
"Set TEAMS_GOOGLE_CLIENT_ID (and optional TEAMS_GOOGLE_CLIENT_SECRET) to connect Google Calendar."87
.to_owned(),88
None,89
cx,90
);91
return;92
};93
let store = self.store.clone();94
cx.spawn(async move |this, cx| {95
let prepared = runtime::spawn({96
let oauth = oauth.clone();97
async move {98
let (redirect_uri, listener) = allocate_redirect_uri()99
.await100
.map_err(|error| error.to_string())?;101
let pending = oauth.begin(&redirect_uri);102
let authorize_url = pending.authorize_url.clone();103
Ok::<_, String>((authorize_url, pending, listener, oauth))104
}105
});106
let (authorize_url, pending, listener, oauth) = match prepared.await {107
Ok(Ok(value)) => value,108
Ok(Err(error)) => {109
this.update(cx, |state, cx| state.raise_notice(error, None, cx))110
.ok();111
return;112
}113
Err(_) => {114
this.update(cx, |state, cx| {115
state.raise_notice("Could not start Google sign-in.".to_owned(), None, cx)116
})117
.ok();118
return;119
}120
};121
this.update(cx, |_, cx| cx.open_url(&authorize_url)).ok();122
let finished = runtime::spawn(async move {123
finish_google_connect(oauth, pending, listener, store).await124
});125
match finished.await {126
Ok(Ok(email)) => {127
this.update(cx, |state, cx| {128
state.raise_notice(129
format!("Google Calendar connected ({email})."),130
None,131
cx,132
);133
state.refresh_calendar(cx);134
cx.notify();135
})136
.ok();137
}138
Ok(Err(error)) => {139
this.update(cx, |state, cx| state.raise_notice(error, None, cx))140
.ok();141
}142
Err(_) => {143
this.update(cx, |state, cx| {144
state.raise_notice("Google sign-in was cancelled.".to_owned(), None, cx)145
})146
.ok();147
}148
}149
})150
.detach();151
}152
}153
154
async fn finish_google_connect(155
oauth: GoogleOAuth,156
pending: chatsvc::AuthPending,157
listener: tokio::net::TcpListener,158
store: std::sync::Arc<store::Store>,159
) -> Result<String, String> {160
let code = wait_for_code(&pending, listener)161
.await162
.map_err(|error| error.to_string())?;163
let bundle = exchange_code(&oauth, &pending, &code)164
.await165
.map_err(|error| error.to_string())?;166
let client = GoogleCalendar::new(bundle.access_token.clone());167
let list = client168
.list_calendars()169
.await170
.map_err(|error| error.to_string())?;171
let mut calendars = parse_calendar_list(&list)172
.into_iter()173
.map(|(id, summary, primary)| GoogleCalendarInfo {174
id,175
summary,176
selected: true,177
primary,178
})179
.collect::<Vec<_>>();180
if calendars.is_empty() {181
calendars.push(GoogleCalendarInfo {182
id: "primary".into(),183
summary: "Primary".into(),184
selected: true,185
primary: true,186
});187
}188
let email = calendars189
.iter()190
.find(|calendar| calendar.primary)191
.map(|calendar| calendar.summary.clone())192
.unwrap_or_else(|| "Google".into());193
let account = GoogleAccount {194
id: Uuid::new_v4().to_string(),195
email: email.clone(),196
calendars,197
tokens: GoogleTokenSet {198
access_token: bundle.access_token,199
refresh_token: bundle.refresh_token,200
expires_at: Utc::now().timestamp() + bundle.expires_in.max(60),201
},202
};203
let mut accounts = load_calendar_accounts(&store);204
accounts.google_accounts.push(account);205
save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;206
Ok(email)207
}@@ -17,6 +17,9 @@ pub(crate) fn demo_anchor() -> DateTime<Utc> {
17
17
18
18
impl AppState {
19
19
pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {
20
// Agenda / reminders poll — must not replace calendar_week.events.
21
// That window is only ~today+7d; overwriting wiped earlier days in the
22
// visible week/month and made entries "vanish" after delete or poll.
20
23
self.calendar_events = events;
21
24
self.calls_list.invalidate();
22
25
cx.emit(AppEvent::CallHistory);
@@ -29,22 +32,25 @@ impl AppState {
29
32
events.extend(self.demo_meetings.iter().cloned());
30
33
events.sort_by_key(|event| (event.start, event.end));
31
34
self.apply_calendar(events, cx);
35
if self.calendar_week.start.is_some() {
36
self.load_calendar_week(cx);
37
}
32
38
return;
33
39
}
34
40
if let Some(nudge) = &self.calendar_nudge {
35
41
let _ = nudge.send(());
36
42
}
43
// Visible grid SoT is load_calendar_week (full span + Google merge).
44
if self.calendar_week.start.is_some() {
45
self.load_calendar_week(cx);
46
}
37
47
}
38
48
39
49
pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {
40
50
let now = Utc::now();
41
51
let offset = Local::now().offset().fix();
42
self.calls_list.rebuild(
43
&self.call_history,
44
&self.sidebar.chats,
45
now,
46
offset,
47
);
52
self.calls_list
53
.rebuild(&self.call_history, &self.sidebar.chats, now, offset);
48
54
cx.emit(AppEvent::CallHistory);
49
55
cx.notify();
50
56
}
@@ -17,6 +17,9 @@ pub(crate) fn demo_anchor() -> DateTime<Utc> {17
17
18
impl AppState {18
impl AppState {19
pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {19
pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {20
// Agenda / reminders poll — must not replace calendar_week.events.21
// That window is only ~today+7d; overwriting wiped earlier days in the22
// visible week/month and made entries "vanish" after delete or poll.20
self.calendar_events = events;23
self.calendar_events = events;21
self.calls_list.invalidate();24
self.calls_list.invalidate();22
cx.emit(AppEvent::CallHistory);25
cx.emit(AppEvent::CallHistory);@@ -29,22 +32,25 @@ impl AppState {29
events.extend(self.demo_meetings.iter().cloned());32
events.extend(self.demo_meetings.iter().cloned());30
events.sort_by_key(|event| (event.start, event.end));33
events.sort_by_key(|event| (event.start, event.end));31
self.apply_calendar(events, cx);34
self.apply_calendar(events, cx);35
if self.calendar_week.start.is_some() {36
self.load_calendar_week(cx);37
}32
return;38
return;33
}39
}34
if let Some(nudge) = &self.calendar_nudge {40
if let Some(nudge) = &self.calendar_nudge {35
let _ = nudge.send(());41
let _ = nudge.send(());36
}42
}43
// Visible grid SoT is load_calendar_week (full span + Google merge).44
if self.calendar_week.start.is_some() {45
self.load_calendar_week(cx);46
}37
}47
}38
48
39
pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {49
pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {40
let now = Utc::now();50
let now = Utc::now();41
let offset = Local::now().offset().fix();51
let offset = Local::now().offset().fix();42
self.calls_list.rebuild(52
self.calls_list43
&self.call_history,53
.rebuild(&self.call_history, &self.sidebar.chats, now, offset);44
&self.sidebar.chats,45
now,46
offset,47
);48
cx.emit(AppEvent::CallHistory);54
cx.emit(AppEvent::CallHistory);49
cx.notify();55
cx.notify();50
}56
}@@ -1,14 +1,14 @@
1
1
use std::future::Future;
2
2
use std::sync::{Arc, Mutex};
3
3
4
use tokio::sync::watch;
5
4
use std::time::Duration;
5
use tokio::sync::watch;
6
6
7
7
use calling::meeting::{LiveMeeting, fetch_live_meeting};
8
8
use calling::{
9
AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,
10
DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent, MeetingTarget,
11
call_channel,
9
AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState,
10
CallUpdate, DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent,
11
MeetingTarget, call_channel,
12
12
};
13
13
use session::{Session, SessionConfig, Transport};
14
14
@@ -163,16 +163,16 @@ impl CallLauncher {
163
163
.map_err(|error| error.to_string())
164
164
}
165
165
166
pub async fn create_meeting(
166
pub async fn resolve_new_event(
167
167
&self,
168
168
draft: MeetingDraft,
169
) -> Result<chatsvc::CreatedEvent, String> {
169
) -> Result<chatsvc::NewEvent, String> {
170
170
let session = self
171
171
.ready_engine()
172
172
.await
173
173
.ok_or_else(|| NOT_READY.to_owned())?
174
174
.session();
175
let graph = graph::Graph::new(session.clone());
175
let graph = graph::Graph::new(session);
176
176
let mut attendees = Vec::with_capacity(draft.people.len());
177
177
for invitee in &draft.people {
178
178
let looked_up = match invitee.mail {
@@ -181,7 +181,7 @@ impl CallLauncher {
181
181
};
182
182
attendees.push(attendee_for(invitee, looked_up)?);
183
183
}
184
let event = chatsvc::NewEvent {
184
Ok(chatsvc::NewEvent {
185
185
subject: draft.subject,
186
186
start: draft.start,
187
187
end: draft.end,
@@ -191,13 +191,41 @@ impl CallLauncher {
191
191
attendees,
192
192
repeat: draft.repeat,
193
193
details: draft.details,
194
};
194
})
195
}
196
197
pub async fn create_meeting(
198
&self,
199
draft: MeetingDraft,
200
) -> Result<chatsvc::CreatedEvent, String> {
201
let session = self
202
.ready_engine()
203
.await
204
.ok_or_else(|| NOT_READY.to_owned())?
205
.session();
206
let event = self.resolve_new_event(draft).await?;
195
207
chatsvc::Calendar::new(&session)
196
208
.create_event(&event)
197
209
.await
198
210
.map_err(|error| error.to_string())
199
211
}
200
212
213
pub async fn create_meeting_with_join(
214
&self,
215
event: chatsvc::NewEvent,
216
join_url: &str,
217
) -> Result<chatsvc::CreatedEvent, String> {
218
let session = self
219
.ready_engine()
220
.await
221
.ok_or_else(|| NOT_READY.to_owned())?
222
.session();
223
chatsvc::Calendar::new(&session)
224
.create_event_with_join(&event, join_url)
225
.await
226
.map_err(|error| error.to_string())
227
}
228
201
229
pub async fn time_zone_name(&self, mail: &str) -> Option<String> {
202
230
let session = self.engine()?.session();
203
231
graph::Graph::new(session)
@@ -225,6 +253,22 @@ impl CallLauncher {
225
253
.map_err(|error| error.to_string())
226
254
}
227
255
256
pub async fn delete_calendar_event(
257
&self,
258
event_id: &str,
259
ical_uid: Option<&str>,
260
) -> Result<(), String> {
261
let session = self
262
.ready_engine()
263
.await
264
.ok_or_else(|| NOT_READY.to_owned())?
265
.session();
266
chatsvc::Calendar::new(&session)
267
.delete_event(event_id, ical_uid)
268
.await
269
.map_err(|error| error.to_string())
270
}
271
228
272
pub async fn calendar_view(
229
273
&self,
230
274
start: chrono::DateTime<chrono::Utc>,
@@ -423,24 +467,39 @@ mod tests {
423
467
#[tokio::test]
424
468
async fn waiting_gives_up_after_the_timeout() {
425
469
let (_sender, receiver) = watch::channel(None::<u32>);
426
assert_eq!(wait_until_ready(receiver, Duration::from_millis(20)).await, None);
470
assert_eq!(
471
wait_until_ready(receiver, Duration::from_millis(20)).await,
472
None
473
);
427
474
}
428
475
429
476
#[tokio::test]
430
477
async fn waiting_gives_up_when_the_launcher_is_gone() {
431
478
let (sender, receiver) = watch::channel(None::<u32>);
432
479
drop(sender);
433
assert_eq!(wait_until_ready(receiver, Duration::from_secs(5)).await, None);
480
assert_eq!(
481
wait_until_ready(receiver, Duration::from_secs(5)).await,
482
None
483
);
434
484
}
435
485
436
486
#[tokio::test]
437
487
async fn queued_call_fails_with_notice_after_the_timeout() {
438
488
let (_sender, receiver) = watch::channel(None);
439
489
let (mut handle, control) = call_channel();
440
queue_outgoing(receiver, Duration::from_millis(20), CallSpec::Echo, OutgoingKind::Audio, control).await;
490
queue_outgoing(
491
receiver,
492
Duration::from_millis(20),
493
CallSpec::Echo,
494
OutgoingKind::Audio,
495
control,
496
)
497
.await;
441
498
assert_eq!(
442
499
handle.updates.recv().await,
443
Some(CallUpdate::State(CallState::Ended { reason: EndReason::Failed(NOT_READY.to_owned()) }))
500
Some(CallUpdate::State(CallState::Ended {
501
reason: EndReason::Failed(NOT_READY.to_owned())
502
}))
444
503
);
445
504
}
446
505
@@ -449,10 +508,19 @@ mod tests {
449
508
let (_sender, receiver) = watch::channel(None);
450
509
let (mut handle, control) = call_channel();
451
510
handle.commands.send(CallCommand::Hangup).unwrap();
452
queue_outgoing(receiver, Duration::from_secs(30), CallSpec::Echo, OutgoingKind::Video, control).await;
511
queue_outgoing(
512
receiver,
513
Duration::from_secs(30),
514
CallSpec::Echo,
515
OutgoingKind::Video,
516
control,
517
)
518
.await;
453
519
assert_eq!(
454
520
handle.updates.recv().await,
455
Some(CallUpdate::State(CallState::Ended { reason: EndReason::Cancelled }))
521
Some(CallUpdate::State(CallState::Ended {
522
reason: EndReason::Cancelled
523
}))
456
524
);
457
525
}
458
526
}
@@ -1,14 +1,14 @@1
use std::future::Future;1
use std::future::Future;2
use std::sync::{Arc, Mutex};2
use std::sync::{Arc, Mutex};3
3
4
use tokio::sync::watch;5
use std::time::Duration;4
use std::time::Duration;5
use tokio::sync::watch;6
6
7
use calling::meeting::{LiveMeeting, fetch_live_meeting};7
use calling::meeting::{LiveMeeting, fetch_live_meeting};8
use calling::{8
use calling::{9
AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,9
AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState,10
DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent, MeetingTarget,10
CallUpdate, DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent,11
call_channel,11
MeetingTarget, call_channel,12
};12
};13
use session::{Session, SessionConfig, Transport};13
use session::{Session, SessionConfig, Transport};14
14
@@ -163,16 +163,16 @@ impl CallLauncher {163
.map_err(|error| error.to_string())163
.map_err(|error| error.to_string())164
}164
}165
165
166
pub async fn create_meeting(166
pub async fn resolve_new_event(167
&self,167
&self,168
draft: MeetingDraft,168
draft: MeetingDraft,169
) -> Result<chatsvc::CreatedEvent, String> {169
) -> Result<chatsvc::NewEvent, String> {170
let session = self170
let session = self171
.ready_engine()171
.ready_engine()172
.await172
.await173
.ok_or_else(|| NOT_READY.to_owned())?173
.ok_or_else(|| NOT_READY.to_owned())?174
.session();174
.session();175
let graph = graph::Graph::new(session.clone());175
let graph = graph::Graph::new(session);176
let mut attendees = Vec::with_capacity(draft.people.len());176
let mut attendees = Vec::with_capacity(draft.people.len());177
for invitee in &draft.people {177
for invitee in &draft.people {178
let looked_up = match invitee.mail {178
let looked_up = match invitee.mail {@@ -181,7 +181,7 @@ impl CallLauncher {181
};181
};182
attendees.push(attendee_for(invitee, looked_up)?);182
attendees.push(attendee_for(invitee, looked_up)?);183
}183
}184
let event = chatsvc::NewEvent {184
Ok(chatsvc::NewEvent {185
subject: draft.subject,185
subject: draft.subject,186
start: draft.start,186
start: draft.start,187
end: draft.end,187
end: draft.end,@@ -191,13 +191,41 @@ impl CallLauncher {191
attendees,191
attendees,192
repeat: draft.repeat,192
repeat: draft.repeat,193
details: draft.details,193
details: draft.details,194
};194
})195
}196
197
pub async fn create_meeting(198
&self,199
draft: MeetingDraft,200
) -> Result<chatsvc::CreatedEvent, String> {201
let session = self202
.ready_engine()203
.await204
.ok_or_else(|| NOT_READY.to_owned())?205
.session();206
let event = self.resolve_new_event(draft).await?;195
chatsvc::Calendar::new(&session)207
chatsvc::Calendar::new(&session)196
.create_event(&event)208
.create_event(&event)197
.await209
.await198
.map_err(|error| error.to_string())210
.map_err(|error| error.to_string())199
}211
}200
212
213
pub async fn create_meeting_with_join(214
&self,215
event: chatsvc::NewEvent,216
join_url: &str,217
) -> Result<chatsvc::CreatedEvent, String> {218
let session = self219
.ready_engine()220
.await221
.ok_or_else(|| NOT_READY.to_owned())?222
.session();223
chatsvc::Calendar::new(&session)224
.create_event_with_join(&event, join_url)225
.await226
.map_err(|error| error.to_string())227
}228
201
pub async fn time_zone_name(&self, mail: &str) -> Option<String> {229
pub async fn time_zone_name(&self, mail: &str) -> Option<String> {202
let session = self.engine()?.session();230
let session = self.engine()?.session();203
graph::Graph::new(session)231
graph::Graph::new(session)@@ -225,6 +253,22 @@ impl CallLauncher {225
.map_err(|error| error.to_string())253
.map_err(|error| error.to_string())226
}254
}227
255
256
pub async fn delete_calendar_event(257
&self,258
event_id: &str,259
ical_uid: Option<&str>,260
) -> Result<(), String> {261
let session = self262
.ready_engine()263
.await264
.ok_or_else(|| NOT_READY.to_owned())?265
.session();266
chatsvc::Calendar::new(&session)267
.delete_event(event_id, ical_uid)268
.await269
.map_err(|error| error.to_string())270
}271
228
pub async fn calendar_view(272
pub async fn calendar_view(229
&self,273
&self,230
start: chrono::DateTime<chrono::Utc>,274
start: chrono::DateTime<chrono::Utc>,@@ -423,24 +467,39 @@ mod tests {423
#[tokio::test]467
#[tokio::test]424
async fn waiting_gives_up_after_the_timeout() {468
async fn waiting_gives_up_after_the_timeout() {425
let (_sender, receiver) = watch::channel(None::<u32>);469
let (_sender, receiver) = watch::channel(None::<u32>);426
assert_eq!(wait_until_ready(receiver, Duration::from_millis(20)).await, None);470
assert_eq!(471
wait_until_ready(receiver, Duration::from_millis(20)).await,472
None473
);427
}474
}428
475
429
#[tokio::test]476
#[tokio::test]430
async fn waiting_gives_up_when_the_launcher_is_gone() {477
async fn waiting_gives_up_when_the_launcher_is_gone() {431
let (sender, receiver) = watch::channel(None::<u32>);478
let (sender, receiver) = watch::channel(None::<u32>);432
drop(sender);479
drop(sender);433
assert_eq!(wait_until_ready(receiver, Duration::from_secs(5)).await, None);480
assert_eq!(481
wait_until_ready(receiver, Duration::from_secs(5)).await,482
None483
);434
}484
}435
485
436
#[tokio::test]486
#[tokio::test]437
async fn queued_call_fails_with_notice_after_the_timeout() {487
async fn queued_call_fails_with_notice_after_the_timeout() {438
let (_sender, receiver) = watch::channel(None);488
let (_sender, receiver) = watch::channel(None);439
let (mut handle, control) = call_channel();489
let (mut handle, control) = call_channel();440
queue_outgoing(receiver, Duration::from_millis(20), CallSpec::Echo, OutgoingKind::Audio, control).await;490
queue_outgoing(491
receiver,492
Duration::from_millis(20),493
CallSpec::Echo,494
OutgoingKind::Audio,495
control,496
)497
.await;441
assert_eq!(498
assert_eq!(442
handle.updates.recv().await,499
handle.updates.recv().await,443
Some(CallUpdate::State(CallState::Ended { reason: EndReason::Failed(NOT_READY.to_owned()) }))500
Some(CallUpdate::State(CallState::Ended {501
reason: EndReason::Failed(NOT_READY.to_owned())502
}))444
);503
);445
}504
}446
505
@@ -449,10 +508,19 @@ mod tests {449
let (_sender, receiver) = watch::channel(None);508
let (_sender, receiver) = watch::channel(None);450
let (mut handle, control) = call_channel();509
let (mut handle, control) = call_channel();451
handle.commands.send(CallCommand::Hangup).unwrap();510
handle.commands.send(CallCommand::Hangup).unwrap();452
queue_outgoing(receiver, Duration::from_secs(30), CallSpec::Echo, OutgoingKind::Video, control).await;511
queue_outgoing(512
receiver,513
Duration::from_secs(30),514
CallSpec::Echo,515
OutgoingKind::Video,516
control,517
)518
.await;453
assert_eq!(519
assert_eq!(454
handle.updates.recv().await,520
handle.updates.recv().await,455
Some(CallUpdate::State(CallState::Ended { reason: EndReason::Cancelled }))521
Some(CallUpdate::State(CallState::Ended {522
reason: EndReason::Cancelled523
}))456
);524
);457
}525
}458
}526
}@@ -0,0 +1,164 @@
1
use std::sync::Arc;
2
3
use chatsvc::{CreatedEvent, GoogleEventDraft, NewEvent};
4
use store::{CalendarAccounts, CalendarProvider, CalendarRef, Store};
5
6
use super::launcher::CallLauncher;
7
use super::schedule::MeetingDraft;
8
9
/// Whether create must mint a Teams join URL before per-target inserts.
10
pub fn needs_join_first(accounts: &CalendarAccounts) -> bool {
11
let targets = accounts.resolved_write_targets();
12
targets.len() > 1
13
|| targets
14
.iter()
15
.any(|target| target.provider == CalendarProvider::Google)
16
}
17
18
/// Write targets used for New meeting (home + extras, de-duplicated).
19
pub fn create_targets(accounts: &CalendarAccounts) -> Vec<CalendarRef> {
20
accounts.resolved_write_targets()
21
}
22
23
/// Format a partial-failure notice when the join link exists but a target failed.
24
pub fn partial_create_notice(join_url: &str, failed: &[String]) -> String {
25
format!(
26
"Meeting link ready, but calendar write failed for {}: {join_url}",
27
failed.join(", ")
28
)
29
}
30
31
pub async fn create_across_targets(
32
launcher: Arc<CallLauncher>,
33
draft: MeetingDraft,
34
mut accounts: CalendarAccounts,
35
store: Arc<Store>,
36
) -> Result<CreatedEvent, String> {
37
if !needs_join_first(&accounts) {
38
return launcher.create_meeting(draft).await;
39
}
40
let event = launcher.resolve_new_event(draft).await?;
41
let join_url = launcher.create_meet_now(&event.subject).await?;
42
let targets = create_targets(&accounts);
43
let mut failed = Vec::new();
44
let mut first_id = String::new();
45
for target in targets {
46
match write_target(launcher.as_ref(), &mut accounts, &target, &event, &join_url).await {
47
Ok(id) => {
48
if first_id.is_empty() {
49
first_id = id;
50
}
51
}
52
Err(error) => failed.push(format!("{} ({error})", target.key())),
53
}
54
}
55
let _ = store::save_calendar_accounts(&store, &accounts);
56
if !failed.is_empty() {
57
crate::diagnostics::record(partial_create_notice(&join_url, &failed));
58
if first_id.is_empty() {
59
return Err(partial_create_notice(&join_url, &failed));
60
}
61
}
62
Ok(CreatedEvent {
63
id: if first_id.is_empty() {
64
join_url.clone()
65
} else {
66
first_id
67
},
68
join_url: Some(join_url),
69
})
70
}
71
72
async fn write_target(
73
launcher: &CallLauncher,
74
accounts: &mut CalendarAccounts,
75
target: &CalendarRef,
76
event: &NewEvent,
77
join_url: &str,
78
) -> Result<String, String> {
79
match target.provider {
80
CalendarProvider::Outlook => launcher
81
.create_meeting_with_join(event.clone(), join_url)
82
.await
83
.map(|created| created.id),
84
CalendarProvider::Google => {
85
let calendar_id = if target.calendar_id.is_empty() {
86
"primary"
87
} else {
88
target.calendar_id.as_str()
89
};
90
let mut draft = GoogleEventDraft::from(event);
91
draft.join_url = Some(join_url.to_owned());
92
crate::google_calendar_sync::insert_google_event(
93
accounts,
94
&target.account_id,
95
calendar_id,
96
&draft,
97
)
98
.await?;
99
Ok(format!("google:{}:{}", target.account_id, calendar_id))
100
}
101
}
102
}
103
104
#[cfg(test)]
105
mod tests {
106
use store::{CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet};
107
108
use super::*;
109
110
fn google_home() -> CalendarAccounts {
111
CalendarAccounts {
112
home: CalendarRef::google("g1", "primary"),
113
write_targets: Vec::new(),
114
outlook_selected: true,
115
google_accounts: vec![GoogleAccount {
116
id: "g1".into(),
117
email: "joe@example.com".into(),
118
calendars: vec![GoogleCalendarInfo {
119
id: "primary".into(),
120
summary: "Joe".into(),
121
selected: true,
122
primary: true,
123
}],
124
tokens: GoogleTokenSet::default(),
125
}],
126
}
127
}
128
129
#[test]
130
fn outlook_only_home_keeps_one_step() {
131
let accounts = CalendarAccounts::default();
132
assert!(!needs_join_first(&accounts));
133
assert_eq!(create_targets(&accounts).len(), 1);
134
assert_eq!(
135
create_targets(&accounts)[0].provider,
136
CalendarProvider::Outlook
137
);
138
}
139
140
#[test]
141
fn google_home_needs_join_first() {
142
assert!(needs_join_first(&google_home()));
143
}
144
145
#[test]
146
fn outlook_home_with_google_extra_needs_join_first() {
147
let mut accounts = CalendarAccounts::default();
148
accounts
149
.write_targets
150
.push(CalendarRef::google("g1", "primary"));
151
assert!(needs_join_first(&accounts));
152
assert_eq!(create_targets(&accounts).len(), 2);
153
}
154
155
#[test]
156
fn partial_notice_keeps_join_url() {
157
let notice = partial_create_notice(
158
"https://teams.microsoft.com/l/meetup-join/x",
159
&["Google:primary".into()],
160
);
161
assert!(notice.contains("teams.microsoft.com"));
162
assert!(notice.contains("Google:primary"));
163
}
164
}
@@ -0,0 +1,164 @@1
use std::sync::Arc;2
3
use chatsvc::{CreatedEvent, GoogleEventDraft, NewEvent};4
use store::{CalendarAccounts, CalendarProvider, CalendarRef, Store};5
6
use super::launcher::CallLauncher;7
use super::schedule::MeetingDraft;8
9
/// Whether create must mint a Teams join URL before per-target inserts.10
pub fn needs_join_first(accounts: &CalendarAccounts) -> bool {11
let targets = accounts.resolved_write_targets();12
targets.len() > 113
|| targets14
.iter()15
.any(|target| target.provider == CalendarProvider::Google)16
}17
18
/// Write targets used for New meeting (home + extras, de-duplicated).19
pub fn create_targets(accounts: &CalendarAccounts) -> Vec<CalendarRef> {20
accounts.resolved_write_targets()21
}22
23
/// Format a partial-failure notice when the join link exists but a target failed.24
pub fn partial_create_notice(join_url: &str, failed: &[String]) -> String {25
format!(26
"Meeting link ready, but calendar write failed for {}: {join_url}",27
failed.join(", ")28
)29
}30
31
pub async fn create_across_targets(32
launcher: Arc<CallLauncher>,33
draft: MeetingDraft,34
mut accounts: CalendarAccounts,35
store: Arc<Store>,36
) -> Result<CreatedEvent, String> {37
if !needs_join_first(&accounts) {38
return launcher.create_meeting(draft).await;39
}40
let event = launcher.resolve_new_event(draft).await?;41
let join_url = launcher.create_meet_now(&event.subject).await?;42
let targets = create_targets(&accounts);43
let mut failed = Vec::new();44
let mut first_id = String::new();45
for target in targets {46
match write_target(launcher.as_ref(), &mut accounts, &target, &event, &join_url).await {47
Ok(id) => {48
if first_id.is_empty() {49
first_id = id;50
}51
}52
Err(error) => failed.push(format!("{} ({error})", target.key())),53
}54
}55
let _ = store::save_calendar_accounts(&store, &accounts);56
if !failed.is_empty() {57
crate::diagnostics::record(partial_create_notice(&join_url, &failed));58
if first_id.is_empty() {59
return Err(partial_create_notice(&join_url, &failed));60
}61
}62
Ok(CreatedEvent {63
id: if first_id.is_empty() {64
join_url.clone()65
} else {66
first_id67
},68
join_url: Some(join_url),69
})70
}71
72
async fn write_target(73
launcher: &CallLauncher,74
accounts: &mut CalendarAccounts,75
target: &CalendarRef,76
event: &NewEvent,77
join_url: &str,78
) -> Result<String, String> {79
match target.provider {80
CalendarProvider::Outlook => launcher81
.create_meeting_with_join(event.clone(), join_url)82
.await83
.map(|created| created.id),84
CalendarProvider::Google => {85
let calendar_id = if target.calendar_id.is_empty() {86
"primary"87
} else {88
target.calendar_id.as_str()89
};90
let mut draft = GoogleEventDraft::from(event);91
draft.join_url = Some(join_url.to_owned());92
crate::google_calendar_sync::insert_google_event(93
accounts,94
&target.account_id,95
calendar_id,96
&draft,97
)98
.await?;99
Ok(format!("google:{}:{}", target.account_id, calendar_id))100
}101
}102
}103
104
#[cfg(test)]105
mod tests {106
use store::{CalendarRef, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet};107
108
use super::*;109
110
fn google_home() -> CalendarAccounts {111
CalendarAccounts {112
home: CalendarRef::google("g1", "primary"),113
write_targets: Vec::new(),114
outlook_selected: true,115
google_accounts: vec![GoogleAccount {116
id: "g1".into(),117
email: "joe@example.com".into(),118
calendars: vec![GoogleCalendarInfo {119
id: "primary".into(),120
summary: "Joe".into(),121
selected: true,122
primary: true,123
}],124
tokens: GoogleTokenSet::default(),125
}],126
}127
}128
129
#[test]130
fn outlook_only_home_keeps_one_step() {131
let accounts = CalendarAccounts::default();132
assert!(!needs_join_first(&accounts));133
assert_eq!(create_targets(&accounts).len(), 1);134
assert_eq!(135
create_targets(&accounts)[0].provider,136
CalendarProvider::Outlook137
);138
}139
140
#[test]141
fn google_home_needs_join_first() {142
assert!(needs_join_first(&google_home()));143
}144
145
#[test]146
fn outlook_home_with_google_extra_needs_join_first() {147
let mut accounts = CalendarAccounts::default();148
accounts149
.write_targets150
.push(CalendarRef::google("g1", "primary"));151
assert!(needs_join_first(&accounts));152
assert_eq!(create_targets(&accounts).len(), 2);153
}154
155
#[test]156
fn partial_notice_keeps_join_url() {157
let notice = partial_create_notice(158
"https://teams.microsoft.com/l/meetup-join/x",159
&["Google:primary".into()],160
);161
assert!(notice.contains("teams.microsoft.com"));162
assert!(notice.contains("Google:primary"));163
}164
}@@ -7,39 +7,39 @@ pub mod history;
7
7
pub mod join;
8
8
pub mod launcher;
9
9
pub mod list;
10
pub mod meeting_create;
10
11
pub mod outlook_reminders;
11
12
pub mod overlay_layout;
12
13
pub mod people_actions;
13
14
pub mod prejoin;
14
15
pub mod record_load;
15
pub mod remote_command;
16
16
pub mod reminder;
17
pub mod remote_command;
18
pub mod schedule;
17
19
pub mod share_actions;
18
20
pub mod share_overlay;
19
21
pub mod speed_dial;
20
pub mod schedule;
21
22
pub mod target;
22
23
pub mod view_actions;
23
24
pub mod week;
24
25
25
26
pub use app_call_model::{
26
agenda, background, bubbles, caption_style, demo, end_screen, fullscreen, health, media, mic,
27
model, options_dialog, people, preview, record_rights,
28
recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,
29
week_grid,
27
agenda, background, bubbles, calendar_now, caption_style, demo, end_screen, fullscreen, health,
28
media, mic, model, options_dialog, people, preview, record_rights, recording_menu, report,
29
ring, share_view, stage_layout, stage_split, transcript, view_settings, week_grid,
30
30
};
31
31
32
32
pub use actions::{
33
33
apply_sound_output, load_camera, load_camera_effects, load_input, load_output, load_share_sound,
34
load_video_quality,
34
35
};
35
pub use mic::load_mic;
36
36
pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
37
pub use caption_style::{CaptionPosition, CaptionSize};
38
37
pub use background::{
39
38
BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
40
39
load_custom_backgrounds,
41
40
};
42
41
pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};
42
pub use caption_style::{CaptionPosition, CaptionSize};
43
43
pub use demo::DemoScene;
44
44
pub use features::TransferCandidate;
45
45
pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};
@@ -47,29 +47,33 @@ pub use history::CallRow;
47
47
pub use launcher::CallLauncher;
48
48
pub use list::{CALL_ROW_HEIGHT, CallsList, EMPTY_HEIGHT, HistoryFilter, ListEntry};
49
49
pub use media::CallMedia;
50
pub use mic::load_mic;
51
pub use model::ConsultCall;
50
52
pub use model::{
51
53
ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
52
54
TileState,
53
55
};
54
pub use model::ConsultCall;
55
56
pub use options_dialog::OptionsDialog;
56
pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
57
57
pub use people::{PeopleSections, PersonRow, people_sections};
58
pub use share_actions::ZoomStep;
59
pub use speed_dial::SpeedDialEntry;
60
pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, ShareStage, load_flag};
58
pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
61
59
pub use preview::{CameraPreview, preview_backgrounds};
60
pub use record_rights::{RecordBlock, RecordFeature};
61
pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
62
62
pub use reminder::{MeetingToasts, ReminderPhase, subtitle as meeting_subtitle};
63
pub use report::load_enabled as load_report_enabled;
63
64
pub use ring::{MissedCall, RingEntry, Rings};
64
pub use stage_split::{
65
GRID_PADDING, STRIP_GAP, GalleryPage, SpeakerSplit, StripSplit, TILE_GAP, gallery_page,
66
measured_stage, speaker_split, strip_split, video_wants,
65
pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
66
pub use share_actions::ZoomStep;
67
pub use share_view::{
68
SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, STRIP_WIDTH_META_KEY,
69
ShareStage, StripDrag, clamp_strip_width, load_flag, load_strip_width,
67
70
};
71
pub use speed_dial::SpeedDialEntry;
68
72
pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};
69
pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
70
pub use record_rights::{RecordBlock, RecordFeature};
71
pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
72
pub use report::load_enabled as load_report_enabled;
73
pub use stage_split::{
74
GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP, gallery_page, measured_stage,
75
speaker_split, strip_split, video_wants,
76
};
73
77
pub use target::{is_echo_chat, plan_for_chat};
74
78
pub use transcript::clock_label;
75
79
pub use view_settings::{CallLayout, ViewSettings};
@@ -7,39 +7,39 @@ pub mod history;7
pub mod join;7
pub mod join;8
pub mod launcher;8
pub mod launcher;9
pub mod list;9
pub mod list;10
pub mod meeting_create;10
pub mod outlook_reminders;11
pub mod outlook_reminders;11
pub mod overlay_layout;12
pub mod overlay_layout;12
pub mod people_actions;13
pub mod people_actions;13
pub mod prejoin;14
pub mod prejoin;14
pub mod record_load;15
pub mod record_load;15
pub mod remote_command;16
pub mod reminder;16
pub mod reminder;17
pub mod remote_command;18
pub mod schedule;17
pub mod share_actions;19
pub mod share_actions;18
pub mod share_overlay;20
pub mod share_overlay;19
pub mod speed_dial;21
pub mod speed_dial;20
pub mod schedule;21
pub mod target;22
pub mod target;22
pub mod view_actions;23
pub mod view_actions;23
pub mod week;24
pub mod week;24
25
25
pub use app_call_model::{26
pub use app_call_model::{26
agenda, background, bubbles, caption_style, demo, end_screen, fullscreen, health, media, mic,27
agenda, background, bubbles, calendar_now, caption_style, demo, end_screen, fullscreen, health,27
model, options_dialog, people, preview, record_rights,28
media, mic, model, options_dialog, people, preview, record_rights, recording_menu, report,28
recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,29
ring, share_view, stage_layout, stage_split, transcript, view_settings, week_grid,29
week_grid,30
};30
};31
31
32
pub use actions::{32
pub use actions::{33
apply_sound_output, load_camera, load_camera_effects, load_input, load_output, load_share_sound,33
apply_sound_output, load_camera, load_camera_effects, load_input, load_output, load_share_sound,34
load_video_quality,34
};35
};35
pub use mic::load_mic;36
pub use agenda::{AgendaRow, fetch_window, join_available, response_label};36
pub use agenda::{AgendaRow, fetch_window, join_available, response_label};37
pub use caption_style::{CaptionPosition, CaptionSize};38
pub use background::{37
pub use background::{39
BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,38
BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,40
load_custom_backgrounds,39
load_custom_backgrounds,41
};40
};42
pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};41
pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};42
pub use caption_style::{CaptionPosition, CaptionSize};43
pub use demo::DemoScene;43
pub use demo::DemoScene;44
pub use features::TransferCandidate;44
pub use features::TransferCandidate;45
pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};45
pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};@@ -47,29 +47,33 @@ pub use history::CallRow;47
pub use launcher::CallLauncher;47
pub use launcher::CallLauncher;48
pub use list::{CALL_ROW_HEIGHT, CallsList, EMPTY_HEIGHT, HistoryFilter, ListEntry};48
pub use list::{CALL_ROW_HEIGHT, CallsList, EMPTY_HEIGHT, HistoryFilter, ListEntry};49
pub use media::CallMedia;49
pub use media::CallMedia;50
pub use mic::load_mic;51
pub use model::ConsultCall;50
pub use model::{52
pub use model::{51
ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,53
ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,52
TileState,54
TileState,53
};55
};54
pub use model::ConsultCall;55
pub use options_dialog::OptionsDialog;56
pub use options_dialog::OptionsDialog;56
pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};57
pub use people::{PeopleSections, PersonRow, people_sections};57
pub use people::{PeopleSections, PersonRow, people_sections};58
pub use share_actions::ZoomStep;58
pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};59
pub use speed_dial::SpeedDialEntry;60
pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, ShareStage, load_flag};61
pub use preview::{CameraPreview, preview_backgrounds};59
pub use preview::{CameraPreview, preview_backgrounds};60
pub use record_rights::{RecordBlock, RecordFeature};61
pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};62
pub use reminder::{MeetingToasts, ReminderPhase, subtitle as meeting_subtitle};62
pub use reminder::{MeetingToasts, ReminderPhase, subtitle as meeting_subtitle};63
pub use report::load_enabled as load_report_enabled;63
pub use ring::{MissedCall, RingEntry, Rings};64
pub use ring::{MissedCall, RingEntry, Rings};64
pub use stage_split::{65
pub use schedule::{FormValues, Invitee, default_window, draft_from_form};65
GRID_PADDING, STRIP_GAP, GalleryPage, SpeakerSplit, StripSplit, TILE_GAP, gallery_page,66
pub use share_actions::ZoomStep;66
measured_stage, speaker_split, strip_split, video_wants,67
pub use share_view::{68
SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, STRIP_WIDTH_META_KEY,69
ShareStage, StripDrag, clamp_strip_width, load_flag, load_strip_width,67
};70
};71
pub use speed_dial::SpeedDialEntry;68
pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};72
pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};69
pub use schedule::{FormValues, Invitee, default_window, draft_from_form};73
pub use stage_split::{70
pub use record_rights::{RecordBlock, RecordFeature};74
GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP, gallery_page, measured_stage,71
pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};75
speaker_split, strip_split, video_wants,72
pub use report::load_enabled as load_report_enabled;76
};73
pub use target::{is_echo_chat, plan_for_chat};77
pub use target::{is_echo_chat, plan_for_chat};74
pub use transcript::clock_label;78
pub use transcript::clock_label;75
pub use view_settings::{CallLayout, ViewSettings};79
pub use view_settings::{CallLayout, ViewSettings};@@ -1,6 +1,6 @@
1
1
use std::collections::HashMap;
2
2
3
use chatsvc::{CalendarEvent, Reminder};
3
use chatsvc::{CalendarEvent, CalendarSource, Reminder};
4
4
use chrono::{DateTime, Duration, Utc};
5
5
use gpui_kit::Context;
6
6
@@ -33,6 +33,9 @@ pub enum ReminderWrite {
33
33
}
34
34
35
35
fn watched(event: &CalendarEvent, now: DateTime<Utc>) -> bool {
36
if event.source != CalendarSource::Outlook {
37
return false;
38
}
36
39
let watch_from = event.start - Duration::minutes(LEAD_MINUTES + WATCH_BEFORE_LEAD_MINUTES);
37
40
let watch_until = event
38
41
.end
@@ -79,6 +82,11 @@ impl OutlookReminders {
79
82
}
80
83
81
84
pub fn allows(&self, event: &CalendarEvent, now: DateTime<Utc>) -> bool {
85
// Google (and later sources) use the local Soon/Started phase only —
86
// Outlook ReminderView must not suppress them when the id is absent.
87
if event.source != CalendarSource::Outlook {
88
return true;
89
}
82
90
let Some(known) = &self.known else {
83
91
return true;
84
92
};
@@ -192,6 +200,7 @@ mod tests {
192
200
show_as: Default::default(),
193
201
dial_in: None,
194
202
response: ResponseType::Accepted,
203
..Default::default()
195
204
}
196
205
}
197
206
@@ -243,6 +252,16 @@ mod tests {
243
252
assert!(outlook.allows(&event("b"), at(9, 40)));
244
253
}
245
254
255
#[test]
256
fn google_events_stay_allowed_when_outlook_reminder_view_is_loaded() {
257
let outlook = known(vec![reminder("outlook-1", at(9, 30))], at(9, 39));
258
let mut google = event("google-1");
259
google.source = CalendarSource::Google;
260
google.sources = vec![CalendarSource::Google];
261
assert!(outlook.allows(&google, at(9, 40)));
262
assert!(!outlook.allows(&event("missing-outlook"), at(9, 40)));
263
}
264
246
265
#[test]
247
266
fn a_reminder_snoozed_in_outlook_waits_for_its_fire_time() {
248
267
let outlook = known(vec![reminder("a", at(9, 43))], at(9, 39));
@@ -1,6 +1,6 @@1
use std::collections::HashMap;1
use std::collections::HashMap;2
2
3
use chatsvc::{CalendarEvent, Reminder};3
use chatsvc::{CalendarEvent, CalendarSource, Reminder};4
use chrono::{DateTime, Duration, Utc};4
use chrono::{DateTime, Duration, Utc};5
use gpui_kit::Context;5
use gpui_kit::Context;6
6
@@ -33,6 +33,9 @@ pub enum ReminderWrite {33
}33
}34
34
35
fn watched(event: &CalendarEvent, now: DateTime<Utc>) -> bool {35
fn watched(event: &CalendarEvent, now: DateTime<Utc>) -> bool {36
if event.source != CalendarSource::Outlook {37
return false;38
}36
let watch_from = event.start - Duration::minutes(LEAD_MINUTES + WATCH_BEFORE_LEAD_MINUTES);39
let watch_from = event.start - Duration::minutes(LEAD_MINUTES + WATCH_BEFORE_LEAD_MINUTES);37
let watch_until = event40
let watch_until = event38
.end41
.end@@ -79,6 +82,11 @@ impl OutlookReminders {79
}82
}80
83
81
pub fn allows(&self, event: &CalendarEvent, now: DateTime<Utc>) -> bool {84
pub fn allows(&self, event: &CalendarEvent, now: DateTime<Utc>) -> bool {85
// Google (and later sources) use the local Soon/Started phase only —86
// Outlook ReminderView must not suppress them when the id is absent.87
if event.source != CalendarSource::Outlook {88
return true;89
}82
let Some(known) = &self.known else {90
let Some(known) = &self.known else {83
return true;91
return true;84
};92
};@@ -192,6 +200,7 @@ mod tests {192
show_as: Default::default(),200
show_as: Default::default(),193
dial_in: None,201
dial_in: None,194
response: ResponseType::Accepted,202
response: ResponseType::Accepted,203
..Default::default()195
}204
}196
}205
}197
206
@@ -243,6 +252,16 @@ mod tests {243
assert!(outlook.allows(&event("b"), at(9, 40)));252
assert!(outlook.allows(&event("b"), at(9, 40)));244
}253
}245
254
255
#[test]256
fn google_events_stay_allowed_when_outlook_reminder_view_is_loaded() {257
let outlook = known(vec![reminder("outlook-1", at(9, 30))], at(9, 39));258
let mut google = event("google-1");259
google.source = CalendarSource::Google;260
google.sources = vec![CalendarSource::Google];261
assert!(outlook.allows(&google, at(9, 40)));262
assert!(!outlook.allows(&event("missing-outlook"), at(9, 40)));263
}264
246
#[test]265
#[test]247
fn a_reminder_snoozed_in_outlook_waits_for_its_fire_time() {266
fn a_reminder_snoozed_in_outlook_waits_for_its_fire_time() {248
let outlook = known(vec![reminder("a", at(9, 43))], at(9, 39));267
let outlook = known(vec![reminder("a", at(9, 43))], at(9, 39));@@ -73,7 +73,10 @@ pub struct ReminderUpdate {
73
73
}
74
74
75
75
pub fn subtitle(toast: &MeetingToast, now: DateTime<Utc>, offset: FixedOffset) -> String {
76
let clock = toast.start.with_timezone(&offset).format(app_base::format::clock_format());
76
let clock = toast
77
.start
78
.with_timezone(&offset)
79
.format(app_base::format::clock_format());
77
80
match toast.phase {
78
81
ReminderPhase::Started => format!("{clock} - started"),
79
82
ReminderPhase::Live => format!("{clock} - live now"),
@@ -268,27 +271,37 @@ impl MeetingToasts {
268
271
}
269
272
}
270
273
274
fn reminder_source_events(state: &AppState) -> Vec<CalendarEvent> {
275
let mut events = state.calendar_events.clone();
276
for event in &state.calendar_week.events {
277
if !events
278
.iter()
279
.any(|existing| existing.object_id == event.object_id)
280
{
281
events.push(event.clone());
282
}
283
}
284
events
285
}
286
271
287
impl AppState {
272
288
pub fn tick_meeting_reminders(&mut self, show: bool, cx: &mut Context<Self>) {
273
289
let now = Utc::now();
274
290
self.poll_outlook_reminders(now, cx);
275
291
let in_call = self.call.is_some();
276
292
let show = show && !in_call && !self.mode.read_only;
277
for thread_id in self
278
.meeting_toasts
279
.live_candidates(&self.calendar_events, now)
280
{
293
let events = reminder_source_events(self);
294
for thread_id in self.meeting_toasts.live_candidates(&events, now) {
281
295
self.fetch_live_meeting(&thread_id, cx);
282
296
}
283
let live_threads: HashSet<String> = self
284
.calendar_events
297
let live_threads: HashSet<String> = events
285
298
.iter()
286
299
.filter_map(|event| event.thread_id.clone())
287
300
.filter(|thread_id| self.running_meeting(thread_id).is_some())
288
301
.collect();
289
302
let update = self
290
303
.meeting_toasts
291
.update(&self.calendar_events, &live_threads, now, show);
304
.update(&events, &live_threads, now, show);
292
305
if (in_call && self.meeting_toasts.clear()) || update.changed {
293
306
cx.emit(AppEvent::MeetingReminder);
294
307
cx.notify();
@@ -317,7 +330,9 @@ impl AppState {
317
330
318
331
pub fn snooze_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
319
332
if let Some(toast) = self.meeting_toasts.snooze(id) {
320
self.write_outlook_reminder(toast.event_id, ReminderWrite::Snooze(toast.start));
333
if self.outlook_reminder_event(&toast.event_id) {
334
self.write_outlook_reminder(toast.event_id, ReminderWrite::Snooze(toast.start));
335
}
321
336
cx.emit(AppEvent::MeetingReminder);
322
337
cx.notify();
323
338
}
@@ -325,11 +340,21 @@ impl AppState {
325
340
326
341
pub fn dismiss_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
327
342
if let Some(toast) = self.meeting_toasts.dismiss(id) {
328
self.write_outlook_reminder(toast.event_id, ReminderWrite::Dismiss);
343
if self.outlook_reminder_event(&toast.event_id) {
344
self.write_outlook_reminder(toast.event_id, ReminderWrite::Dismiss);
345
}
329
346
cx.emit(AppEvent::MeetingReminder);
330
347
cx.notify();
331
348
}
332
349
}
350
351
fn outlook_reminder_event(&self, event_id: &str) -> bool {
352
self.calendar_events
353
.iter()
354
.chain(self.calendar_week.events.iter())
355
.find(|event| event.object_id == event_id)
356
.is_none_or(|event| event.source == chatsvc::CalendarSource::Outlook)
357
}
333
358
}
334
359
335
360
#[cfg(test)]
@@ -360,6 +385,7 @@ mod tests {
360
385
show_as: Default::default(),
361
386
dial_in: None,
362
387
response: ResponseType::Accepted,
388
..Default::default()
363
389
}
364
390
}
365
391
@@ -73,7 +73,10 @@ pub struct ReminderUpdate {73
}73
}74
74
75
pub fn subtitle(toast: &MeetingToast, now: DateTime<Utc>, offset: FixedOffset) -> String {75
pub fn subtitle(toast: &MeetingToast, now: DateTime<Utc>, offset: FixedOffset) -> String {76
let clock = toast.start.with_timezone(&offset).format(app_base::format::clock_format());76
let clock = toast77
.start78
.with_timezone(&offset)79
.format(app_base::format::clock_format());77
match toast.phase {80
match toast.phase {78
ReminderPhase::Started => format!("{clock} - started"),81
ReminderPhase::Started => format!("{clock} - started"),79
ReminderPhase::Live => format!("{clock} - live now"),82
ReminderPhase::Live => format!("{clock} - live now"),@@ -268,27 +271,37 @@ impl MeetingToasts {268
}271
}269
}272
}270
273
274
fn reminder_source_events(state: &AppState) -> Vec<CalendarEvent> {275
let mut events = state.calendar_events.clone();276
for event in &state.calendar_week.events {277
if !events278
.iter()279
.any(|existing| existing.object_id == event.object_id)280
{281
events.push(event.clone());282
}283
}284
events285
}286
271
impl AppState {287
impl AppState {272
pub fn tick_meeting_reminders(&mut self, show: bool, cx: &mut Context<Self>) {288
pub fn tick_meeting_reminders(&mut self, show: bool, cx: &mut Context<Self>) {273
let now = Utc::now();289
let now = Utc::now();274
self.poll_outlook_reminders(now, cx);290
self.poll_outlook_reminders(now, cx);275
let in_call = self.call.is_some();291
let in_call = self.call.is_some();276
let show = show && !in_call && !self.mode.read_only;292
let show = show && !in_call && !self.mode.read_only;277
for thread_id in self293
let events = reminder_source_events(self);278
.meeting_toasts294
for thread_id in self.meeting_toasts.live_candidates(&events, now) {279
.live_candidates(&self.calendar_events, now)280
{281
self.fetch_live_meeting(&thread_id, cx);295
self.fetch_live_meeting(&thread_id, cx);282
}296
}283
let live_threads: HashSet<String> = self297
let live_threads: HashSet<String> = events284
.calendar_events285
.iter()298
.iter()286
.filter_map(|event| event.thread_id.clone())299
.filter_map(|event| event.thread_id.clone())287
.filter(|thread_id| self.running_meeting(thread_id).is_some())300
.filter(|thread_id| self.running_meeting(thread_id).is_some())288
.collect();301
.collect();289
let update = self302
let update = self290
.meeting_toasts303
.meeting_toasts291
.update(&self.calendar_events, &live_threads, now, show);304
.update(&events, &live_threads, now, show);292
if (in_call && self.meeting_toasts.clear()) || update.changed {305
if (in_call && self.meeting_toasts.clear()) || update.changed {293
cx.emit(AppEvent::MeetingReminder);306
cx.emit(AppEvent::MeetingReminder);294
cx.notify();307
cx.notify();@@ -317,7 +330,9 @@ impl AppState {317
330
318
pub fn snooze_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {331
pub fn snooze_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {319
if let Some(toast) = self.meeting_toasts.snooze(id) {332
if let Some(toast) = self.meeting_toasts.snooze(id) {320
self.write_outlook_reminder(toast.event_id, ReminderWrite::Snooze(toast.start));333
if self.outlook_reminder_event(&toast.event_id) {334
self.write_outlook_reminder(toast.event_id, ReminderWrite::Snooze(toast.start));335
}321
cx.emit(AppEvent::MeetingReminder);336
cx.emit(AppEvent::MeetingReminder);322
cx.notify();337
cx.notify();323
}338
}@@ -325,11 +340,21 @@ impl AppState {325
340
326
pub fn dismiss_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {341
pub fn dismiss_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {327
if let Some(toast) = self.meeting_toasts.dismiss(id) {342
if let Some(toast) = self.meeting_toasts.dismiss(id) {328
self.write_outlook_reminder(toast.event_id, ReminderWrite::Dismiss);343
if self.outlook_reminder_event(&toast.event_id) {344
self.write_outlook_reminder(toast.event_id, ReminderWrite::Dismiss);345
}329
cx.emit(AppEvent::MeetingReminder);346
cx.emit(AppEvent::MeetingReminder);330
cx.notify();347
cx.notify();331
}348
}332
}349
}350
351
fn outlook_reminder_event(&self, event_id: &str) -> bool {352
self.calendar_events353
.iter()354
.chain(self.calendar_week.events.iter())355
.find(|event| event.object_id == event_id)356
.is_none_or(|event| event.source == chatsvc::CalendarSource::Outlook)357
}333
}358
}334
359
335
#[cfg(test)]360
#[cfg(test)]@@ -360,6 +385,7 @@ mod tests {360
show_as: Default::default(),385
show_as: Default::default(),361
dial_in: None,386
dial_in: None,362
response: ResponseType::Accepted,387
response: ResponseType::Accepted,388
..Default::default()363
}389
}364
}390
}365
391
@@ -12,6 +12,8 @@ const HALF_HOUR_MINUTES: i64 = 30;
12
12
const DEFAULT_LENGTH_MINUTES: i64 = 30;
13
13
const READ_ONLY_MESSAGE: &str = "Meetings cannot be scheduled in read-only mode.";
14
14
const RESPONSE_FAILED_NOTICE: &str = "Could not send your response";
15
const DELETE_FAILED_NOTICE: &str = "Could not delete the meeting";
16
const DELETE_READ_ONLY_NOTICE: &str = "Meetings cannot be deleted in read-only mode.";
15
17
16
18
#[derive(Debug, Clone, PartialEq, Eq)]
17
19
pub struct Invitee {
@@ -129,6 +131,7 @@ fn demo_event(draft: &MeetingDraft, serial: u64) -> CalendarEvent {
129
131
show_as: Default::default(),
130
132
dial_in: None,
131
133
response: ResponseType::Organizer,
134
..Default::default()
132
135
}
133
136
}
134
137
@@ -176,7 +179,11 @@ impl AppState {
176
179
let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));
177
180
return receiver;
178
181
};
179
let created = runtime::spawn(async move { launcher.create_meeting(draft).await });
182
let accounts = store::load_calendar_accounts(&self.store);
183
let store = self.store.clone();
184
let created = runtime::spawn(async move {
185
super::meeting_create::create_across_targets(launcher, draft, accounts, store).await
186
});
180
187
cx.spawn(async move |this, cx| {
181
188
let outcome = created
182
189
.await
@@ -208,6 +215,125 @@ impl AppState {
208
215
self.calls_list.invalidate();
209
216
}
210
217
218
fn remove_calendar_event(&mut self, event_id: &str) -> Option<CalendarEvent> {
219
let mut removed = None;
220
if let Some(index) = self
221
.calendar_week
222
.events
223
.iter()
224
.position(|event| event.object_id == event_id)
225
{
226
removed = Some(self.calendar_week.events.remove(index));
227
}
228
if let Some(index) = self
229
.calendar_events
230
.iter()
231
.position(|event| event.object_id == event_id)
232
{
233
let event = self.calendar_events.remove(index);
234
if removed.is_none() {
235
removed = Some(event);
236
}
237
}
238
self.calls_list.invalidate();
239
removed
240
}
241
242
fn restore_calendar_event(&mut self, event: CalendarEvent) {
243
if !self
244
.calendar_week
245
.events
246
.iter()
247
.any(|existing| existing.object_id == event.object_id)
248
{
249
self.calendar_week.events.push(event.clone());
250
self.calendar_week
251
.events
252
.sort_by_key(|item| (item.start, item.end));
253
}
254
if !self
255
.calendar_events
256
.iter()
257
.any(|existing| existing.object_id == event.object_id)
258
{
259
self.calendar_events.push(event);
260
self.calendar_events
261
.sort_by_key(|item| (item.start, item.end));
262
}
263
self.calls_list.invalidate();
264
}
265
266
pub fn delete_calendar_event(&mut self, event_key: &str, cx: &mut Context<Self>) {
267
if self.mode.read_only {
268
self.raise_notice(DELETE_READ_ONLY_NOTICE.to_owned(), None, cx);
269
return;
270
}
271
let Some(event) = self
272
.calendar_events
273
.iter()
274
.chain(&self.calendar_week.events)
275
.find(|event| event.object_id == event_key)
276
.cloned()
277
else {
278
return;
279
};
280
let snapshot = event.clone();
281
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
282
let source = event.source;
283
let account_id = event.account_id.clone();
284
let calendar_id = event.calendar_id.clone();
285
self.remove_calendar_event(&event_id);
286
cx.notify();
287
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
288
let Some(launcher) = launcher else {
289
return;
290
};
291
let send_updates = self.rsvp_send_response;
292
let store = self.store.clone();
293
let deleted = runtime::spawn({
294
let event_id = event_id.clone();
295
async move {
296
match source {
297
chatsvc::CalendarSource::Outlook => {
298
launcher
299
.delete_calendar_event(&event_id, ical_uid.as_deref())
300
.await
301
}
302
chatsvc::CalendarSource::Google => {
303
let mut accounts = store::load_calendar_accounts(&store);
304
let account =
305
account_id.ok_or_else(|| "Google account missing".to_owned())?;
306
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
307
let result = crate::google_calendar_sync::delete_google_event(
308
&mut accounts,
309
&account,
310
&calendar,
311
&event_id,
312
send_updates,
313
)
314
.await;
315
let _ = store::save_calendar_accounts(&store, &accounts);
316
result
317
}
318
}
319
}
320
});
321
cx.spawn(async move |this, cx| {
322
let ok = deleted.await.is_ok_and(|result| result.is_ok());
323
this.update(cx, |state, cx| {
324
if ok {
325
// refresh_calendar nudges agenda poll + reloads the week grid.
326
state.refresh_calendar(cx);
327
return;
328
}
329
state.restore_calendar_event(snapshot);
330
state.raise_notice(DELETE_FAILED_NOTICE.to_owned(), None, cx);
331
})
332
.ok();
333
})
334
.detach();
335
}
336
211
337
pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {
212
338
if self.mode.read_only {
213
339
self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
@@ -223,6 +349,9 @@ impl AppState {
223
349
};
224
350
let previous = event.response;
225
351
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
352
let source = event.source;
353
let account_id = event.account_id.clone();
354
let calendar_id = event.calendar_id.clone();
226
355
self.set_event_response(&event_id, response_for(reply));
227
356
cx.notify();
228
357
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
@@ -230,12 +359,34 @@ impl AppState {
230
359
return;
231
360
};
232
361
let send_response = self.rsvp_send_response;
362
let store = self.store.clone();
233
363
let answered = runtime::spawn({
234
364
let event_id = event_id.clone();
235
365
async move {
236
launcher
237
.respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
238
.await
366
match source {
367
chatsvc::CalendarSource::Outlook => {
368
launcher
369
.respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
370
.await
371
}
372
chatsvc::CalendarSource::Google => {
373
let mut accounts = store::load_calendar_accounts(&store);
374
let account =
375
account_id.ok_or_else(|| "Google account missing".to_owned())?;
376
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
377
let result = crate::google_calendar_sync::respond_google_event(
378
&mut accounts,
379
&account,
380
&calendar,
381
&event_id,
382
reply,
383
send_response,
384
)
385
.await;
386
let _ = store::save_calendar_accounts(&store, &accounts);
387
result
388
}
389
}
239
390
}
240
391
});
241
392
cx.spawn(async move |this, cx| {
@@ -12,6 +12,8 @@ const HALF_HOUR_MINUTES: i64 = 30;12
const DEFAULT_LENGTH_MINUTES: i64 = 30;12
const DEFAULT_LENGTH_MINUTES: i64 = 30;13
const READ_ONLY_MESSAGE: &str = "Meetings cannot be scheduled in read-only mode.";13
const READ_ONLY_MESSAGE: &str = "Meetings cannot be scheduled in read-only mode.";14
const RESPONSE_FAILED_NOTICE: &str = "Could not send your response";14
const RESPONSE_FAILED_NOTICE: &str = "Could not send your response";15
const DELETE_FAILED_NOTICE: &str = "Could not delete the meeting";16
const DELETE_READ_ONLY_NOTICE: &str = "Meetings cannot be deleted in read-only mode.";15
17
16
#[derive(Debug, Clone, PartialEq, Eq)]18
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct Invitee {19
pub struct Invitee {@@ -129,6 +131,7 @@ fn demo_event(draft: &MeetingDraft, serial: u64) -> CalendarEvent {129
show_as: Default::default(),131
show_as: Default::default(),130
dial_in: None,132
dial_in: None,131
response: ResponseType::Organizer,133
response: ResponseType::Organizer,134
..Default::default()132
}135
}133
}136
}134
137
@@ -176,7 +179,11 @@ impl AppState {176
let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));179
let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));177
return receiver;180
return receiver;178
};181
};179
let created = runtime::spawn(async move { launcher.create_meeting(draft).await });182
let accounts = store::load_calendar_accounts(&self.store);183
let store = self.store.clone();184
let created = runtime::spawn(async move {185
super::meeting_create::create_across_targets(launcher, draft, accounts, store).await186
});180
cx.spawn(async move |this, cx| {187
cx.spawn(async move |this, cx| {181
let outcome = created188
let outcome = created182
.await189
.await@@ -208,6 +215,125 @@ impl AppState {208
self.calls_list.invalidate();215
self.calls_list.invalidate();209
}216
}210
217
218
fn remove_calendar_event(&mut self, event_id: &str) -> Option<CalendarEvent> {219
let mut removed = None;220
if let Some(index) = self221
.calendar_week222
.events223
.iter()224
.position(|event| event.object_id == event_id)225
{226
removed = Some(self.calendar_week.events.remove(index));227
}228
if let Some(index) = self229
.calendar_events230
.iter()231
.position(|event| event.object_id == event_id)232
{233
let event = self.calendar_events.remove(index);234
if removed.is_none() {235
removed = Some(event);236
}237
}238
self.calls_list.invalidate();239
removed240
}241
242
fn restore_calendar_event(&mut self, event: CalendarEvent) {243
if !self244
.calendar_week245
.events246
.iter()247
.any(|existing| existing.object_id == event.object_id)248
{249
self.calendar_week.events.push(event.clone());250
self.calendar_week251
.events252
.sort_by_key(|item| (item.start, item.end));253
}254
if !self255
.calendar_events256
.iter()257
.any(|existing| existing.object_id == event.object_id)258
{259
self.calendar_events.push(event);260
self.calendar_events261
.sort_by_key(|item| (item.start, item.end));262
}263
self.calls_list.invalidate();264
}265
266
pub fn delete_calendar_event(&mut self, event_key: &str, cx: &mut Context<Self>) {267
if self.mode.read_only {268
self.raise_notice(DELETE_READ_ONLY_NOTICE.to_owned(), None, cx);269
return;270
}271
let Some(event) = self272
.calendar_events273
.iter()274
.chain(&self.calendar_week.events)275
.find(|event| event.object_id == event_key)276
.cloned()277
else {278
return;279
};280
let snapshot = event.clone();281
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());282
let source = event.source;283
let account_id = event.account_id.clone();284
let calendar_id = event.calendar_id.clone();285
self.remove_calendar_event(&event_id);286
cx.notify();287
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);288
let Some(launcher) = launcher else {289
return;290
};291
let send_updates = self.rsvp_send_response;292
let store = self.store.clone();293
let deleted = runtime::spawn({294
let event_id = event_id.clone();295
async move {296
match source {297
chatsvc::CalendarSource::Outlook => {298
launcher299
.delete_calendar_event(&event_id, ical_uid.as_deref())300
.await301
}302
chatsvc::CalendarSource::Google => {303
let mut accounts = store::load_calendar_accounts(&store);304
let account =305
account_id.ok_or_else(|| "Google account missing".to_owned())?;306
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());307
let result = crate::google_calendar_sync::delete_google_event(308
&mut accounts,309
&account,310
&calendar,311
&event_id,312
send_updates,313
)314
.await;315
let _ = store::save_calendar_accounts(&store, &accounts);316
result317
}318
}319
}320
});321
cx.spawn(async move |this, cx| {322
let ok = deleted.await.is_ok_and(|result| result.is_ok());323
this.update(cx, |state, cx| {324
if ok {325
// refresh_calendar nudges agenda poll + reloads the week grid.326
state.refresh_calendar(cx);327
return;328
}329
state.restore_calendar_event(snapshot);330
state.raise_notice(DELETE_FAILED_NOTICE.to_owned(), None, cx);331
})332
.ok();333
})334
.detach();335
}336
211
pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {337
pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {212
if self.mode.read_only {338
if self.mode.read_only {213
self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);339
self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);@@ -223,6 +349,9 @@ impl AppState {223
};349
};224
let previous = event.response;350
let previous = event.response;225
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());351
let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());352
let source = event.source;353
let account_id = event.account_id.clone();354
let calendar_id = event.calendar_id.clone();226
self.set_event_response(&event_id, response_for(reply));355
self.set_event_response(&event_id, response_for(reply));227
cx.notify();356
cx.notify();228
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);357
let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);@@ -230,12 +359,34 @@ impl AppState {230
return;359
return;231
};360
};232
let send_response = self.rsvp_send_response;361
let send_response = self.rsvp_send_response;362
let store = self.store.clone();233
let answered = runtime::spawn({363
let answered = runtime::spawn({234
let event_id = event_id.clone();364
let event_id = event_id.clone();235
async move {365
async move {236
launcher366
match source {237
.respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)367
chatsvc::CalendarSource::Outlook => {238
.await368
launcher369
.respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)370
.await371
}372
chatsvc::CalendarSource::Google => {373
let mut accounts = store::load_calendar_accounts(&store);374
let account =375
account_id.ok_or_else(|| "Google account missing".to_owned())?;376
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());377
let result = crate::google_calendar_sync::respond_google_event(378
&mut accounts,379
&account,380
&calendar,381
&event_id,382
reply,383
send_response,384
)385
.await;386
let _ = store::save_calendar_accounts(&store, &accounts);387
result388
}389
}239
}390
}240
});391
});241
cx.spawn(async move |this, cx| {392
cx.spawn(async move |this, cx| {@@ -27,6 +27,7 @@ impl AppState {
27
27
28
28
pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
29
29
self.calendar_week.start = Some(self.calendar_start());
30
self.request_calendar_scroll_to_now(cx);
30
31
self.load_calendar_week(cx);
31
32
}
32
33
@@ -41,6 +42,14 @@ impl AppState {
41
42
self.open_calendar(cx);
42
43
}
43
44
45
pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) {
46
if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) {
47
return;
48
}
49
self.calendar_scroll_to_now = self.calendar_scroll_to_now.wrapping_add(1);
50
cx.notify();
51
}
52
44
53
pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
45
54
let today = Local::now().date_naive();
46
55
let start = self.calendar_start();
@@ -48,6 +57,9 @@ impl AppState {
48
57
start <= today && today < start + Duration::days(self.calendar_week.span.days());
49
58
self.calendar_week.span = span;
50
59
self.calendar_week.start = Some(span.start_for(if shown { today } else { start }));
60
if crate::call::calendar_now::shows_hour_grid(span) {
61
self.request_calendar_scroll_to_now(cx);
62
}
51
63
self.load_calendar_week(cx);
52
64
}
53
65
@@ -61,7 +73,7 @@ impl AppState {
61
73
self.show_calendar_date(date, cx);
62
74
}
63
75
64
fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
76
pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
65
77
let start = self.calendar_start();
66
78
let offset = Local::now().offset().fix();
67
79
let (from, to) = week_range(start, self.calendar_week.span.days(), offset);
@@ -82,17 +94,48 @@ impl AppState {
82
94
let request = self.calendar_week.request;
83
95
self.calendar_week.loading = true;
84
96
cx.notify();
85
let receiver = crate::runtime::spawn(async move { launcher.calendar_view(from, to).await });
97
let store = self.store.clone();
98
let receiver = crate::runtime::spawn(async move {
99
let mut accounts = store::load_calendar_accounts(&store);
100
let mut combined = Vec::new();
101
let mut outlook_failed = false;
102
if accounts.outlook_selected {
103
match launcher.calendar_view(from, to).await {
104
Ok(events) => combined.extend(events),
105
Err(error) => {
106
outlook_failed = true;
107
crate::diagnostics::record(format!(
108
"calls: outlook calendar week not loaded: {error}"
109
));
110
}
111
}
112
}
113
match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {
114
Ok(events) => {
115
let _ = store::save_calendar_accounts(&store, &accounts);
116
combined.extend(events);
117
}
118
Err(error) => crate::diagnostics::record(format!(
119
"calls: google calendar week not loaded: {error}"
120
)),
121
}
122
if combined.is_empty() && outlook_failed && !accounts.has_google() {
123
return Err(CALENDAR_LOAD_FAILURE.to_owned());
124
}
125
Ok(chatsvc::merge_calendar_events(combined))
126
});
86
127
cx.spawn(async move |this, cx| {
87
let loaded = receiver.await.ok().and_then(Result::ok);
128
let loaded = receiver
129
.await
130
.unwrap_or_else(|_| Err(CALENDAR_LOAD_FAILURE.to_owned()));
88
131
this.update(cx, |state, cx| {
89
132
if state.calendar_week.request != request {
90
133
return;
91
134
}
92
135
state.calendar_week.loading = false;
93
136
match loaded {
94
Some(events) => state.calendar_week.events = events,
95
None => state.raise_notice(CALENDAR_LOAD_FAILURE.to_owned(), None, cx),
137
Ok(events) => state.calendar_week.events = events,
138
Err(notice) => state.raise_notice(notice, None, cx),
96
139
}
97
140
cx.notify();
98
141
})
@@ -201,6 +244,7 @@ fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
201
244
show_as: demo_show_as(subject, *response),
202
245
dial_in: None,
203
246
response: *response,
247
..Default::default()
204
248
}
205
249
})
206
250
.collect()
@@ -27,6 +27,7 @@ impl AppState {27
27
28
pub fn open_calendar(&mut self, cx: &mut Context<Self>) {28
pub fn open_calendar(&mut self, cx: &mut Context<Self>) {29
self.calendar_week.start = Some(self.calendar_start());29
self.calendar_week.start = Some(self.calendar_start());30
self.request_calendar_scroll_to_now(cx);30
self.load_calendar_week(cx);31
self.load_calendar_week(cx);31
}32
}32
33
@@ -41,6 +42,14 @@ impl AppState {41
self.open_calendar(cx);42
self.open_calendar(cx);42
}43
}43
44
45
pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) {46
if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) {47
return;48
}49
self.calendar_scroll_to_now = self.calendar_scroll_to_now.wrapping_add(1);50
cx.notify();51
}52
44
pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {53
pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {45
let today = Local::now().date_naive();54
let today = Local::now().date_naive();46
let start = self.calendar_start();55
let start = self.calendar_start();@@ -48,6 +57,9 @@ impl AppState {48
start <= today && today < start + Duration::days(self.calendar_week.span.days());57
start <= today && today < start + Duration::days(self.calendar_week.span.days());49
self.calendar_week.span = span;58
self.calendar_week.span = span;50
self.calendar_week.start = Some(span.start_for(if shown { today } else { start }));59
self.calendar_week.start = Some(span.start_for(if shown { today } else { start }));60
if crate::call::calendar_now::shows_hour_grid(span) {61
self.request_calendar_scroll_to_now(cx);62
}51
self.load_calendar_week(cx);63
self.load_calendar_week(cx);52
}64
}53
65
@@ -61,7 +73,7 @@ impl AppState {61
self.show_calendar_date(date, cx);73
self.show_calendar_date(date, cx);62
}74
}63
75
64
fn load_calendar_week(&mut self, cx: &mut Context<Self>) {76
pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {65
let start = self.calendar_start();77
let start = self.calendar_start();66
let offset = Local::now().offset().fix();78
let offset = Local::now().offset().fix();67
let (from, to) = week_range(start, self.calendar_week.span.days(), offset);79
let (from, to) = week_range(start, self.calendar_week.span.days(), offset);@@ -82,17 +94,48 @@ impl AppState {82
let request = self.calendar_week.request;94
let request = self.calendar_week.request;83
self.calendar_week.loading = true;95
self.calendar_week.loading = true;84
cx.notify();96
cx.notify();85
let receiver = crate::runtime::spawn(async move { launcher.calendar_view(from, to).await });97
let store = self.store.clone();98
let receiver = crate::runtime::spawn(async move {99
let mut accounts = store::load_calendar_accounts(&store);100
let mut combined = Vec::new();101
let mut outlook_failed = false;102
if accounts.outlook_selected {103
match launcher.calendar_view(from, to).await {104
Ok(events) => combined.extend(events),105
Err(error) => {106
outlook_failed = true;107
crate::diagnostics::record(format!(108
"calls: outlook calendar week not loaded: {error}"109
));110
}111
}112
}113
match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {114
Ok(events) => {115
let _ = store::save_calendar_accounts(&store, &accounts);116
combined.extend(events);117
}118
Err(error) => crate::diagnostics::record(format!(119
"calls: google calendar week not loaded: {error}"120
)),121
}122
if combined.is_empty() && outlook_failed && !accounts.has_google() {123
return Err(CALENDAR_LOAD_FAILURE.to_owned());124
}125
Ok(chatsvc::merge_calendar_events(combined))126
});86
cx.spawn(async move |this, cx| {127
cx.spawn(async move |this, cx| {87
let loaded = receiver.await.ok().and_then(Result::ok);128
let loaded = receiver129
.await130
.unwrap_or_else(|_| Err(CALENDAR_LOAD_FAILURE.to_owned()));88
this.update(cx, |state, cx| {131
this.update(cx, |state, cx| {89
if state.calendar_week.request != request {132
if state.calendar_week.request != request {90
return;133
return;91
}134
}92
state.calendar_week.loading = false;135
state.calendar_week.loading = false;93
match loaded {136
match loaded {94
Some(events) => state.calendar_week.events = events,137
Ok(events) => state.calendar_week.events = events,95
None => state.raise_notice(CALENDAR_LOAD_FAILURE.to_owned(), None, cx),138
Err(notice) => state.raise_notice(notice, None, cx),96
}139
}97
cx.notify();140
cx.notify();98
})141
})@@ -201,6 +244,7 @@ fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {201
show_as: demo_show_as(subject, *response),244
show_as: demo_show_as(subject, *response),202
dial_in: None,245
dial_in: None,203
response: *response,246
response: *response,247
..Default::default()204
}248
}205
})249
})206
.collect()250
.collect()@@ -0,0 +1,165 @@
1
use chrono::{DateTime, Utc};
2
use store::{CalendarAccounts, GoogleTokenSet};
3
4
use chatsvc::{
5
CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, client_id_from_env,
6
google_rsvp_status, refresh_access_token,
7
};
8
9
/// Refresh tokens when needed and load events from every selected Google calendar.
10
pub async fn fetch_google_events(
11
accounts: &mut CalendarAccounts,
12
start: DateTime<Utc>,
13
end: DateTime<Utc>,
14
) -> Result<Vec<CalendarEvent>, String> {
15
let Some(oauth) = client_id_from_env() else {
16
return Ok(Vec::new());
17
};
18
let mut all = Vec::new();
19
for index in 0..accounts.google_accounts.len() {
20
if !ensure_access_token(accounts, index, &oauth).await? {
21
continue;
22
}
23
let account = &accounts.google_accounts[index];
24
let access = account.tokens.access_token.clone();
25
let account_id = account.id.clone();
26
let calendars: Vec<_> = account
27
.calendars
28
.iter()
29
.filter(|calendar| calendar.selected)
30
.map(|calendar| calendar.id.clone())
31
.collect();
32
let calendars = if calendars.is_empty() {
33
vec!["primary".to_owned()]
34
} else {
35
calendars
36
};
37
let client = GoogleCalendar::new(access);
38
for calendar_id in calendars {
39
match client.events(&calendar_id, start, end).await {
40
Ok(mut events) => {
41
for event in &mut events {
42
event.account_id = Some(account_id.clone());
43
event.calendar_id = Some(calendar_id.clone());
44
}
45
all.extend(events);
46
}
47
Err(error) => crate::diagnostics::record(format!(
48
"calls: google calendar {calendar_id} not loaded: {error}"
49
)),
50
}
51
}
52
}
53
Ok(all)
54
}
55
56
pub async fn insert_google_event(
57
accounts: &mut CalendarAccounts,
58
account_id: &str,
59
calendar_id: &str,
60
draft: &GoogleEventDraft,
61
) -> Result<(), String> {
62
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
63
let index = accounts
64
.google_accounts
65
.iter()
66
.position(|account| account.id == account_id)
67
.ok_or_else(|| format!("Google account {account_id} missing"))?;
68
if !ensure_access_token(accounts, index, &oauth).await? {
69
return Err("Google access token missing".into());
70
}
71
let access = accounts.google_accounts[index].tokens.access_token.clone();
72
GoogleCalendar::new(access)
73
.insert_event(calendar_id, draft)
74
.await
75
.map(|_| ())
76
.map_err(|error| error.to_string())
77
}
78
79
pub async fn respond_google_event(
80
accounts: &mut CalendarAccounts,
81
account_id: &str,
82
calendar_id: &str,
83
event_id: &str,
84
reply: Reply,
85
send_updates: bool,
86
) -> Result<(), String> {
87
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
88
let index = accounts
89
.google_accounts
90
.iter()
91
.position(|account| account.id == account_id)
92
.ok_or_else(|| format!("Google account {account_id} missing"))?;
93
if !ensure_access_token(accounts, index, &oauth).await? {
94
return Err("Google access token missing".into());
95
}
96
let access = accounts.google_accounts[index].tokens.access_token.clone();
97
GoogleCalendar::new(access)
98
.respond(
99
calendar_id,
100
event_id,
101
google_rsvp_status(reply),
102
send_updates,
103
)
104
.await
105
.map_err(|error| error.to_string())
106
}
107
108
pub async fn delete_google_event(
109
accounts: &mut CalendarAccounts,
110
account_id: &str,
111
calendar_id: &str,
112
event_id: &str,
113
send_updates: bool,
114
) -> Result<(), String> {
115
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
116
let index = accounts
117
.google_accounts
118
.iter()
119
.position(|account| account.id == account_id)
120
.ok_or_else(|| format!("Google account {account_id} missing"))?;
121
if !ensure_access_token(accounts, index, &oauth).await? {
122
return Err("Google access token missing".into());
123
}
124
let access = accounts.google_accounts[index].tokens.access_token.clone();
125
GoogleCalendar::new(access)
126
.delete_event(calendar_id, event_id, send_updates)
127
.await
128
.map_err(|error| error.to_string())
129
}
130
131
async fn ensure_access_token(
132
accounts: &mut CalendarAccounts,
133
index: usize,
134
oauth: &GoogleOAuth,
135
) -> Result<bool, String> {
136
let now = Utc::now().timestamp();
137
let account = &mut accounts.google_accounts[index];
138
if account.tokens.refresh_token.is_empty() && account.tokens.access_token.is_empty() {
139
return Ok(false);
140
}
141
if account.tokens.expires_at <= now + 60 && !account.tokens.refresh_token.is_empty() {
142
match refresh_access_token(oauth, &account.tokens.refresh_token).await {
143
Ok(bundle) => {
144
account.tokens = GoogleTokenSet {
145
access_token: bundle.access_token,
146
refresh_token: if bundle.refresh_token.is_empty() {
147
account.tokens.refresh_token.clone()
148
} else {
149
bundle.refresh_token
150
},
151
expires_at: now + bundle.expires_in.max(60),
152
};
153
}
154
Err(error) => {
155
crate::diagnostics::record(format!("calls: google token refresh failed: {error}"));
156
return Ok(false);
157
}
158
}
159
}
160
Ok(!account.tokens.access_token.is_empty())
161
}
162
163
fn missing_client_id() -> String {
164
"Set TEAMS_GOOGLE_CLIENT_ID to connect Google Calendar".into()
165
}
@@ -0,0 +1,165 @@1
use chrono::{DateTime, Utc};2
use store::{CalendarAccounts, GoogleTokenSet};3
4
use chatsvc::{5
CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, client_id_from_env,6
google_rsvp_status, refresh_access_token,7
};8
9
/// Refresh tokens when needed and load events from every selected Google calendar.10
pub async fn fetch_google_events(11
accounts: &mut CalendarAccounts,12
start: DateTime<Utc>,13
end: DateTime<Utc>,14
) -> Result<Vec<CalendarEvent>, String> {15
let Some(oauth) = client_id_from_env() else {16
return Ok(Vec::new());17
};18
let mut all = Vec::new();19
for index in 0..accounts.google_accounts.len() {20
if !ensure_access_token(accounts, index, &oauth).await? {21
continue;22
}23
let account = &accounts.google_accounts[index];24
let access = account.tokens.access_token.clone();25
let account_id = account.id.clone();26
let calendars: Vec<_> = account27
.calendars28
.iter()29
.filter(|calendar| calendar.selected)30
.map(|calendar| calendar.id.clone())31
.collect();32
let calendars = if calendars.is_empty() {33
vec!["primary".to_owned()]34
} else {35
calendars36
};37
let client = GoogleCalendar::new(access);38
for calendar_id in calendars {39
match client.events(&calendar_id, start, end).await {40
Ok(mut events) => {41
for event in &mut events {42
event.account_id = Some(account_id.clone());43
event.calendar_id = Some(calendar_id.clone());44
}45
all.extend(events);46
}47
Err(error) => crate::diagnostics::record(format!(48
"calls: google calendar {calendar_id} not loaded: {error}"49
)),50
}51
}52
}53
Ok(all)54
}55
56
pub async fn insert_google_event(57
accounts: &mut CalendarAccounts,58
account_id: &str,59
calendar_id: &str,60
draft: &GoogleEventDraft,61
) -> Result<(), String> {62
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;63
let index = accounts64
.google_accounts65
.iter()66
.position(|account| account.id == account_id)67
.ok_or_else(|| format!("Google account {account_id} missing"))?;68
if !ensure_access_token(accounts, index, &oauth).await? {69
return Err("Google access token missing".into());70
}71
let access = accounts.google_accounts[index].tokens.access_token.clone();72
GoogleCalendar::new(access)73
.insert_event(calendar_id, draft)74
.await75
.map(|_| ())76
.map_err(|error| error.to_string())77
}78
79
pub async fn respond_google_event(80
accounts: &mut CalendarAccounts,81
account_id: &str,82
calendar_id: &str,83
event_id: &str,84
reply: Reply,85
send_updates: bool,86
) -> Result<(), String> {87
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;88
let index = accounts89
.google_accounts90
.iter()91
.position(|account| account.id == account_id)92
.ok_or_else(|| format!("Google account {account_id} missing"))?;93
if !ensure_access_token(accounts, index, &oauth).await? {94
return Err("Google access token missing".into());95
}96
let access = accounts.google_accounts[index].tokens.access_token.clone();97
GoogleCalendar::new(access)98
.respond(99
calendar_id,100
event_id,101
google_rsvp_status(reply),102
send_updates,103
)104
.await105
.map_err(|error| error.to_string())106
}107
108
pub async fn delete_google_event(109
accounts: &mut CalendarAccounts,110
account_id: &str,111
calendar_id: &str,112
event_id: &str,113
send_updates: bool,114
) -> Result<(), String> {115
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;116
let index = accounts117
.google_accounts118
.iter()119
.position(|account| account.id == account_id)120
.ok_or_else(|| format!("Google account {account_id} missing"))?;121
if !ensure_access_token(accounts, index, &oauth).await? {122
return Err("Google access token missing".into());123
}124
let access = accounts.google_accounts[index].tokens.access_token.clone();125
GoogleCalendar::new(access)126
.delete_event(calendar_id, event_id, send_updates)127
.await128
.map_err(|error| error.to_string())129
}130
131
async fn ensure_access_token(132
accounts: &mut CalendarAccounts,133
index: usize,134
oauth: &GoogleOAuth,135
) -> Result<bool, String> {136
let now = Utc::now().timestamp();137
let account = &mut accounts.google_accounts[index];138
if account.tokens.refresh_token.is_empty() && account.tokens.access_token.is_empty() {139
return Ok(false);140
}141
if account.tokens.expires_at <= now + 60 && !account.tokens.refresh_token.is_empty() {142
match refresh_access_token(oauth, &account.tokens.refresh_token).await {143
Ok(bundle) => {144
account.tokens = GoogleTokenSet {145
access_token: bundle.access_token,146
refresh_token: if bundle.refresh_token.is_empty() {147
account.tokens.refresh_token.clone()148
} else {149
bundle.refresh_token150
},151
expires_at: now + bundle.expires_in.max(60),152
};153
}154
Err(error) => {155
crate::diagnostics::record(format!("calls: google token refresh failed: {error}"));156
return Ok(false);157
}158
}159
}160
Ok(!account.tokens.access_token.is_empty())161
}162
163
fn missing_client_id() -> String {164
"Set TEAMS_GOOGLE_CLIENT_ID to connect Google Calendar".into()165
}@@ -1,22 +1,20 @@
1
1
pub mod activity;
2
pub mod banner_image;
3
2
pub mod agent_api;
4
3
pub mod agents;
5
4
pub mod app_state;
6
5
pub mod backend;
6
pub mod banner_image;
7
pub mod calendar_accounts_actions;
7
8
pub mod call;
8
9
pub mod call_rows;
9
10
pub mod card_actions;
10
11
pub mod card_inputs;
11
12
pub mod card_refresh;
12
13
pub mod card_state;
14
pub mod channel_filter;
13
15
pub mod channel_menu;
14
16
pub mod chat_actions;
15
mod sidebar_load;
16
pub mod channel_filter;
17
17
pub mod chat_filter;
18
pub mod find_in_chat;
19
pub mod forward_selection;
20
18
pub mod chat_members;
21
19
pub mod chat_settings_actions;
22
20
pub mod connection_banner;
@@ -27,7 +25,10 @@ pub mod demo;
27
25
pub mod demo_meetings;
28
26
pub mod demo_profiles;
29
27
pub mod emoji;
28
pub mod find_in_chat;
29
pub mod forward_selection;
30
30
pub mod gifs;
31
pub mod google_calendar_sync;
31
32
pub mod image_view_gallery;
32
33
pub mod importance;
33
34
pub mod local_previews;
@@ -38,11 +39,11 @@ pub mod notify;
38
39
pub mod outbox;
39
40
pub mod outgoing;
40
41
pub mod own_status;
41
pub mod presence_follow;
42
42
pub mod absence_notice;
43
43
pub mod pending_rows;
44
44
pub mod people;
45
45
pub mod post_follow;
46
pub mod presence_follow;
46
47
pub mod profile_model;
47
48
pub mod profile_state;
48
49
pub mod reaction_model;
@@ -53,6 +54,7 @@ pub mod scheduled_rows;
53
54
pub mod section_actions;
54
55
pub mod settings_section;
55
56
pub mod share_outlook;
57
mod sidebar_load;
56
58
pub mod sidebar_model;
57
59
pub mod sound_actions;
58
60
pub mod stored_outgoing;
@@ -63,10 +65,11 @@ pub mod typing;
63
65
mod warm_chats;
64
66
pub mod urgent_ack;
65
67
66
pub use app_ui_kit::render;
67
68
pub use app_base::{
68
APP_NAME, appearance, autostart, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
69
demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
70
emoticons, image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
71
single_instance, stickers, theme, translation, updater, user_activity, zoom,
69
APP_NAME, appearance, autostart, avatar_image, channel_files, crash_log, demo_cards,
70
demo_chart_cards, demo_gifs, demo_input_cards, demo_library, demo_recap, diagnostics,
71
downloads, emoticons, format, frame_log, fuzzy, image_clipboard, image_view_math, inline_image,
72
presence_link, read_state, recap, remote_image, runtime, schedule_time, single_instance,
73
stickers, theme, translation, updater, user_activity, zoom,
72
74
};
75
pub use app_ui_kit::render;
@@ -1,22 +1,20 @@1
pub mod activity;1
pub mod activity;2
pub mod banner_image;3
pub mod agent_api;2
pub mod agent_api;4
pub mod agents;3
pub mod agents;5
pub mod app_state;4
pub mod app_state;6
pub mod backend;5
pub mod backend;6
pub mod banner_image;7
pub mod calendar_accounts_actions;7
pub mod call;8
pub mod call;8
pub mod call_rows;9
pub mod call_rows;9
pub mod card_actions;10
pub mod card_actions;10
pub mod card_inputs;11
pub mod card_inputs;11
pub mod card_refresh;12
pub mod card_refresh;12
pub mod card_state;13
pub mod card_state;14
pub mod channel_filter;13
pub mod channel_menu;15
pub mod channel_menu;14
pub mod chat_actions;16
pub mod chat_actions;15
mod sidebar_load;16
pub mod channel_filter;17
pub mod chat_filter;17
pub mod chat_filter;18
pub mod find_in_chat;19
pub mod forward_selection;20
pub mod chat_members;18
pub mod chat_members;21
pub mod chat_settings_actions;19
pub mod chat_settings_actions;22
pub mod connection_banner;20
pub mod connection_banner;@@ -27,7 +25,10 @@ pub mod demo;27
pub mod demo_meetings;25
pub mod demo_meetings;28
pub mod demo_profiles;26
pub mod demo_profiles;29
pub mod emoji;27
pub mod emoji;28
pub mod find_in_chat;29
pub mod forward_selection;30
pub mod gifs;30
pub mod gifs;31
pub mod google_calendar_sync;31
pub mod image_view_gallery;32
pub mod image_view_gallery;32
pub mod importance;33
pub mod importance;33
pub mod local_previews;34
pub mod local_previews;@@ -38,11 +39,11 @@ pub mod notify;38
pub mod outbox;39
pub mod outbox;39
pub mod outgoing;40
pub mod outgoing;40
pub mod own_status;41
pub mod own_status;41
pub mod presence_follow;42
pub mod absence_notice;42
pub mod absence_notice;43
pub mod pending_rows;43
pub mod pending_rows;44
pub mod people;44
pub mod people;45
pub mod post_follow;45
pub mod post_follow;46
pub mod presence_follow;46
pub mod profile_model;47
pub mod profile_model;47
pub mod profile_state;48
pub mod profile_state;48
pub mod reaction_model;49
pub mod reaction_model;@@ -53,6 +54,7 @@ pub mod scheduled_rows;53
pub mod section_actions;54
pub mod section_actions;54
pub mod settings_section;55
pub mod settings_section;55
pub mod share_outlook;56
pub mod share_outlook;57
mod sidebar_load;56
pub mod sidebar_model;58
pub mod sidebar_model;57
pub mod sound_actions;59
pub mod sound_actions;58
pub mod stored_outgoing;60
pub mod stored_outgoing;@@ -63,10 +65,11 @@ pub mod typing;63
mod warm_chats;65
mod warm_chats;64
pub mod urgent_ack;66
pub mod urgent_ack;65
67
66
pub use app_ui_kit::render;67
pub use app_base::{68
pub use app_base::{68
APP_NAME, appearance, autostart, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,69
APP_NAME, appearance, autostart, avatar_image, channel_files, crash_log, demo_cards,69
demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,70
demo_chart_cards, demo_gifs, demo_input_cards, demo_library, demo_recap, diagnostics,70
emoticons, image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,71
downloads, emoticons, format, frame_log, fuzzy, image_clipboard, image_view_math, inline_image,71
single_instance, stickers, theme, translation, updater, user_activity, zoom,72
presence_link, read_state, recap, remote_image, runtime, schedule_time, single_instance,73
stickers, theme, translation, updater, user_activity, zoom,72
};74
};75
pub use app_ui_kit::render;@@ -9,6 +9,7 @@ pub enum SettingsSection {
9
9
Appearance,
10
10
Chats,
11
11
Calls,
12
Calendar,
12
13
Devices,
13
14
Agents,
14
15
Mcp,
@@ -9,6 +9,7 @@ pub enum SettingsSection {9
Appearance,9
Appearance,10
Chats,10
Chats,11
Calls,11
Calls,12
Calendar,12
Devices,13
Devices,13
Agents,14
Agents,14
Mcp,15
Mcp,@@ -0,0 +1,180 @@
1
use gpui_kit::component::v_flex;
2
use gpui_kit::*;
3
use store::{CalendarProvider, CalendarRef};
4
5
use super::rows::{caption, control_row, text_button, toggle_row};
6
use crate::app_state::AppState;
7
use crate::theme;
8
9
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
10
let accounts = app.read(cx).calendar_accounts();
11
let mut body = v_flex()
12
.w_full()
13
.child(caption("GOOGLE"))
14
.child(connect_row(app, accounts.has_google()));
15
for account in &accounts.google_accounts {
16
body = body.child(account_block(app, account, &accounts));
17
}
18
body = body
19
.child(caption("HOME CALENDAR"))
20
.child(home_choices(app, &accounts))
21
.child(caption("ALSO WRITE TO"));
22
if accounts.home.provider != CalendarProvider::Outlook {
23
let write_app = app.clone();
24
let target = CalendarRef::outlook();
25
let selected = accounts
26
.write_targets
27
.iter()
28
.any(|existing| existing.key() == target.key());
29
body = body.child(
30
toggle_row(
31
"settings-write-outlook",
32
"Outlook (Microsoft mailbox)",
33
"Dual-write when home is Google",
34
theme::text_muted(),
35
selected,
36
)
37
.on_click(move |_, _, cx| {
38
write_app.update(cx, |state, cx| {
39
state.toggle_write_target(target.clone(), cx)
40
})
41
}),
42
);
43
} else if accounts.google_accounts.is_empty() {
44
body = body.child(control_row(
45
"No extra write targets",
46
"Connect Google, then enable dual-write on a calendar above.",
47
div(),
48
));
49
}
50
body
51
}
52
53
fn connect_row(app: &Entity<AppState>, connected: bool) -> Div {
54
let app = app.clone();
55
if connected {
56
control_row(
57
"Google Calendar",
58
"Connected accounts appear below. Disconnect removes tokens from this device.",
59
div(),
60
)
61
} else {
62
control_row(
63
"Google Calendar",
64
"Requires TEAMS_GOOGLE_CLIENT_ID. Opens a browser for sign-in.",
65
text_button("settings-google-connect", "Connect Google").on_click(move |_, _, cx| {
66
app.update(cx, |state, cx| state.connect_google_calendar(cx))
67
}),
68
)
69
}
70
}
71
72
fn account_block(
73
app: &Entity<AppState>,
74
account: &store::GoogleAccount,
75
accounts: &store::CalendarAccounts,
76
) -> Div {
77
let disconnect_app = app.clone();
78
let account_id = account.id.clone();
79
let mut block = v_flex().w_full().child(control_row(
80
account.email.clone(),
81
"Google account",
82
text_button(
83
format!("settings-google-disconnect-{}", account.id),
84
"Disconnect",
85
)
86
.on_click(move |_, _, cx| {
87
disconnect_app.update(cx, |state, cx| {
88
state.disconnect_google_account(&account_id, cx)
89
})
90
}),
91
));
92
for calendar in &account.calendars {
93
let toggle_app = app.clone();
94
let account_id = account.id.clone();
95
let calendar_id = calendar.id.clone();
96
let write_ref = CalendarRef::google(&account.id, &calendar.id);
97
let is_home = accounts.home.key() == write_ref.key();
98
let is_write = accounts
99
.write_targets
100
.iter()
101
.any(|target| target.key() == write_ref.key());
102
block = block.child(
103
toggle_row(
104
format!("settings-google-cal-{}", calendar.id),
105
calendar.summary.clone(),
106
if calendar.primary {
107
"Primary calendar"
108
} else {
109
"Show in calendar grid"
110
},
111
theme::text_muted(),
112
calendar.selected,
113
)
114
.on_click(move |_, _, cx| {
115
toggle_app.update(cx, |state, cx| {
116
state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)
117
})
118
}),
119
);
120
if !is_home {
121
let write_app = app.clone();
122
let target = write_ref;
123
block = block.child(
124
toggle_row(
125
format!("settings-google-write-{}", calendar.id),
126
format!("Also write new meetings to {}", calendar.summary),
127
"",
128
theme::text_muted(),
129
is_write,
130
)
131
.on_click(move |_, _, cx| {
132
write_app.update(cx, |state, cx| {
133
state.toggle_write_target(target.clone(), cx)
134
})
135
}),
136
);
137
}
138
}
139
block
140
}
141
142
fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {
143
let mut choices = v_flex().w_full();
144
let outlook_app = app.clone();
145
let outlook_home = accounts.home.provider == CalendarProvider::Outlook;
146
choices = choices.child(
147
toggle_row(
148
"settings-home-outlook",
149
"Outlook (Microsoft mailbox)",
150
"Default when no Google home is chosen",
151
theme::text_muted(),
152
outlook_home,
153
)
154
.on_click(move |_, _, cx| {
155
outlook_app.update(cx, |state, cx| {
156
state.set_home_calendar(CalendarRef::outlook(), cx)
157
})
158
}),
159
);
160
for account in &accounts.google_accounts {
161
for calendar in &account.calendars {
162
let home_app = app.clone();
163
let target = CalendarRef::google(&account.id, &calendar.id);
164
let selected = accounts.home.key() == target.key();
165
choices = choices.child(
166
toggle_row(
167
format!("settings-home-google-{}", calendar.id),
168
format!("Google · {}", calendar.summary),
169
account.email.clone(),
170
theme::text_muted(),
171
selected,
172
)
173
.on_click(move |_, _, cx| {
174
home_app.update(cx, |state, cx| state.set_home_calendar(target.clone(), cx))
175
}),
176
);
177
}
178
}
179
choices
180
}
@@ -0,0 +1,180 @@1
use gpui_kit::component::v_flex;2
use gpui_kit::*;3
use store::{CalendarProvider, CalendarRef};4
5
use super::rows::{caption, control_row, text_button, toggle_row};6
use crate::app_state::AppState;7
use crate::theme;8
9
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {10
let accounts = app.read(cx).calendar_accounts();11
let mut body = v_flex()12
.w_full()13
.child(caption("GOOGLE"))14
.child(connect_row(app, accounts.has_google()));15
for account in &accounts.google_accounts {16
body = body.child(account_block(app, account, &accounts));17
}18
body = body19
.child(caption("HOME CALENDAR"))20
.child(home_choices(app, &accounts))21
.child(caption("ALSO WRITE TO"));22
if accounts.home.provider != CalendarProvider::Outlook {23
let write_app = app.clone();24
let target = CalendarRef::outlook();25
let selected = accounts26
.write_targets27
.iter()28
.any(|existing| existing.key() == target.key());29
body = body.child(30
toggle_row(31
"settings-write-outlook",32
"Outlook (Microsoft mailbox)",33
"Dual-write when home is Google",34
theme::text_muted(),35
selected,36
)37
.on_click(move |_, _, cx| {38
write_app.update(cx, |state, cx| {39
state.toggle_write_target(target.clone(), cx)40
})41
}),42
);43
} else if accounts.google_accounts.is_empty() {44
body = body.child(control_row(45
"No extra write targets",46
"Connect Google, then enable dual-write on a calendar above.",47
div(),48
));49
}50
body51
}52
53
fn connect_row(app: &Entity<AppState>, connected: bool) -> Div {54
let app = app.clone();55
if connected {56
control_row(57
"Google Calendar",58
"Connected accounts appear below. Disconnect removes tokens from this device.",59
div(),60
)61
} else {62
control_row(63
"Google Calendar",64
"Requires TEAMS_GOOGLE_CLIENT_ID. Opens a browser for sign-in.",65
text_button("settings-google-connect", "Connect Google").on_click(move |_, _, cx| {66
app.update(cx, |state, cx| state.connect_google_calendar(cx))67
}),68
)69
}70
}71
72
fn account_block(73
app: &Entity<AppState>,74
account: &store::GoogleAccount,75
accounts: &store::CalendarAccounts,76
) -> Div {77
let disconnect_app = app.clone();78
let account_id = account.id.clone();79
let mut block = v_flex().w_full().child(control_row(80
account.email.clone(),81
"Google account",82
text_button(83
format!("settings-google-disconnect-{}", account.id),84
"Disconnect",85
)86
.on_click(move |_, _, cx| {87
disconnect_app.update(cx, |state, cx| {88
state.disconnect_google_account(&account_id, cx)89
})90
}),91
));92
for calendar in &account.calendars {93
let toggle_app = app.clone();94
let account_id = account.id.clone();95
let calendar_id = calendar.id.clone();96
let write_ref = CalendarRef::google(&account.id, &calendar.id);97
let is_home = accounts.home.key() == write_ref.key();98
let is_write = accounts99
.write_targets100
.iter()101
.any(|target| target.key() == write_ref.key());102
block = block.child(103
toggle_row(104
format!("settings-google-cal-{}", calendar.id),105
calendar.summary.clone(),106
if calendar.primary {107
"Primary calendar"108
} else {109
"Show in calendar grid"110
},111
theme::text_muted(),112
calendar.selected,113
)114
.on_click(move |_, _, cx| {115
toggle_app.update(cx, |state, cx| {116
state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)117
})118
}),119
);120
if !is_home {121
let write_app = app.clone();122
let target = write_ref;123
block = block.child(124
toggle_row(125
format!("settings-google-write-{}", calendar.id),126
format!("Also write new meetings to {}", calendar.summary),127
"",128
theme::text_muted(),129
is_write,130
)131
.on_click(move |_, _, cx| {132
write_app.update(cx, |state, cx| {133
state.toggle_write_target(target.clone(), cx)134
})135
}),136
);137
}138
}139
block140
}141
142
fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {143
let mut choices = v_flex().w_full();144
let outlook_app = app.clone();145
let outlook_home = accounts.home.provider == CalendarProvider::Outlook;146
choices = choices.child(147
toggle_row(148
"settings-home-outlook",149
"Outlook (Microsoft mailbox)",150
"Default when no Google home is chosen",151
theme::text_muted(),152
outlook_home,153
)154
.on_click(move |_, _, cx| {155
outlook_app.update(cx, |state, cx| {156
state.set_home_calendar(CalendarRef::outlook(), cx)157
})158
}),159
);160
for account in &accounts.google_accounts {161
for calendar in &account.calendars {162
let home_app = app.clone();163
let target = CalendarRef::google(&account.id, &calendar.id);164
let selected = accounts.home.key() == target.key();165
choices = choices.child(166
toggle_row(167
format!("settings-home-google-{}", calendar.id),168
format!("Google · {}", calendar.summary),169
account.email.clone(),170
theme::text_muted(),171
selected,172
)173
.on_click(move |_, _, cx| {174
home_app.update(cx, |state, cx| state.set_home_calendar(target.clone(), cx))175
}),176
);177
}178
}179
choices180
}@@ -1,7 +1,7 @@
1
1
use app_ui_kit::settings_controls::PAGE_PADDING;
2
use gpui_kit::component::scroll::ScrollableElement as _;
3
2
use gpui_kit::assets::IconName;
4
3
use gpui_kit::component::input::{Input, InputEvent, InputState};
4
use gpui_kit::component::scroll::ScrollableElement as _;
5
5
use gpui_kit::component::{h_flex, v_flex};
6
6
use gpui_kit::*;
7
7
@@ -9,7 +9,7 @@ use super::devices::DevicesView;
9
9
use super::mcp::McpView;
10
10
use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};
11
11
use super::rows::ROW_INSET;
12
use super::{about, appearance, calls, chats, general, notifications};
12
use super::{about, appearance, calendar, calls, chats, general, notifications};
13
13
use crate::agents::AgentsSettings;
14
14
use crate::app_state::AppState;
15
15
use crate::notify::NotificationCenter;
@@ -85,11 +85,15 @@ impl SettingsDialog {
85
85
let subscriptions = [
86
86
cx.observe(¢er, |_, _, cx| cx.notify()),
87
87
cx.observe(&app, |_, _, cx| cx.notify()),
88
cx.subscribe_in(&search, window, |this, _, event: &InputEvent, window, cx| {
89
if matches!(event, InputEvent::Change) {
90
this.follow_search(window, cx);
91
}
92
}),
88
cx.subscribe_in(
89
&search,
90
window,
91
|this, _, event: &InputEvent, window, cx| {
92
if matches!(event, InputEvent::Change) {
93
this.follow_search(window, cx);
94
}
95
},
96
),
93
97
];
94
98
let focus_handle = cx.focus_handle();
95
99
window.focus(&focus_handle, cx);
@@ -182,6 +186,7 @@ impl SettingsDialog {
182
186
SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),
183
187
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
184
188
SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),
189
SettingsSection::Calendar => calendar::render(&self.app, cx).into_any_element(),
185
190
SettingsSection::Devices => self
186
191
.devices
187
192
.clone()
@@ -1,7 +1,7 @@1
use app_ui_kit::settings_controls::PAGE_PADDING;1
use app_ui_kit::settings_controls::PAGE_PADDING;2
use gpui_kit::component::scroll::ScrollableElement as _;3
use gpui_kit::assets::IconName;2
use gpui_kit::assets::IconName;4
use gpui_kit::component::input::{Input, InputEvent, InputState};3
use gpui_kit::component::input::{Input, InputEvent, InputState};4
use gpui_kit::component::scroll::ScrollableElement as _;5
use gpui_kit::component::{h_flex, v_flex};5
use gpui_kit::component::{h_flex, v_flex};6
use gpui_kit::*;6
use gpui_kit::*;7
7
@@ -9,7 +9,7 @@ use super::devices::DevicesView;9
use super::mcp::McpView;9
use super::mcp::McpView;10
use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};10
use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};11
use super::rows::ROW_INSET;11
use super::rows::ROW_INSET;12
use super::{about, appearance, calls, chats, general, notifications};12
use super::{about, appearance, calendar, calls, chats, general, notifications};13
use crate::agents::AgentsSettings;13
use crate::agents::AgentsSettings;14
use crate::app_state::AppState;14
use crate::app_state::AppState;15
use crate::notify::NotificationCenter;15
use crate::notify::NotificationCenter;@@ -85,11 +85,15 @@ impl SettingsDialog {85
let subscriptions = [85
let subscriptions = [86
cx.observe(¢er, |_, _, cx| cx.notify()),86
cx.observe(¢er, |_, _, cx| cx.notify()),87
cx.observe(&app, |_, _, cx| cx.notify()),87
cx.observe(&app, |_, _, cx| cx.notify()),88
cx.subscribe_in(&search, window, |this, _, event: &InputEvent, window, cx| {88
cx.subscribe_in(89
if matches!(event, InputEvent::Change) {89
&search,90
this.follow_search(window, cx);90
window,91
}91
|this, _, event: &InputEvent, window, cx| {92
}),92
if matches!(event, InputEvent::Change) {93
this.follow_search(window, cx);94
}95
},96
),93
];97
];94
let focus_handle = cx.focus_handle();98
let focus_handle = cx.focus_handle();95
window.focus(&focus_handle, cx);99
window.focus(&focus_handle, cx);@@ -182,6 +186,7 @@ impl SettingsDialog {182
SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),186
SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),183
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),187
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),184
SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),188
SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),189
SettingsSection::Calendar => calendar::render(&self.app, cx).into_any_element(),185
SettingsSection::Devices => self190
SettingsSection::Devices => self186
.devices191
.devices187
.clone()192
.clone()@@ -1,6 +1,7 @@
1
1
mod about;
2
2
mod account;
3
3
mod appearance;
4
mod calendar;
4
5
mod calls;
5
6
mod chats;
6
7
mod devices;
@@ -1,6 +1,7 @@1
mod about;1
mod about;2
mod account;2
mod account;3
mod appearance;3
mod appearance;4
mod calendar;4
mod calls;5
mod calls;5
mod chats;6
mod chats;6
mod devices;7
mod devices;@@ -0,0 +1,210 @@
1
use chatsvc::{CalendarEvent, ResponseType, join_info_text};
2
use chrono::{Local, Offset};
3
use gpui_kit::assets::IconName;
4
use gpui_kit::component::Sizable as _;
5
use gpui_kit::component::button::{Button, ButtonVariants as _};
6
use gpui_kit::component::dialog::{Dialog, DialogFooter};
7
use gpui_kit::component::menu::DropdownMenu as _;
8
use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
9
use gpui_kit::*;
10
11
use super::rsvp_menu::rsvp_menu;
12
use crate::i18n::tr;
13
use crate::app_state::AppState;
14
use crate::call::week_grid::is_effective_all_day;
15
use crate::theme;
16
17
const DIALOG_WIDTH: f32 = 440.;
18
const FIELD_GAP: f32 = 12.;
19
const LABEL_SIZE: f32 = 12.;
20
const COPY_JOIN_INFO: &str = "Copy join info";
21
22
fn when_label(event: &CalendarEvent) -> String {
23
let offset = Local::now().offset().fix();
24
if is_effective_all_day(event, offset) {
25
let start = event.start.with_timezone(&offset).date_naive();
26
let end = event.end.with_timezone(&offset).date_naive();
27
if end > start + chrono::Duration::days(1) {
28
return format!(
29
"All day · {} – {}",
30
start.format("%a, %b %-d"),
31
(end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")
32
);
33
}
34
return format!("All day · {}", start.format("%a, %b %-d, %Y"));
35
}
36
let start = event.start.with_timezone(&offset);
37
let end = event.end.with_timezone(&offset);
38
if start.date_naive() == end.date_naive() {
39
format!(
40
"{} · {} – {}",
41
start.format("%a, %b %-d, %Y"),
42
start.format(app_base::format::clock_format()),
43
end.format(app_base::format::clock_format())
44
)
45
} else {
46
format!(
47
"{} {} – {} {}",
48
start.format("%a, %b %-d"),
49
start.format(app_base::format::clock_format()),
50
end.format("%a, %b %-d, %Y"),
51
end.format(app_base::format::clock_format())
52
)
53
}
54
}
55
56
fn source_label(event: &CalendarEvent) -> String {
57
let mut sources = event.sources.clone();
58
if sources.is_empty() {
59
sources.push(event.source);
60
}
61
sources.sort_by_key(|source| source.label());
62
sources.dedup();
63
sources
64
.iter()
65
.map(|source| source.label())
66
.collect::<Vec<_>>()
67
.join(" + ")
68
}
69
70
fn detail_row(label: &str, value: impl Into<SharedString>) -> Div {
71
v_flex()
72
.gap(px(2.))
73
.child(
74
div()
75
.text_size(px(LABEL_SIZE))
76
.text_color(theme::text_muted())
77
.child(label.to_owned()),
78
)
79
.child(
80
div()
81
.text_size(px(14.))
82
.text_color(theme::text())
83
.child(value.into()),
84
)
85
}
86
87
pub fn open_calendar_event(
88
state: Entity<AppState>,
89
event: CalendarEvent,
90
window: &mut Window,
91
cx: &mut App,
92
) {
93
let send_response = state.read(cx).rsvp_send_response;
94
// Show Join whenever a Teams link exists — not only inside the join window.
95
let can_join = event.online && !event.cancelled && event.join_url.is_some();
96
let subject = if event.cancelled {
97
format!("Canceled: {}", event.subject)
98
} else if event.subject.is_empty() {
99
"(No title)".to_owned()
100
} else {
101
event.subject.clone()
102
};
103
let when = when_label(&event);
104
let source = source_label(&event);
105
let organizer = event
106
.organizer_name
107
.clone()
108
.or_else(|| event.organizer_address.clone());
109
let join_url = event.join_url.clone();
110
let dial_in = event.dial_in.clone();
111
let thread_id = event.thread_id.clone();
112
let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();
113
let response = event.response;
114
let event_key = event.object_id.clone();
115
let meeting_title = event.subject.clone();
116
let online = event.online;
117
118
window.open_dialog(cx, move |dialog: Dialog, _, _| {
119
let delete_state = state.clone();
120
let delete_key = event_key.clone();
121
let mut footer = DialogFooter::new()
122
.child(
123
Button::new("calendar-event-delete")
124
.danger()
125
.label(tr("common.delete"))
126
.on_click(move |_, window, cx| {
127
delete_state
128
.update(cx, |state, cx| state.delete_calendar_event(&delete_key, cx));
129
window.close_dialog(cx);
130
}),
131
)
132
.child(
133
Button::new("calendar-event-close")
134
.label(tr("common.close"))
135
.on_click(|_, window, cx| window.close_dialog(cx)),
136
);
137
if can_rsvp {
138
let menu_state = state.clone();
139
let menu_key = event_key.clone();
140
footer = footer.child(
141
Button::new("calendar-event-rsvp")
142
.label("RSVP")
143
.dropdown_menu(move |menu, _, _| {
144
rsvp_menu(menu, &menu_state, &menu_key, response, send_response)
145
}),
146
);
147
}
148
if thread_id.is_some() {
149
let chat_state = state.clone();
150
let chat_thread = thread_id.clone();
151
footer = footer.child(Button::new("calendar-event-chat").label(tr("common.chat")).on_click(
152
move |_, window, cx| {
153
chat_state.update(cx, |state, cx| {
154
state.open_meeting_chat(chat_thread.as_deref(), cx)
155
});
156
window.close_dialog(cx);
157
},
158
));
159
}
160
if can_join {
161
let join_state = state.clone();
162
let url = join_url.clone();
163
let title = meeting_title.clone();
164
footer = footer.child(
165
Button::new("calendar-event-join")
166
.primary()
167
.label(tr("common.join"))
168
.on_click(move |_, window, cx| {
169
join_state.update(cx, |state, cx| {
170
state.join_calendar_meeting(url.as_deref(), &title, cx)
171
});
172
window.close_dialog(cx);
173
}),
174
);
175
}
176
177
let mut body = v_flex()
178
.gap(px(FIELD_GAP))
179
.child(detail_row("When", when.clone()))
180
.child(detail_row("Calendar", source.clone()));
181
if let Some(name) = organizer.clone() {
182
body = body.child(detail_row("Organizer", name));
183
}
184
if let Some(url) = join_url.clone().filter(|_| online) {
185
let info = join_info_text(&url, dial_in.as_ref());
186
body = body.child(
187
v_flex()
188
.gap(px(6.))
189
.child(detail_row("Join link", url))
190
.child(
191
h_flex().child(
192
Button::new("calendar-event-copy-join")
193
.small()
194
.label(COPY_JOIN_INFO)
195
.icon(IconName::Copy)
196
.on_click(move |_, _, cx| {
197
cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
198
}),
199
),
200
),
201
);
202
}
203
204
dialog
205
.title(subject.clone())
206
.w(px(DIALOG_WIDTH))
207
.child(body)
208
.footer(footer)
209
});
210
}
@@ -0,0 +1,210 @@1
use chatsvc::{CalendarEvent, ResponseType, join_info_text};2
use chrono::{Local, Offset};3
use gpui_kit::assets::IconName;4
use gpui_kit::component::Sizable as _;5
use gpui_kit::component::button::{Button, ButtonVariants as _};6
use gpui_kit::component::dialog::{Dialog, DialogFooter};7
use gpui_kit::component::menu::DropdownMenu as _;8
use gpui_kit::component::{WindowExt as _, h_flex, v_flex};9
use gpui_kit::*;10
11
use super::rsvp_menu::rsvp_menu;12
use crate::i18n::tr;13
use crate::app_state::AppState;14
use crate::call::week_grid::is_effective_all_day;15
use crate::theme;16
17
const DIALOG_WIDTH: f32 = 440.;18
const FIELD_GAP: f32 = 12.;19
const LABEL_SIZE: f32 = 12.;20
const COPY_JOIN_INFO: &str = "Copy join info";21
22
fn when_label(event: &CalendarEvent) -> String {23
let offset = Local::now().offset().fix();24
if is_effective_all_day(event, offset) {25
let start = event.start.with_timezone(&offset).date_naive();26
let end = event.end.with_timezone(&offset).date_naive();27
if end > start + chrono::Duration::days(1) {28
return format!(29
"All day · {} – {}",30
start.format("%a, %b %-d"),31
(end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")32
);33
}34
return format!("All day · {}", start.format("%a, %b %-d, %Y"));35
}36
let start = event.start.with_timezone(&offset);37
let end = event.end.with_timezone(&offset);38
if start.date_naive() == end.date_naive() {39
format!(40
"{} · {} – {}",41
start.format("%a, %b %-d, %Y"),42
start.format(app_base::format::clock_format()),43
end.format(app_base::format::clock_format())44
)45
} else {46
format!(47
"{} {} – {} {}",48
start.format("%a, %b %-d"),49
start.format(app_base::format::clock_format()),50
end.format("%a, %b %-d, %Y"),51
end.format(app_base::format::clock_format())52
)53
}54
}55
56
fn source_label(event: &CalendarEvent) -> String {57
let mut sources = event.sources.clone();58
if sources.is_empty() {59
sources.push(event.source);60
}61
sources.sort_by_key(|source| source.label());62
sources.dedup();63
sources64
.iter()65
.map(|source| source.label())66
.collect::<Vec<_>>()67
.join(" + ")68
}69
70
fn detail_row(label: &str, value: impl Into<SharedString>) -> Div {71
v_flex()72
.gap(px(2.))73
.child(74
div()75
.text_size(px(LABEL_SIZE))76
.text_color(theme::text_muted())77
.child(label.to_owned()),78
)79
.child(80
div()81
.text_size(px(14.))82
.text_color(theme::text())83
.child(value.into()),84
)85
}86
87
pub fn open_calendar_event(88
state: Entity<AppState>,89
event: CalendarEvent,90
window: &mut Window,91
cx: &mut App,92
) {93
let send_response = state.read(cx).rsvp_send_response;94
// Show Join whenever a Teams link exists — not only inside the join window.95
let can_join = event.online && !event.cancelled && event.join_url.is_some();96
let subject = if event.cancelled {97
format!("Canceled: {}", event.subject)98
} else if event.subject.is_empty() {99
"(No title)".to_owned()100
} else {101
event.subject.clone()102
};103
let when = when_label(&event);104
let source = source_label(&event);105
let organizer = event106
.organizer_name107
.clone()108
.or_else(|| event.organizer_address.clone());109
let join_url = event.join_url.clone();110
let dial_in = event.dial_in.clone();111
let thread_id = event.thread_id.clone();112
let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();113
let response = event.response;114
let event_key = event.object_id.clone();115
let meeting_title = event.subject.clone();116
let online = event.online;117
118
window.open_dialog(cx, move |dialog: Dialog, _, _| {119
let delete_state = state.clone();120
let delete_key = event_key.clone();121
let mut footer = DialogFooter::new()122
.child(123
Button::new("calendar-event-delete")124
.danger()125
.label(tr("common.delete"))126
.on_click(move |_, window, cx| {127
delete_state128
.update(cx, |state, cx| state.delete_calendar_event(&delete_key, cx));129
window.close_dialog(cx);130
}),131
)132
.child(133
Button::new("calendar-event-close")134
.label(tr("common.close"))135
.on_click(|_, window, cx| window.close_dialog(cx)),136
);137
if can_rsvp {138
let menu_state = state.clone();139
let menu_key = event_key.clone();140
footer = footer.child(141
Button::new("calendar-event-rsvp")142
.label("RSVP")143
.dropdown_menu(move |menu, _, _| {144
rsvp_menu(menu, &menu_state, &menu_key, response, send_response)145
}),146
);147
}148
if thread_id.is_some() {149
let chat_state = state.clone();150
let chat_thread = thread_id.clone();151
footer = footer.child(Button::new("calendar-event-chat").label(tr("common.chat")).on_click(152
move |_, window, cx| {153
chat_state.update(cx, |state, cx| {154
state.open_meeting_chat(chat_thread.as_deref(), cx)155
});156
window.close_dialog(cx);157
},158
));159
}160
if can_join {161
let join_state = state.clone();162
let url = join_url.clone();163
let title = meeting_title.clone();164
footer = footer.child(165
Button::new("calendar-event-join")166
.primary()167
.label(tr("common.join"))168
.on_click(move |_, window, cx| {169
join_state.update(cx, |state, cx| {170
state.join_calendar_meeting(url.as_deref(), &title, cx)171
});172
window.close_dialog(cx);173
}),174
);175
}176
177
let mut body = v_flex()178
.gap(px(FIELD_GAP))179
.child(detail_row("When", when.clone()))180
.child(detail_row("Calendar", source.clone()));181
if let Some(name) = organizer.clone() {182
body = body.child(detail_row("Organizer", name));183
}184
if let Some(url) = join_url.clone().filter(|_| online) {185
let info = join_info_text(&url, dial_in.as_ref());186
body = body.child(187
v_flex()188
.gap(px(6.))189
.child(detail_row("Join link", url))190
.child(191
h_flex().child(192
Button::new("calendar-event-copy-join")193
.small()194
.label(COPY_JOIN_INFO)195
.icon(IconName::Copy)196
.on_click(move |_, _, cx| {197
cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))198
}),199
),200
),201
);202
}203
204
dialog205
.title(subject.clone())206
.w(px(DIALOG_WIDTH))207
.child(body)208
.footer(footer)209
});210
}@@ -6,7 +6,7 @@ use gpui_kit::prelude::FluentBuilder as _;
6
6
use gpui_kit::*;
7
7
8
8
use crate::app_state::AppState;
9
use crate::call::week_grid::{WeekDay, month_shown};
9
use crate::call::week_grid::{WeekDay, is_effective_all_day, month_shown};
10
10
use crate::theme;
11
11
12
12
pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";
@@ -35,7 +35,8 @@ fn more_label(hidden: usize) -> String {
35
35
}
36
36
37
37
fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
38
let time = (!event.all_day).then(|| {
38
let all_day = is_effective_all_day(event, offset);
39
let time = (!all_day).then(|| {
39
40
event
40
41
.start
41
42
.with_timezone(&offset)
@@ -50,16 +51,28 @@ fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
50
51
.gap(px(6.))
51
52
.items_center()
52
53
.rounded(px(4.))
53
.bg(theme::accent().opacity(if event.all_day { 0.28 } else { 0.14 }))
54
.bg(theme::accent().opacity(if all_day { 0.28 } else { 0.14 }))
54
55
.text_size(px(11.5))
55
56
.text_color(theme::text())
56
.children(time.map(|time| {
57
div()
58
.flex_none()
59
.text_color(theme::text_soft())
60
.child(time)
57
.children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))
58
.child(div().flex_1().min_w_0().truncate().child({
59
let mut sources = event.sources.clone();
60
if sources.is_empty() {
61
sources.push(event.source);
62
}
63
sources.sort_by_key(|source| source.label());
64
sources.dedup();
65
if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {
66
event.subject.clone()
67
} else {
68
let names = sources
69
.iter()
70
.map(|source| source.label())
71
.collect::<Vec<_>>()
72
.join("+");
73
format!("{} · {names}", event.subject)
74
}
61
75
}))
62
.child(div().flex_1().min_w_0().truncate().child(event.subject.clone()))
63
76
}
64
77
65
78
fn day_cell(
@@ -6,7 +6,7 @@ use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::*;6
use gpui_kit::*;7
7
8
use crate::app_state::AppState;8
use crate::app_state::AppState;9
use crate::call::week_grid::{WeekDay, month_shown};9
use crate::call::week_grid::{WeekDay, is_effective_all_day, month_shown};10
use crate::theme;10
use crate::theme;11
11
12
pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";12
pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";@@ -35,7 +35,8 @@ fn more_label(hidden: usize) -> String {35
}35
}36
36
37
fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {37
fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {38
let time = (!event.all_day).then(|| {38
let all_day = is_effective_all_day(event, offset);39
let time = (!all_day).then(|| {39
event40
event40
.start41
.start41
.with_timezone(&offset)42
.with_timezone(&offset)@@ -50,16 +51,28 @@ fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {50
.gap(px(6.))51
.gap(px(6.))51
.items_center()52
.items_center()52
.rounded(px(4.))53
.rounded(px(4.))53
.bg(theme::accent().opacity(if event.all_day { 0.28 } else { 0.14 }))54
.bg(theme::accent().opacity(if all_day { 0.28 } else { 0.14 }))54
.text_size(px(11.5))55
.text_size(px(11.5))55
.text_color(theme::text())56
.text_color(theme::text())56
.children(time.map(|time| {57
.children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))57
div()58
.child(div().flex_1().min_w_0().truncate().child({58
.flex_none()59
let mut sources = event.sources.clone();59
.text_color(theme::text_soft())60
if sources.is_empty() {60
.child(time)61
sources.push(event.source);62
}63
sources.sort_by_key(|source| source.label());64
sources.dedup();65
if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {66
event.subject.clone()67
} else {68
let names = sources69
.iter()70
.map(|source| source.label())71
.collect::<Vec<_>>()72
.join("+");73
format!("{} · {names}", event.subject)74
}61
}))75
}))62
.child(div().flex_1().min_w_0().truncate().child(event.subject.clone()))63
}76
}64
77
65
fn day_cell(78
fn day_cell(@@ -0,0 +1,137 @@
1
use gpui_kit::assets::IconName;
2
use gpui_kit::component::{h_flex, v_flex};
3
use gpui_kit::prelude::FluentBuilder as _;
4
use gpui_kit::*;
5
use store::CalendarAccounts;
6
7
use crate::app_state::AppState;
8
use crate::theme;
9
use crate::views::widgets::icon;
10
11
pub const PICKER_WIDTH: f32 = 220.;
12
const ROW_HEIGHT: f32 = 28.;
13
14
/// Teams-like calendar list: Outlook + each connected Google calendar with show toggles.
15
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
16
let accounts = app.read(cx).calendar_accounts();
17
let mut column = v_flex()
18
.debug_selector(|| "shell/islands/calendar/picker".into())
19
.w(px(PICKER_WIDTH))
20
.flex_none()
21
.h_full()
22
.border_r_1()
23
.border_color(theme::border())
24
.bg(theme::surface())
25
.px(px(12.))
26
.py(px(12.))
27
.gap(px(4.))
28
.child(
29
div()
30
.text_size(px(11.))
31
.font_weight(FontWeight::SEMIBOLD)
32
.text_color(theme::text_muted())
33
.mb(px(6.))
34
.child("CALENDARS"),
35
)
36
.child(outlook_row(app, &accounts));
37
for account in &accounts.google_accounts {
38
column = column.child(
39
div()
40
.mt(px(8.))
41
.mb(px(2.))
42
.text_size(px(11.))
43
.font_weight(FontWeight::SEMIBOLD)
44
.text_color(theme::text_muted())
45
.truncate()
46
.child(account.email.clone()),
47
);
48
for calendar in &account.calendars {
49
let toggle_app = app.clone();
50
let account_id = account.id.clone();
51
let calendar_id = calendar.id.clone();
52
let color = if calendar.primary {
53
theme::accent()
54
} else {
55
theme::text_soft()
56
};
57
column = column.child(toggle_row(
58
format!("calendar-picker-{}", calendar.id),
59
calendar.summary.clone(),
60
calendar.selected,
61
color,
62
move |cx| {
63
toggle_app.update(cx, |state, cx| {
64
state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)
65
});
66
},
67
));
68
}
69
}
70
if !accounts.has_google() {
71
column = column.child(
72
div()
73
.mt(px(8.))
74
.text_size(px(12.))
75
.text_color(theme::text_muted())
76
.child("Connect Google in Settings › Calendar"),
77
);
78
}
79
column
80
}
81
82
fn outlook_row(app: &Entity<AppState>, accounts: &CalendarAccounts) -> Stateful<Div> {
83
let app = app.clone();
84
toggle_row(
85
"calendar-picker-outlook",
86
"Outlook",
87
accounts.outlook_selected,
88
theme::accent(),
89
move |cx| {
90
app.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx));
91
},
92
)
93
}
94
95
fn toggle_row(
96
id: impl Into<ElementId>,
97
label: impl Into<SharedString>,
98
on: bool,
99
swatch: Hsla,
100
on_click: impl Fn(&mut App) + 'static,
101
) -> Stateful<Div> {
102
h_flex()
103
.id(id)
104
.h(px(ROW_HEIGHT))
105
.flex_none()
106
.w_full()
107
.items_center()
108
.gap(px(8.))
109
.rounded(px(6.))
110
.px(px(4.))
111
.cursor_pointer()
112
.hover(|row| row.bg(theme::popup_hover()))
113
.on_click(move |_, _, cx| on_click(cx))
114
.child(
115
div()
116
.size(px(14.))
117
.flex_none()
118
.rounded(px(3.))
119
.bg(if on { swatch } else { theme::border() })
120
.when(on, |box_| {
121
box_.flex().items_center().justify_center().child(icon(
122
IconName::Check,
123
10.,
124
theme::text(),
125
))
126
}),
127
)
128
.child(
129
div()
130
.flex_1()
131
.min_w_0()
132
.truncate()
133
.text_size(px(13.))
134
.text_color(theme::text())
135
.child(label.into()),
136
)
137
}
@@ -0,0 +1,137 @@1
use gpui_kit::assets::IconName;2
use gpui_kit::component::{h_flex, v_flex};3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;5
use store::CalendarAccounts;6
7
use crate::app_state::AppState;8
use crate::theme;9
use crate::views::widgets::icon;10
11
pub const PICKER_WIDTH: f32 = 220.;12
const ROW_HEIGHT: f32 = 28.;13
14
/// Teams-like calendar list: Outlook + each connected Google calendar with show toggles.15
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {16
let accounts = app.read(cx).calendar_accounts();17
let mut column = v_flex()18
.debug_selector(|| "shell/islands/calendar/picker".into())19
.w(px(PICKER_WIDTH))20
.flex_none()21
.h_full()22
.border_r_1()23
.border_color(theme::border())24
.bg(theme::surface())25
.px(px(12.))26
.py(px(12.))27
.gap(px(4.))28
.child(29
div()30
.text_size(px(11.))31
.font_weight(FontWeight::SEMIBOLD)32
.text_color(theme::text_muted())33
.mb(px(6.))34
.child("CALENDARS"),35
)36
.child(outlook_row(app, &accounts));37
for account in &accounts.google_accounts {38
column = column.child(39
div()40
.mt(px(8.))41
.mb(px(2.))42
.text_size(px(11.))43
.font_weight(FontWeight::SEMIBOLD)44
.text_color(theme::text_muted())45
.truncate()46
.child(account.email.clone()),47
);48
for calendar in &account.calendars {49
let toggle_app = app.clone();50
let account_id = account.id.clone();51
let calendar_id = calendar.id.clone();52
let color = if calendar.primary {53
theme::accent()54
} else {55
theme::text_soft()56
};57
column = column.child(toggle_row(58
format!("calendar-picker-{}", calendar.id),59
calendar.summary.clone(),60
calendar.selected,61
color,62
move |cx| {63
toggle_app.update(cx, |state, cx| {64
state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)65
});66
},67
));68
}69
}70
if !accounts.has_google() {71
column = column.child(72
div()73
.mt(px(8.))74
.text_size(px(12.))75
.text_color(theme::text_muted())76
.child("Connect Google in Settings › Calendar"),77
);78
}79
column80
}81
82
fn outlook_row(app: &Entity<AppState>, accounts: &CalendarAccounts) -> Stateful<Div> {83
let app = app.clone();84
toggle_row(85
"calendar-picker-outlook",86
"Outlook",87
accounts.outlook_selected,88
theme::accent(),89
move |cx| {90
app.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx));91
},92
)93
}94
95
fn toggle_row(96
id: impl Into<ElementId>,97
label: impl Into<SharedString>,98
on: bool,99
swatch: Hsla,100
on_click: impl Fn(&mut App) + 'static,101
) -> Stateful<Div> {102
h_flex()103
.id(id)104
.h(px(ROW_HEIGHT))105
.flex_none()106
.w_full()107
.items_center()108
.gap(px(8.))109
.rounded(px(6.))110
.px(px(4.))111
.cursor_pointer()112
.hover(|row| row.bg(theme::popup_hover()))113
.on_click(move |_, _, cx| on_click(cx))114
.child(115
div()116
.size(px(14.))117
.flex_none()118
.rounded(px(3.))119
.bg(if on { swatch } else { theme::border() })120
.when(on, |box_| {121
box_.flex().items_center().justify_center().child(icon(122
IconName::Check,123
10.,124
theme::text(),125
))126
}),127
)128
.child(129
div()130
.flex_1()131
.min_w_0()132
.truncate()133
.text_size(px(13.))134
.text_color(theme::text())135
.child(label.into()),136
)137
}@@ -1,3 +1,5 @@
1
use std::time::Duration;
2
1
3
use app_base::format::{self, clock_format};
2
4
use chatsvc::{CalendarEvent, ResponseType, join_info_text};
3
5
use chrono::{DateTime, Local, NaiveDate, Offset, Timelike, Utc};
@@ -10,13 +12,20 @@ use gpui_kit::prelude::FluentBuilder as _;
10
12
use gpui_kit::*;
11
13
12
14
use super::calendar_date_picker::date_picker_button;
15
use super::calendar_event_dialog::open_calendar_event;
13
16
use super::calendar_month::month_grid;
14
use super::meeting_proposal_card::meeting_proposal_cards;
15
use super::rsvp_menu::rsvp_menu;
17
use super::calendar_picker;
16
18
use super::join_dialog::open_join_with_id;
19
use super::meeting_proposal_card::meeting_proposal_cards;
17
20
use super::new_meeting_dialog::open_new_meeting;
21
use super::rsvp_menu::rsvp_menu;
22
use super::scroll_edge::scroll_offset;
23
use crate::i18n::tr;
18
24
use crate::app_state::AppState;
19
use crate::call::join_available;
25
use crate::call::calendar_now::{
26
DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
27
now_scroll_offset_y, offset_differs, shows_hour_grid,
28
};
20
29
use crate::call::week_grid::{
21
30
CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
22
31
};
@@ -30,7 +39,6 @@ const HEADER_HEIGHT: f32 = 52.;
30
39
const DAY_HEADER_HEIGHT: f32 = 56.;
31
40
const ALL_DAY_HEIGHT: f32 = 26.;
32
41
const BLOCK_GAP: f32 = 2.;
33
const FIRST_VISIBLE_HOUR: f32 = 8.;
34
42
const CANCELED_PREFIX: &str = "Canceled: ";
35
43
const COPY_JOIN_INFO: &str = "Copy join info";
36
44
const COMPACT_HEADER_WIDTH: f32 = 960.;
@@ -42,11 +50,17 @@ const HATCH_GAP: f32 = 2.5;
42
50
const SMALL_TITLE_HEIGHT: f32 = 20.;
43
51
const TODAY_MARK_HEIGHT: f32 = 3.;
44
52
const NOW_DOT_SIZE: f32 = 8.;
53
const CLOCK_TICK: Duration = Duration::from_secs(30);
54
const CHROME_HEIGHT: f32 = HEADER_HEIGHT + DAY_HEADER_HEIGHT + ALL_DAY_HEIGHT;
45
55
46
56
pub struct CalendarView {
47
57
state: Entity<AppState>,
48
58
scroll: ScrollHandle,
49
scrolled_to_morning: bool,
59
follow_now: FollowNow,
60
seen_scroll_to_now: u64,
61
last_programmatic_offset: f32,
62
skip_manual_check: bool,
63
clock_running: bool,
50
64
_observation: Subscription,
51
65
_agent_observation: Option<Subscription>,
52
66
}
@@ -58,12 +72,113 @@ impl CalendarView {
58
72
CalendarView {
59
73
state,
60
74
scroll: ScrollHandle::new(),
61
scrolled_to_morning: false,
75
follow_now: FollowNow { active: true },
76
seen_scroll_to_now: 0,
77
last_programmatic_offset: 0.,
78
skip_manual_check: false,
79
clock_running: false,
62
80
_observation: observation,
63
81
_agent_observation: agent_observation,
64
82
}
65
83
}
66
84
85
fn grid_viewport_height(window: &Window) -> f32 {
86
(f32::from(window.viewport_size().height) - CHROME_HEIGHT).max(DEFAULT_GRID_VIEWPORT * 0.5)
87
}
88
89
fn align_scroll_to_now(&mut self, window: &Window) {
90
let local = Local::now();
91
let offset = now_scroll_offset_y(
92
local.hour(),
93
local.minute(),
94
HOUR_HEIGHT,
95
Self::grid_viewport_height(window),
96
NOW_BIAS_FRACTION,
97
);
98
self.scroll.set_offset(point(px(0.), px(offset)));
99
self.last_programmatic_offset = offset;
100
self.skip_manual_check = true;
101
}
102
103
fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
104
let (scroll_to_now, span, today_visible) = {
105
let state = self.state.read(cx);
106
let start = state.calendar_start();
107
let today = Local::now().date_naive();
108
let today_visible = start <= today
109
&& today < start + chrono::Duration::days(state.calendar_week.span.days());
110
(
111
state.calendar_scroll_to_now,
112
state.calendar_week.span,
113
today_visible,
114
)
115
};
116
if !shows_hour_grid(span) {
117
self.stop_clock();
118
return;
119
}
120
self.ensure_clock(cx);
121
if scroll_to_now != self.seen_scroll_to_now {
122
self.seen_scroll_to_now = scroll_to_now;
123
self.follow_now.request_align();
124
}
125
if self.skip_manual_check {
126
self.skip_manual_check = false;
127
} else if self.follow_now.active
128
&& offset_differs(
129
f32::from(scroll_offset(&self.scroll).y),
130
self.last_programmatic_offset,
131
MANUAL_SCROLL_EPSILON,
132
)
133
{
134
self.follow_now.note_manual_scroll();
135
}
136
if self.follow_now.should_follow(today_visible) {
137
self.align_scroll_to_now(window);
138
}
139
}
140
141
fn ensure_clock(&mut self, cx: &mut Context<Self>) {
142
if self.clock_running {
143
return;
144
}
145
self.clock_running = true;
146
cx.spawn(async move |this, cx| {
147
loop {
148
cx.background_executor().timer(CLOCK_TICK).await;
149
let keep = this
150
.update(cx, |view, cx| {
151
let span = view.state.read(cx).calendar_week.span;
152
if !shows_hour_grid(span) {
153
view.clock_running = false;
154
return false;
155
}
156
cx.notify();
157
true
158
})
159
.unwrap_or(false);
160
if !keep {
161
break;
162
}
163
}
164
})
165
.detach();
166
}
167
168
fn stop_clock(&mut self) {
169
self.clock_running = false;
170
}
171
172
fn on_grid_scroll_wheel(
173
&mut self,
174
_event: &ScrollWheelEvent,
175
_window: &mut Window,
176
cx: &mut Context<Self>,
177
) {
178
self.follow_now.note_manual_scroll();
179
cx.notify();
180
}
181
67
182
fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {
68
183
let span_state = self.state.clone();
69
184
let label = |text: &'static str| (!compact).then_some(text);
@@ -123,19 +238,17 @@ impl CalendarView {
123
238
forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
124
239
}),
125
240
)
126
.child(
127
h_flex().flex_1().min_w_0().child(date_picker_button(
128
&self.state,
129
span.title(start),
130
start,
131
span.days(),
132
if span == CalendarSpan::Month {
133
month_shown(start)
134
} else {
135
start
136
},
137
)),
138
)
241
.child(h_flex().flex_1().min_w_0().child(date_picker_button(
242
&self.state,
243
span.title(start),
244
start,
245
span.days(),
246
if span == CalendarSpan::Month {
247
month_shown(start)
248
} else {
249
start
250
},
251
)))
139
252
.child(
140
253
Button::new("calendar-span")
141
254
.small()
@@ -240,7 +353,12 @@ impl CalendarView {
240
353
}))
241
354
}
242
355
243
fn all_day_row(&self, days: &[WeekDay], events: &[CalendarEvent]) -> Option<Div> {
356
fn all_day_row(
357
&self,
358
days: &[WeekDay],
359
events: &[CalendarEvent],
360
send_response: bool,
361
) -> Option<Div> {
244
362
if days.iter().all(|day| day.all_day.is_empty()) {
245
363
return None;
246
364
}
@@ -259,16 +377,36 @@ impl CalendarView {
259
377
.border_l_1()
260
378
.border_color(theme::border())
261
379
.children(day.all_day.iter().map(|&index| {
380
let event = events[index].clone();
381
let open_state = self.state.clone();
382
let (menu_state, menu_event) = (self.state.clone(), event.clone());
383
// Day-qualified id: multi-day all-day chips share object_id.
262
384
div()
385
.id(SharedString::from(format!(
386
"calendar-all-day-{}-{}",
387
event.object_id, day.date
388
)))
263
389
.h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))
264
390
.px(px(6.))
265
391
.flex()
266
392
.items_center()
267
393
.rounded(px(4.))
268
.bg(event_fill(event_look(&events[index])))
394
.bg(event_fill(event_look(&event)))
269
395
.text_size(px(12.))
270
396
.truncate()
271
.child(event_title(&events[index]))
397
.cursor_pointer()
398
.child(event_title(&event))
399
.on_click(move |_, window, cx| {
400
open_calendar_event(
401
open_state.clone(),
402
event.clone(),
403
window,
404
cx,
405
);
406
})
407
.context_menu(move |menu, _, _| {
408
event_menu(menu, &menu_state, &menu_event, send_response)
409
})
272
410
}))
273
411
})),
274
412
)
@@ -278,7 +416,7 @@ impl CalendarView {
278
416
&self,
279
417
block: &WeekBlock,
280
418
event: &CalendarEvent,
281
now: DateTime<Utc>,
419
day: NaiveDate,
282
420
send_response: bool,
283
421
) -> impl IntoElement {
284
422
let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;
@@ -289,11 +427,10 @@ impl CalendarView {
289
427
let compact = height < 36.;
290
428
let small = height < SMALL_TITLE_HEIGHT;
291
429
let look = event_look(event);
292
let can_join = event.online
293
&& !event.cancelled
294
&& event.join_url.is_some()
295
&& join_available(event.start, event.end, now);
296
let (open_state, thread_id) = (self.state.clone(), event.thread_id.clone());
430
// Join on the block whenever a Teams link exists (same as detail dialog).
431
let can_join = event.online && !event.cancelled && event.join_url.is_some();
432
let open_state = self.state.clone();
433
let open_event = event.clone();
297
434
let (menu_state, menu_event) = (self.state.clone(), event.clone());
298
435
let (join_state, join_url, subject) = (
299
436
self.state.clone(),
@@ -304,10 +441,11 @@ impl CalendarView {
304
441
EventLook::Busy => (theme::text(), theme::text_soft()),
305
442
EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),
306
443
};
444
// Day-qualified id: overnight / multi-day spans reuse object_id per column.
307
445
div()
308
446
.id(SharedString::from(format!(
309
"calendar-event-{}",
310
event.object_id
447
"calendar-event-{}-{}",
448
event.object_id, day
311
449
)))
312
450
.absolute()
313
451
.top(px(top))
@@ -359,12 +497,12 @@ impl CalendarView {
359
497
block.child(
360
498
div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(
361
499
Button::new(SharedString::from(format!(
362
"calendar-join-{}",
363
event.object_id
500
"calendar-join-{}-{}",
501
event.object_id, day
364
502
)))
365
503
.xsmall()
366
504
.primary()
367
.label("Join")
505
.label(tr("common.join"))
368
506
.on_click(move |_, _, cx| {
369
507
cx.stop_propagation();
370
508
join_state.update(cx, |state, cx| {
@@ -379,10 +517,8 @@ impl CalendarView {
379
517
)
380
518
}),
381
519
)
382
.on_click(move |_, _, cx| {
383
open_state.update(cx, |state, cx| {
384
state.open_meeting_chat(thread_id.as_deref(), cx)
385
});
520
.on_click(move |_, window, cx| {
521
open_calendar_event(open_state.clone(), open_event.clone(), window, cx);
386
522
})
387
523
.context_menu(move |menu, _, _| {
388
524
event_menu(menu, &menu_state, &menu_event, send_response)
@@ -396,6 +532,7 @@ impl CalendarView {
396
532
today: NaiveDate,
397
533
now: DateTime<Utc>,
398
534
send_response: bool,
535
cx: &mut Context<Self>,
399
536
) -> impl IntoElement {
400
537
let total_height = 24. * HOUR_HEIGHT;
401
538
let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");
@@ -409,6 +546,7 @@ impl CalendarView {
409
546
.min_h_0()
410
547
.overflow_y_scroll()
411
548
.track_scroll(&self.scroll)
549
.on_scroll_wheel(cx.listener(Self::on_grid_scroll_wheel))
412
550
.child(
413
551
h_flex()
414
552
.h(px(total_height))
@@ -457,7 +595,7 @@ impl CalendarView {
457
595
self.event_block(
458
596
block,
459
597
&events[block.event_index],
460
now,
598
day.date,
461
599
send_response,
462
600
)
463
601
}))
@@ -566,21 +704,40 @@ fn status_bar(look: EventLook) -> Option<Div> {
566
704
}
567
705
568
706
fn event_title(event: &CalendarEvent) -> String {
569
if event.cancelled {
707
let subject = if event.cancelled {
570
708
format!("{CANCELED_PREFIX}{}", event.subject)
571
709
} else {
572
710
event.subject.clone()
711
};
712
let label = source_label(event);
713
if label.is_empty() {
714
subject
715
} else {
716
format!("{subject} · {label}")
717
}
718
}
719
720
fn source_label(event: &CalendarEvent) -> String {
721
let mut sources = event.sources.clone();
722
if sources.is_empty() {
723
sources.push(event.source);
724
}
725
sources.sort_by_key(|source| source.label());
726
sources.dedup();
727
if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {
728
return String::new();
573
729
}
730
sources
731
.iter()
732
.map(|source| source.label())
733
.collect::<Vec<_>>()
734
.join("+")
574
735
}
575
736
576
737
impl Render for CalendarView {
577
738
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
578
739
let compact = f32::from(window.viewport_size().width) < COMPACT_HEADER_WIDTH;
579
if !self.scrolled_to_morning {
580
self.scrolled_to_morning = true;
581
self.scroll
582
.set_offset(point(px(0.), px(-FIRST_VISIBLE_HOUR * HOUR_HEIGHT)));
583
}
740
self.sync_follow_from_state(window, cx);
584
741
let state = self.state.read(cx);
585
742
let start = state.calendar_start();
586
743
let events = state.calendar_week.events.clone();
@@ -590,7 +747,8 @@ impl Render for CalendarView {
590
747
let days = week_days(&events, start, span.days(), offset);
591
748
let today = Local::now().date_naive();
592
749
let now = Utc::now();
593
v_flex()
750
let show_picker = !compact;
751
h_flex()
594
752
.debug_selector(|| "shell/islands/calendar".into())
595
753
.flex_1()
596
754
.w_full()
@@ -599,17 +757,33 @@ impl Render for CalendarView {
599
757
.rounded(px(10.))
600
758
.bg(theme::surface())
601
759
.overflow_hidden()
602
.child(self.header(start, span, compact))
603
.children(meeting_proposal_cards(cx))
604
.map(|calendar| {
605
if span == CalendarSpan::Month {
606
calendar.child(month_grid(&self.state, start, &days, &events, today, offset))
607
} else {
608
calendar
609
.child(self.day_headers(&days, today))
610
.children(self.all_day_row(&days, &events))
611
.child(self.grid(&days, &events, today, now, send_response))
612
}
760
.when(show_picker, |row| {
761
row.child(calendar_picker::render(&self.state, cx))
613
762
})
763
.child(
764
v_flex()
765
.flex_1()
766
.min_w_0()
767
.h_full()
768
.child(self.header(start, span, compact))
769
.children(meeting_proposal_cards(cx))
770
.map(|calendar| {
771
if span == CalendarSpan::Month {
772
calendar.child(month_grid(
773
&self.state,
774
start,
775
&days,
776
&events,
777
today,
778
offset,
779
))
780
} else {
781
calendar
782
.child(self.day_headers(&days, today))
783
.children(self.all_day_row(&days, &events, send_response))
784
.child(self.grid(&days, &events, today, now, send_response, cx))
785
}
786
}),
787
)
614
788
}
615
789
}
@@ -1,3 +1,5 @@1
use std::time::Duration;2
1
use app_base::format::{self, clock_format};3
use app_base::format::{self, clock_format};2
use chatsvc::{CalendarEvent, ResponseType, join_info_text};4
use chatsvc::{CalendarEvent, ResponseType, join_info_text};3
use chrono::{DateTime, Local, NaiveDate, Offset, Timelike, Utc};5
use chrono::{DateTime, Local, NaiveDate, Offset, Timelike, Utc};@@ -10,13 +12,20 @@ use gpui_kit::prelude::FluentBuilder as _;10
use gpui_kit::*;12
use gpui_kit::*;11
13
12
use super::calendar_date_picker::date_picker_button;14
use super::calendar_date_picker::date_picker_button;15
use super::calendar_event_dialog::open_calendar_event;13
use super::calendar_month::month_grid;16
use super::calendar_month::month_grid;14
use super::meeting_proposal_card::meeting_proposal_cards;17
use super::calendar_picker;15
use super::rsvp_menu::rsvp_menu;16
use super::join_dialog::open_join_with_id;18
use super::join_dialog::open_join_with_id;19
use super::meeting_proposal_card::meeting_proposal_cards;17
use super::new_meeting_dialog::open_new_meeting;20
use super::new_meeting_dialog::open_new_meeting;21
use super::rsvp_menu::rsvp_menu;22
use super::scroll_edge::scroll_offset;23
use crate::i18n::tr;18
use crate::app_state::AppState;24
use crate::app_state::AppState;19
use crate::call::join_available;25
use crate::call::calendar_now::{26
DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,27
now_scroll_offset_y, offset_differs, shows_hour_grid,28
};20
use crate::call::week_grid::{29
use crate::call::week_grid::{21
CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,30
CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,22
};31
};@@ -30,7 +39,6 @@ const HEADER_HEIGHT: f32 = 52.;30
const DAY_HEADER_HEIGHT: f32 = 56.;39
const DAY_HEADER_HEIGHT: f32 = 56.;31
const ALL_DAY_HEIGHT: f32 = 26.;40
const ALL_DAY_HEIGHT: f32 = 26.;32
const BLOCK_GAP: f32 = 2.;41
const BLOCK_GAP: f32 = 2.;33
const FIRST_VISIBLE_HOUR: f32 = 8.;34
const CANCELED_PREFIX: &str = "Canceled: ";42
const CANCELED_PREFIX: &str = "Canceled: ";35
const COPY_JOIN_INFO: &str = "Copy join info";43
const COPY_JOIN_INFO: &str = "Copy join info";36
const COMPACT_HEADER_WIDTH: f32 = 960.;44
const COMPACT_HEADER_WIDTH: f32 = 960.;@@ -42,11 +50,17 @@ const HATCH_GAP: f32 = 2.5;42
const SMALL_TITLE_HEIGHT: f32 = 20.;50
const SMALL_TITLE_HEIGHT: f32 = 20.;43
const TODAY_MARK_HEIGHT: f32 = 3.;51
const TODAY_MARK_HEIGHT: f32 = 3.;44
const NOW_DOT_SIZE: f32 = 8.;52
const NOW_DOT_SIZE: f32 = 8.;53
const CLOCK_TICK: Duration = Duration::from_secs(30);54
const CHROME_HEIGHT: f32 = HEADER_HEIGHT + DAY_HEADER_HEIGHT + ALL_DAY_HEIGHT;45
55
46
pub struct CalendarView {56
pub struct CalendarView {47
state: Entity<AppState>,57
state: Entity<AppState>,48
scroll: ScrollHandle,58
scroll: ScrollHandle,49
scrolled_to_morning: bool,59
follow_now: FollowNow,60
seen_scroll_to_now: u64,61
last_programmatic_offset: f32,62
skip_manual_check: bool,63
clock_running: bool,50
_observation: Subscription,64
_observation: Subscription,51
_agent_observation: Option<Subscription>,65
_agent_observation: Option<Subscription>,52
}66
}@@ -58,12 +72,113 @@ impl CalendarView {58
CalendarView {72
CalendarView {59
state,73
state,60
scroll: ScrollHandle::new(),74
scroll: ScrollHandle::new(),61
scrolled_to_morning: false,75
follow_now: FollowNow { active: true },76
seen_scroll_to_now: 0,77
last_programmatic_offset: 0.,78
skip_manual_check: false,79
clock_running: false,62
_observation: observation,80
_observation: observation,63
_agent_observation: agent_observation,81
_agent_observation: agent_observation,64
}82
}65
}83
}66
84
85
fn grid_viewport_height(window: &Window) -> f32 {86
(f32::from(window.viewport_size().height) - CHROME_HEIGHT).max(DEFAULT_GRID_VIEWPORT * 0.5)87
}88
89
fn align_scroll_to_now(&mut self, window: &Window) {90
let local = Local::now();91
let offset = now_scroll_offset_y(92
local.hour(),93
local.minute(),94
HOUR_HEIGHT,95
Self::grid_viewport_height(window),96
NOW_BIAS_FRACTION,97
);98
self.scroll.set_offset(point(px(0.), px(offset)));99
self.last_programmatic_offset = offset;100
self.skip_manual_check = true;101
}102
103
fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {104
let (scroll_to_now, span, today_visible) = {105
let state = self.state.read(cx);106
let start = state.calendar_start();107
let today = Local::now().date_naive();108
let today_visible = start <= today109
&& today < start + chrono::Duration::days(state.calendar_week.span.days());110
(111
state.calendar_scroll_to_now,112
state.calendar_week.span,113
today_visible,114
)115
};116
if !shows_hour_grid(span) {117
self.stop_clock();118
return;119
}120
self.ensure_clock(cx);121
if scroll_to_now != self.seen_scroll_to_now {122
self.seen_scroll_to_now = scroll_to_now;123
self.follow_now.request_align();124
}125
if self.skip_manual_check {126
self.skip_manual_check = false;127
} else if self.follow_now.active128
&& offset_differs(129
f32::from(scroll_offset(&self.scroll).y),130
self.last_programmatic_offset,131
MANUAL_SCROLL_EPSILON,132
)133
{134
self.follow_now.note_manual_scroll();135
}136
if self.follow_now.should_follow(today_visible) {137
self.align_scroll_to_now(window);138
}139
}140
141
fn ensure_clock(&mut self, cx: &mut Context<Self>) {142
if self.clock_running {143
return;144
}145
self.clock_running = true;146
cx.spawn(async move |this, cx| {147
loop {148
cx.background_executor().timer(CLOCK_TICK).await;149
let keep = this150
.update(cx, |view, cx| {151
let span = view.state.read(cx).calendar_week.span;152
if !shows_hour_grid(span) {153
view.clock_running = false;154
return false;155
}156
cx.notify();157
true158
})159
.unwrap_or(false);160
if !keep {161
break;162
}163
}164
})165
.detach();166
}167
168
fn stop_clock(&mut self) {169
self.clock_running = false;170
}171
172
fn on_grid_scroll_wheel(173
&mut self,174
_event: &ScrollWheelEvent,175
_window: &mut Window,176
cx: &mut Context<Self>,177
) {178
self.follow_now.note_manual_scroll();179
cx.notify();180
}181
67
fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {182
fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {68
let span_state = self.state.clone();183
let span_state = self.state.clone();69
let label = |text: &'static str| (!compact).then_some(text);184
let label = |text: &'static str| (!compact).then_some(text);@@ -123,19 +238,17 @@ impl CalendarView {123
forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))238
forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))124
}),239
}),125
)240
)126
.child(241
.child(h_flex().flex_1().min_w_0().child(date_picker_button(127
h_flex().flex_1().min_w_0().child(date_picker_button(242
&self.state,128
&self.state,243
span.title(start),129
span.title(start),244
start,130
start,245
span.days(),131
span.days(),246
if span == CalendarSpan::Month {132
if span == CalendarSpan::Month {247
month_shown(start)133
month_shown(start)248
} else {134
} else {249
start135
start250
},136
},251
)))137
)),138
)139
.child(252
.child(140
Button::new("calendar-span")253
Button::new("calendar-span")141
.small()254
.small()@@ -240,7 +353,12 @@ impl CalendarView {240
}))353
}))241
}354
}242
355
243
fn all_day_row(&self, days: &[WeekDay], events: &[CalendarEvent]) -> Option<Div> {356
fn all_day_row(357
&self,358
days: &[WeekDay],359
events: &[CalendarEvent],360
send_response: bool,361
) -> Option<Div> {244
if days.iter().all(|day| day.all_day.is_empty()) {362
if days.iter().all(|day| day.all_day.is_empty()) {245
return None;363
return None;246
}364
}@@ -259,16 +377,36 @@ impl CalendarView {259
.border_l_1()377
.border_l_1()260
.border_color(theme::border())378
.border_color(theme::border())261
.children(day.all_day.iter().map(|&index| {379
.children(day.all_day.iter().map(|&index| {380
let event = events[index].clone();381
let open_state = self.state.clone();382
let (menu_state, menu_event) = (self.state.clone(), event.clone());383
// Day-qualified id: multi-day all-day chips share object_id.262
div()384
div()385
.id(SharedString::from(format!(386
"calendar-all-day-{}-{}",387
event.object_id, day.date388
)))263
.h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))389
.h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))264
.px(px(6.))390
.px(px(6.))265
.flex()391
.flex()266
.items_center()392
.items_center()267
.rounded(px(4.))393
.rounded(px(4.))268
.bg(event_fill(event_look(&events[index])))394
.bg(event_fill(event_look(&event)))269
.text_size(px(12.))395
.text_size(px(12.))270
.truncate()396
.truncate()271
.child(event_title(&events[index]))397
.cursor_pointer()398
.child(event_title(&event))399
.on_click(move |_, window, cx| {400
open_calendar_event(401
open_state.clone(),402
event.clone(),403
window,404
cx,405
);406
})407
.context_menu(move |menu, _, _| {408
event_menu(menu, &menu_state, &menu_event, send_response)409
})272
}))410
}))273
})),411
})),274
)412
)@@ -278,7 +416,7 @@ impl CalendarView {278
&self,416
&self,279
block: &WeekBlock,417
block: &WeekBlock,280
event: &CalendarEvent,418
event: &CalendarEvent,281
now: DateTime<Utc>,419
day: NaiveDate,282
send_response: bool,420
send_response: bool,283
) -> impl IntoElement {421
) -> impl IntoElement {284
let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;422
let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;@@ -289,11 +427,10 @@ impl CalendarView {289
let compact = height < 36.;427
let compact = height < 36.;290
let small = height < SMALL_TITLE_HEIGHT;428
let small = height < SMALL_TITLE_HEIGHT;291
let look = event_look(event);429
let look = event_look(event);292
let can_join = event.online430
// Join on the block whenever a Teams link exists (same as detail dialog).293
&& !event.cancelled431
let can_join = event.online && !event.cancelled && event.join_url.is_some();294
&& event.join_url.is_some()432
let open_state = self.state.clone();295
&& join_available(event.start, event.end, now);433
let open_event = event.clone();296
let (open_state, thread_id) = (self.state.clone(), event.thread_id.clone());297
let (menu_state, menu_event) = (self.state.clone(), event.clone());434
let (menu_state, menu_event) = (self.state.clone(), event.clone());298
let (join_state, join_url, subject) = (435
let (join_state, join_url, subject) = (299
self.state.clone(),436
self.state.clone(),@@ -304,10 +441,11 @@ impl CalendarView {304
EventLook::Busy => (theme::text(), theme::text_soft()),441
EventLook::Busy => (theme::text(), theme::text_soft()),305
EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),442
EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),306
};443
};444
// Day-qualified id: overnight / multi-day spans reuse object_id per column.307
div()445
div()308
.id(SharedString::from(format!(446
.id(SharedString::from(format!(309
"calendar-event-{}",447
"calendar-event-{}-{}",310
event.object_id448
event.object_id, day311
)))449
)))312
.absolute()450
.absolute()313
.top(px(top))451
.top(px(top))@@ -359,12 +497,12 @@ impl CalendarView {359
block.child(497
block.child(360
div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(498
div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(361
Button::new(SharedString::from(format!(499
Button::new(SharedString::from(format!(362
"calendar-join-{}",500
"calendar-join-{}-{}",363
event.object_id501
event.object_id, day364
)))502
)))365
.xsmall()503
.xsmall()366
.primary()504
.primary()367
.label("Join")505
.label(tr("common.join"))368
.on_click(move |_, _, cx| {506
.on_click(move |_, _, cx| {369
cx.stop_propagation();507
cx.stop_propagation();370
join_state.update(cx, |state, cx| {508
join_state.update(cx, |state, cx| {@@ -379,10 +517,8 @@ impl CalendarView {379
)517
)380
}),518
}),381
)519
)382
.on_click(move |_, _, cx| {520
.on_click(move |_, window, cx| {383
open_state.update(cx, |state, cx| {521
open_calendar_event(open_state.clone(), open_event.clone(), window, cx);384
state.open_meeting_chat(thread_id.as_deref(), cx)385
});386
})522
})387
.context_menu(move |menu, _, _| {523
.context_menu(move |menu, _, _| {388
event_menu(menu, &menu_state, &menu_event, send_response)524
event_menu(menu, &menu_state, &menu_event, send_response)@@ -396,6 +532,7 @@ impl CalendarView {396
today: NaiveDate,532
today: NaiveDate,397
now: DateTime<Utc>,533
now: DateTime<Utc>,398
send_response: bool,534
send_response: bool,535
cx: &mut Context<Self>,399
) -> impl IntoElement {536
) -> impl IntoElement {400
let total_height = 24. * HOUR_HEIGHT;537
let total_height = 24. * HOUR_HEIGHT;401
let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");538
let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");@@ -409,6 +546,7 @@ impl CalendarView {409
.min_h_0()546
.min_h_0()410
.overflow_y_scroll()547
.overflow_y_scroll()411
.track_scroll(&self.scroll)548
.track_scroll(&self.scroll)549
.on_scroll_wheel(cx.listener(Self::on_grid_scroll_wheel))412
.child(550
.child(413
h_flex()551
h_flex()414
.h(px(total_height))552
.h(px(total_height))@@ -457,7 +595,7 @@ impl CalendarView {457
self.event_block(595
self.event_block(458
block,596
block,459
&events[block.event_index],597
&events[block.event_index],460
now,598
day.date,461
send_response,599
send_response,462
)600
)463
}))601
}))@@ -566,21 +704,40 @@ fn status_bar(look: EventLook) -> Option<Div> {566
}704
}567
705
568
fn event_title(event: &CalendarEvent) -> String {706
fn event_title(event: &CalendarEvent) -> String {569
if event.cancelled {707
let subject = if event.cancelled {570
format!("{CANCELED_PREFIX}{}", event.subject)708
format!("{CANCELED_PREFIX}{}", event.subject)571
} else {709
} else {572
event.subject.clone()710
event.subject.clone()711
};712
let label = source_label(event);713
if label.is_empty() {714
subject715
} else {716
format!("{subject} · {label}")717
}718
}719
720
fn source_label(event: &CalendarEvent) -> String {721
let mut sources = event.sources.clone();722
if sources.is_empty() {723
sources.push(event.source);724
}725
sources.sort_by_key(|source| source.label());726
sources.dedup();727
if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {728
return String::new();573
}729
}730
sources731
.iter()732
.map(|source| source.label())733
.collect::<Vec<_>>()734
.join("+")574
}735
}575
736
576
impl Render for CalendarView {737
impl Render for CalendarView {577
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {738
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {578
let compact = f32::from(window.viewport_size().width) < COMPACT_HEADER_WIDTH;739
let compact = f32::from(window.viewport_size().width) < COMPACT_HEADER_WIDTH;579
if !self.scrolled_to_morning {740
self.sync_follow_from_state(window, cx);580
self.scrolled_to_morning = true;581
self.scroll582
.set_offset(point(px(0.), px(-FIRST_VISIBLE_HOUR * HOUR_HEIGHT)));583
}584
let state = self.state.read(cx);741
let state = self.state.read(cx);585
let start = state.calendar_start();742
let start = state.calendar_start();586
let events = state.calendar_week.events.clone();743
let events = state.calendar_week.events.clone();@@ -590,7 +747,8 @@ impl Render for CalendarView {590
let days = week_days(&events, start, span.days(), offset);747
let days = week_days(&events, start, span.days(), offset);591
let today = Local::now().date_naive();748
let today = Local::now().date_naive();592
let now = Utc::now();749
let now = Utc::now();593
v_flex()750
let show_picker = !compact;751
h_flex()594
.debug_selector(|| "shell/islands/calendar".into())752
.debug_selector(|| "shell/islands/calendar".into())595
.flex_1()753
.flex_1()596
.w_full()754
.w_full()@@ -599,17 +757,33 @@ impl Render for CalendarView {599
.rounded(px(10.))757
.rounded(px(10.))600
.bg(theme::surface())758
.bg(theme::surface())601
.overflow_hidden()759
.overflow_hidden()602
.child(self.header(start, span, compact))760
.when(show_picker, |row| {603
.children(meeting_proposal_cards(cx))761
row.child(calendar_picker::render(&self.state, cx))604
.map(|calendar| {605
if span == CalendarSpan::Month {606
calendar.child(month_grid(&self.state, start, &days, &events, today, offset))607
} else {608
calendar609
.child(self.day_headers(&days, today))610
.children(self.all_day_row(&days, &events))611
.child(self.grid(&days, &events, today, now, send_response))612
}613
})762
})763
.child(764
v_flex()765
.flex_1()766
.min_w_0()767
.h_full()768
.child(self.header(start, span, compact))769
.children(meeting_proposal_cards(cx))770
.map(|calendar| {771
if span == CalendarSpan::Month {772
calendar.child(month_grid(773
&self.state,774
start,775
&days,776
&events,777
today,778
offset,779
))780
} else {781
calendar782
.child(self.day_headers(&days, today))783
.children(self.all_day_row(&days, &events, send_response))784
.child(self.grid(&days, &events, today, now, send_response, cx))785
}786
}),787
)614
}788
}615
}789
}@@ -1,58 +1,60 @@
1
1
pub mod actions;
2
2
pub mod activity_panel;
3
3
pub mod adaptive_card;
4
pub mod announcement_banner;
5
4
pub mod add_people_dialog;
5
pub mod announcement_banner;
6
6
pub mod attachment_tray;
7
7
pub mod attachments;
8
8
pub mod avatar;
9
pub mod calendar_date_picker;
10
pub mod calendar_event_dialog;
11
pub mod calendar_month;
12
pub mod calendar_picker;
13
pub mod calendar_view;
9
14
pub mod call_card;
10
pub mod call_notice;
11
15
pub mod call_control_fold;
12
pub mod call_end_view;
13
16
pub mod call_controls;
17
pub mod call_end_view;
14
18
pub mod call_extras;
15
19
pub mod call_health;
16
20
pub mod call_layouts;
17
21
pub mod call_mini_window;
22
pub mod call_notice;
18
23
pub mod call_organizer;
19
24
pub mod call_people;
20
25
pub mod call_pop_out;
21
pub mod call_share_gallery;
22
26
pub mod call_record;
27
pub mod call_share_gallery;
23
28
pub mod call_stage;
24
29
pub mod call_transcript;
25
30
pub mod call_view;
26
31
pub mod call_window;
27
32
pub mod call_toolbar;
28
33
pub mod call_view_menu;
29
pub mod calendar_date_picker;
30
pub mod calendar_month;
31
pub mod calendar_view;
32
34
pub mod calls_page;
33
mod rsvp_menu;
34
35
pub mod card_carousel;
35
#[cfg(test)]
36
mod card_input_tests;
37
36
pub mod card_code_block;
38
37
pub mod card_icon;
39
38
pub mod card_input;
39
#[cfg(test)]
40
mod card_input_tests;
40
41
pub mod card_media;
41
42
pub mod card_table;
42
43
pub mod card_widgets;
44
pub mod channel_admin_dialogs;
43
45
pub mod chat_members;
46
mod chat_menu;
44
47
pub mod chat_pop_out;
45
48
pub mod composer;
46
49
pub mod connection_banner;
47
50
pub mod conversation;
48
pub mod channel_admin_dialogs;
49
51
pub mod create_channel_dialog;
50
52
pub mod customize_reactions;
51
53
pub mod dialog_overlay;
52
54
pub mod emoji_popup;
55
pub mod find_panel;
53
56
pub mod format_toolbar;
54
57
pub mod forward_dialog;
55
pub mod find_panel;
56
58
pub mod fun_picker;
57
59
pub mod group_name;
58
60
pub mod image_memory;
@@ -60,14 +62,15 @@ pub mod image_menu;
60
62
pub mod image_viewer;
61
63
pub mod join_dialog;
62
64
pub mod jumbo_emoji;
65
mod last_views;
63
66
pub mod link_preview;
64
67
pub mod message_actions;
65
68
pub mod message_appear;
66
69
pub mod message_context_menu;
67
70
pub mod message_row;
68
71
pub mod new_chat;
69
pub mod notice_toast;
70
72
pub mod new_meeting_dialog;
73
pub mod notice_toast;
71
74
pub mod pin_banner;
72
75
#[cfg(test)]
73
76
mod popup_tooltip_tests;
@@ -76,23 +79,22 @@ pub mod prejoin_view;
76
79
pub mod profile_card;
77
80
pub mod proposal_card;
78
81
pub mod meeting_proposal_card;
82
pub mod quick_view_pane;
79
83
pub mod rail;
80
84
pub mod reaction_picker;
81
85
pub mod reaction_pills;
82
86
pub mod recap_tab;
87
mod rsvp_menu;
83
88
pub mod manage_team_page;
84
pub mod quick_view_pane;
85
89
pub mod scheduled_toolbar;
86
90
pub mod section_dialog;
87
91
pub mod share_bar;
88
92
pub mod shared_tab;
89
pub mod skin_tone_choices;
90
93
pub mod shell;
91
94
pub mod shortcuts;
92
95
pub mod shortcuts_dialog;
93
mod chat_menu;
94
mod last_views;
95
96
pub mod sidebar;
97
pub mod skin_tone_choices;
96
98
pub mod splash;
97
99
pub mod status_menu;
98
100
pub mod status_message_dialog;
@@ -1,58 +1,60 @@1
pub mod actions;1
pub mod actions;2
pub mod activity_panel;2
pub mod activity_panel;3
pub mod adaptive_card;3
pub mod adaptive_card;4
pub mod announcement_banner;5
pub mod add_people_dialog;4
pub mod add_people_dialog;5
pub mod announcement_banner;6
pub mod attachment_tray;6
pub mod attachment_tray;7
pub mod attachments;7
pub mod attachments;8
pub mod avatar;8
pub mod avatar;9
pub mod calendar_date_picker;10
pub mod calendar_event_dialog;11
pub mod calendar_month;12
pub mod calendar_picker;13
pub mod calendar_view;9
pub mod call_card;14
pub mod call_card;10
pub mod call_notice;11
pub mod call_control_fold;15
pub mod call_control_fold;12
pub mod call_end_view;13
pub mod call_controls;16
pub mod call_controls;17
pub mod call_end_view;14
pub mod call_extras;18
pub mod call_extras;15
pub mod call_health;19
pub mod call_health;16
pub mod call_layouts;20
pub mod call_layouts;17
pub mod call_mini_window;21
pub mod call_mini_window;22
pub mod call_notice;18
pub mod call_organizer;23
pub mod call_organizer;19
pub mod call_people;24
pub mod call_people;20
pub mod call_pop_out;25
pub mod call_pop_out;21
pub mod call_share_gallery;22
pub mod call_record;26
pub mod call_record;27
pub mod call_share_gallery;23
pub mod call_stage;28
pub mod call_stage;24
pub mod call_transcript;29
pub mod call_transcript;25
pub mod call_view;30
pub mod call_view;26
pub mod call_window;31
pub mod call_window;27
pub mod call_toolbar;32
pub mod call_toolbar;28
pub mod call_view_menu;33
pub mod call_view_menu;29
pub mod calendar_date_picker;30
pub mod calendar_month;31
pub mod calendar_view;32
pub mod calls_page;34
pub mod calls_page;33
mod rsvp_menu;34
pub mod card_carousel;35
pub mod card_carousel;35
#[cfg(test)]36
mod card_input_tests;37
pub mod card_code_block;36
pub mod card_code_block;38
pub mod card_icon;37
pub mod card_icon;39
pub mod card_input;38
pub mod card_input;39
#[cfg(test)]40
mod card_input_tests;40
pub mod card_media;41
pub mod card_media;41
pub mod card_table;42
pub mod card_table;42
pub mod card_widgets;43
pub mod card_widgets;44
pub mod channel_admin_dialogs;43
pub mod chat_members;45
pub mod chat_members;46
mod chat_menu;44
pub mod chat_pop_out;47
pub mod chat_pop_out;45
pub mod composer;48
pub mod composer;46
pub mod connection_banner;49
pub mod connection_banner;47
pub mod conversation;50
pub mod conversation;48
pub mod channel_admin_dialogs;49
pub mod create_channel_dialog;51
pub mod create_channel_dialog;50
pub mod customize_reactions;52
pub mod customize_reactions;51
pub mod dialog_overlay;53
pub mod dialog_overlay;52
pub mod emoji_popup;54
pub mod emoji_popup;55
pub mod find_panel;53
pub mod format_toolbar;56
pub mod format_toolbar;54
pub mod forward_dialog;57
pub mod forward_dialog;55
pub mod find_panel;56
pub mod fun_picker;58
pub mod fun_picker;57
pub mod group_name;59
pub mod group_name;58
pub mod image_memory;60
pub mod image_memory;@@ -60,14 +62,15 @@ pub mod image_menu;60
pub mod image_viewer;62
pub mod image_viewer;61
pub mod join_dialog;63
pub mod join_dialog;62
pub mod jumbo_emoji;64
pub mod jumbo_emoji;65
mod last_views;63
pub mod link_preview;66
pub mod link_preview;64
pub mod message_actions;67
pub mod message_actions;65
pub mod message_appear;68
pub mod message_appear;66
pub mod message_context_menu;69
pub mod message_context_menu;67
pub mod message_row;70
pub mod message_row;68
pub mod new_chat;71
pub mod new_chat;69
pub mod notice_toast;70
pub mod new_meeting_dialog;72
pub mod new_meeting_dialog;73
pub mod notice_toast;71
pub mod pin_banner;74
pub mod pin_banner;72
#[cfg(test)]75
#[cfg(test)]73
mod popup_tooltip_tests;76
mod popup_tooltip_tests;@@ -76,23 +79,22 @@ pub mod prejoin_view;76
pub mod profile_card;79
pub mod profile_card;77
pub mod proposal_card;80
pub mod proposal_card;78
pub mod meeting_proposal_card;81
pub mod meeting_proposal_card;82
pub mod quick_view_pane;79
pub mod rail;83
pub mod rail;80
pub mod reaction_picker;84
pub mod reaction_picker;81
pub mod reaction_pills;85
pub mod reaction_pills;82
pub mod recap_tab;86
pub mod recap_tab;87
mod rsvp_menu;83
pub mod manage_team_page;88
pub mod manage_team_page;84
pub mod quick_view_pane;85
pub mod scheduled_toolbar;89
pub mod scheduled_toolbar;86
pub mod section_dialog;90
pub mod section_dialog;87
pub mod share_bar;91
pub mod share_bar;88
pub mod shared_tab;92
pub mod shared_tab;89
pub mod skin_tone_choices;90
pub mod shell;93
pub mod shell;91
pub mod shortcuts;94
pub mod shortcuts;92
pub mod shortcuts_dialog;95
pub mod shortcuts_dialog;93
mod chat_menu;94
mod last_views;95
pub mod sidebar;96
pub mod sidebar;97
pub mod skin_tone_choices;96
pub mod splash;98
pub mod splash;97
pub mod status_menu;99
pub mod status_menu;98
pub mod status_message_dialog;100
pub mod status_message_dialog;@@ -10,14 +10,17 @@ base64.workspace = true
10
10
chrono.workspace = true
11
11
futures-util.workspace = true
12
12
percent-encoding.workspace = true
13
rand = "0.9"
14
reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }
13
15
serde.workspace = true
14
16
serde_json.workspace = true
15
17
session.workspace = true
18
sha2 = "0.10"
16
19
thiserror.workspace = true
17
20
tokio.workspace = true
18
21
tokio-tungstenite = { workspace = true, features = ["rustls-tls-native-roots"] }
22
url.workspace = true
19
23
uuid.workspace = true
20
24
21
25
[dev-dependencies]
22
26
tokio = { workspace = true }
23
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
@@ -10,14 +10,17 @@ base64.workspace = true10
chrono.workspace = true10
chrono.workspace = true11
futures-util.workspace = true11
futures-util.workspace = true12
percent-encoding.workspace = true12
percent-encoding.workspace = true13
rand = "0.9"14
reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "query", "form"] }13
serde.workspace = true15
serde.workspace = true14
serde_json.workspace = true16
serde_json.workspace = true15
session.workspace = true17
session.workspace = true18
sha2 = "0.10"16
thiserror.workspace = true19
thiserror.workspace = true17
tokio.workspace = true20
tokio.workspace = true18
tokio-tungstenite = { workspace = true, features = ["rustls-tls-native-roots"] }21
tokio-tungstenite = { workspace = true, features = ["rustls-tls-native-roots"] }22
url.workspace = true19
uuid.workspace = true23
uuid.workspace = true20
24
21
[dev-dependencies]25
[dev-dependencies]22
tokio = { workspace = true }26
tokio = { workspace = true }23
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }@@ -13,7 +13,8 @@ pub use availability::{BusyTime, PersonSchedule, parse_schedules};
13
13
14
14
pub use reminders::{Reminder, parse_reminders};
15
15
pub use schedule::{
16
Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, parse_created_event,
16
Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, new_event_body_with_join,
17
parse_created_event,
17
18
};
18
19
19
20
const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";
@@ -39,6 +40,22 @@ pub enum ShowAs {
39
40
WorkingElsewhere,
40
41
}
41
42
43
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44
pub enum CalendarSource {
45
#[default]
46
Outlook,
47
Google,
48
}
49
50
impl CalendarSource {
51
pub fn label(self) -> &'static str {
52
match self {
53
CalendarSource::Outlook => "Outlook",
54
CalendarSource::Google => "Google",
55
}
56
}
57
}
58
42
59
#[derive(Debug, Clone, PartialEq, Eq)]
43
60
pub struct CalendarEvent {
44
61
pub object_id: String,
@@ -56,6 +73,49 @@ pub struct CalendarEvent {
56
73
pub response: ResponseType,
57
74
pub show_as: ShowAs,
58
75
pub dial_in: Option<DialIn>,
76
pub source: CalendarSource,
77
pub account_id: Option<String>,
78
pub calendar_id: Option<String>,
79
/// When a merge collapsed duplicates, every contributing source.
80
pub sources: Vec<CalendarSource>,
81
}
82
83
impl CalendarEvent {
84
pub fn outlook_defaults() -> (CalendarSource, Option<String>, Option<String>, Vec<CalendarSource>) {
85
(
86
CalendarSource::Outlook,
87
None,
88
None,
89
vec![CalendarSource::Outlook],
90
)
91
}
92
}
93
94
impl Default for CalendarEvent {
95
fn default() -> Self {
96
let (source, account_id, calendar_id, sources) = Self::outlook_defaults();
97
CalendarEvent {
98
object_id: String::new(),
99
subject: String::new(),
100
start: DateTime::<Utc>::UNIX_EPOCH,
101
end: DateTime::<Utc>::UNIX_EPOCH,
102
all_day: false,
103
cancelled: false,
104
online: false,
105
join_url: None,
106
thread_id: None,
107
organizer_name: None,
108
organizer_address: None,
109
ical_uid: None,
110
response: ResponseType::default(),
111
show_as: ShowAs::default(),
112
dial_in: None,
113
source,
114
account_id,
115
calendar_id,
116
sources,
117
}
118
}
59
119
}
60
120
61
121
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -259,6 +319,7 @@ fn show_as(entry: &Value) -> ShowAs {
259
319
260
320
fn parse_event(entry: &Value) -> Option<CalendarEvent> {
261
321
let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));
322
let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();
262
323
Some(CalendarEvent {
263
324
object_id: text(entry, "objectId").or_else(|| text(entry, "id"))?,
264
325
subject: text(entry, "subject").unwrap_or_default(),
@@ -275,6 +336,10 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {
275
336
response: response_type(entry),
276
337
show_as: show_as(entry),
277
338
dial_in: dial_in(entry),
339
source,
340
account_id,
341
calendar_id,
342
sources,
278
343
})
279
344
}
280
345
@@ -13,7 +13,8 @@ pub use availability::{BusyTime, PersonSchedule, parse_schedules};13
13
14
pub use reminders::{Reminder, parse_reminders};14
pub use reminders::{Reminder, parse_reminders};15
pub use schedule::{15
pub use schedule::{16
Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, parse_created_event,16
Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, new_event_body_with_join,17
parse_created_event,17
};18
};18
19
19
const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";20
const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";@@ -39,6 +40,22 @@ pub enum ShowAs {39
WorkingElsewhere,40
WorkingElsewhere,40
}41
}41
42
43
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]44
pub enum CalendarSource {45
#[default]46
Outlook,47
Google,48
}49
50
impl CalendarSource {51
pub fn label(self) -> &'static str {52
match self {53
CalendarSource::Outlook => "Outlook",54
CalendarSource::Google => "Google",55
}56
}57
}58
42
#[derive(Debug, Clone, PartialEq, Eq)]59
#[derive(Debug, Clone, PartialEq, Eq)]43
pub struct CalendarEvent {60
pub struct CalendarEvent {44
pub object_id: String,61
pub object_id: String,@@ -56,6 +73,49 @@ pub struct CalendarEvent {56
pub response: ResponseType,73
pub response: ResponseType,57
pub show_as: ShowAs,74
pub show_as: ShowAs,58
pub dial_in: Option<DialIn>,75
pub dial_in: Option<DialIn>,76
pub source: CalendarSource,77
pub account_id: Option<String>,78
pub calendar_id: Option<String>,79
/// When a merge collapsed duplicates, every contributing source.80
pub sources: Vec<CalendarSource>,81
}82
83
impl CalendarEvent {84
pub fn outlook_defaults() -> (CalendarSource, Option<String>, Option<String>, Vec<CalendarSource>) {85
(86
CalendarSource::Outlook,87
None,88
None,89
vec![CalendarSource::Outlook],90
)91
}92
}93
94
impl Default for CalendarEvent {95
fn default() -> Self {96
let (source, account_id, calendar_id, sources) = Self::outlook_defaults();97
CalendarEvent {98
object_id: String::new(),99
subject: String::new(),100
start: DateTime::<Utc>::UNIX_EPOCH,101
end: DateTime::<Utc>::UNIX_EPOCH,102
all_day: false,103
cancelled: false,104
online: false,105
join_url: None,106
thread_id: None,107
organizer_name: None,108
organizer_address: None,109
ical_uid: None,110
response: ResponseType::default(),111
show_as: ShowAs::default(),112
dial_in: None,113
source,114
account_id,115
calendar_id,116
sources,117
}118
}59
}119
}60
120
61
#[derive(Debug, Clone, PartialEq, Eq)]121
#[derive(Debug, Clone, PartialEq, Eq)]@@ -259,6 +319,7 @@ fn show_as(entry: &Value) -> ShowAs {259
319
260
fn parse_event(entry: &Value) -> Option<CalendarEvent> {320
fn parse_event(entry: &Value) -> Option<CalendarEvent> {261
let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));321
let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));322
let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();262
Some(CalendarEvent {323
Some(CalendarEvent {263
object_id: text(entry, "objectId").or_else(|| text(entry, "id"))?,324
object_id: text(entry, "objectId").or_else(|| text(entry, "id"))?,264
subject: text(entry, "subject").unwrap_or_default(),325
subject: text(entry, "subject").unwrap_or_default(),@@ -275,6 +336,10 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {275
response: response_type(entry),336
response: response_type(entry),276
show_as: show_as(entry),337
show_as: show_as(entry),277
dial_in: dial_in(entry),338
dial_in: dial_in(entry),339
source,340
account_id,341
calendar_id,342
sources,278
})343
})279
}344
}280
345
@@ -157,6 +157,31 @@ pub fn new_event_body(event: &NewEvent) -> Value {
157
157
body
158
158
}
159
159
160
/// Outlook insert when the Teams join URL already exists (multi-target create).
161
pub fn new_event_body_with_join(event: &NewEvent, join_url: &str) -> Value {
162
let mut details = event.details.clone();
163
if !details.is_empty() {
164
details.push_str("\n\n");
165
}
166
details.push_str(join_url);
167
let mut body = json!({
168
"subject": event.subject,
169
"start": graph_time(event, event.local_start, event.start),
170
"end": graph_time(event, event.local_end, event.end),
171
"attendees": event.attendees.iter().map(|attendee| json!({
172
"type": "required",
173
"emailAddress": {"address": attendee.address, "name": attendee.name},
174
})).collect::<Vec<_>>(),
175
"location": {"displayName": join_url},
176
"body": {"contentType": "text", "content": details},
177
"isOnlineMeeting": false,
178
});
179
if let Some(recurrence) = recurrence(event.repeat, event.local_start) {
180
body["recurrence"] = recurrence;
181
}
182
body
183
}
184
160
185
pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> {
161
186
Some(CreatedEvent {
162
187
id: body.get("id")?.as_str()?.to_owned(),
@@ -171,8 +196,12 @@ fn events_url() -> String {
171
196
format!("{GRAPH}/v1.0/me/events")
172
197
}
173
198
199
fn event_item_url(event_id: &str) -> String {
200
format!("{}/{}", events_url(), encode(event_id))
201
}
202
174
203
fn reply_url(event_id: &str, reply: Reply) -> String {
175
format!("{}/{}/{}", events_url(), encode(event_id), reply.action())
204
format!("{}/{}", event_item_url(event_id), reply.action())
176
205
}
177
206
178
207
fn lookup_url(ical_uid: &str) -> String {
@@ -189,8 +218,27 @@ fn api_error(answer: session::ApiResponse, url: &str) -> Error {
189
218
190
219
impl<T: CardTransport> Calendar<T> {
191
220
pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {
221
self.create_event_body(event, new_event_body(event)).await
222
}
223
224
pub async fn create_event_with_join(
225
&self,
226
event: &NewEvent,
227
join_url: &str,
228
) -> Result<CreatedEvent> {
229
let mut created = self
230
.create_event_body(event, new_event_body_with_join(event, join_url))
231
.await?;
232
if created.join_url.is_none() {
233
created.join_url = Some(join_url.to_owned());
234
}
235
Ok(created)
236
}
237
238
async fn create_event_body(&self, event: &NewEvent, body: Value) -> Result<CreatedEvent> {
239
let _ = event;
192
240
let url = events_url();
193
let request = Request::with_body(Method::Post, &url, new_event_body(event));
241
let request = Request::with_body(Method::Post, &url, body);
194
242
let answer = self
195
243
.transport
196
244
.send(request, Scope::graph(CALENDARS_SCOPE))
@@ -223,6 +271,31 @@ impl<T: CardTransport> Calendar<T> {
223
271
Err(api_error(retried, &reply_url(&graph_id, reply)))
224
272
}
225
273
274
pub async fn delete_event(&self, event_id: &str, ical_uid: Option<&str>) -> Result<()> {
275
let answer = self.send_delete(event_id).await?;
276
if answer.is_success() {
277
return Ok(());
278
}
279
let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else {
280
return Err(api_error(answer, &event_item_url(event_id)));
281
};
282
let graph_id = self.graph_event_id(ical_uid).await?;
283
let retried = self.send_delete(&graph_id).await?;
284
if retried.is_success() {
285
return Ok(());
286
}
287
Err(api_error(retried, &event_item_url(&graph_id)))
288
}
289
290
async fn send_delete(&self, event_id: &str) -> Result<session::ApiResponse> {
291
self.transport
292
.send(
293
Request::delete(event_item_url(event_id)),
294
Scope::graph(CALENDARS_SCOPE),
295
)
296
.await
297
}
298
226
299
async fn send_reply(
227
300
&self,
228
301
event_id: &str,
@@ -332,6 +405,25 @@ mod tests {
332
405
}
333
406
}
334
407
408
#[test]
409
fn join_first_body_puts_link_in_location_without_online_meeting() {
410
let body = new_event_body_with_join(
411
&event(Repeat::Never),
412
"https://teams.microsoft.com/l/meetup-join/x",
413
);
414
assert_eq!(body["isOnlineMeeting"], false);
415
assert_eq!(
416
body["location"]["displayName"],
417
"https://teams.microsoft.com/l/meetup-join/x"
418
);
419
assert!(
420
body["body"]["content"]
421
.as_str()
422
.unwrap()
423
.contains("teams.microsoft.com")
424
);
425
}
426
335
427
#[test]
336
428
fn the_body_asks_for_a_teams_meeting_with_utc_times() {
337
429
let body = new_event_body(&event(Repeat::Never));
@@ -479,6 +571,15 @@ mod tests {
479
571
);
480
572
}
481
573
574
#[tokio::test]
575
async fn delete_event_sends_graph_delete() {
576
let calendar = Calendar::with_transport(Scripted::new(vec![(204, Value::Null)]), "emea");
577
calendar.delete_event("AAMk=", None).await.unwrap();
578
let sent = calendar.transport.sent.lock().unwrap();
579
assert_eq!(sent[0].0, Method::Delete);
580
assert_eq!(sent[0].1, "https://graph.microsoft.com/v1.0/me/events/AAMk%3D");
581
}
582
482
583
#[tokio::test]
483
584
async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() {
484
585
let calendar = Calendar::with_transport(
@@ -157,6 +157,31 @@ pub fn new_event_body(event: &NewEvent) -> Value {157
body157
body158
}158
}159
159
160
/// Outlook insert when the Teams join URL already exists (multi-target create).161
pub fn new_event_body_with_join(event: &NewEvent, join_url: &str) -> Value {162
let mut details = event.details.clone();163
if !details.is_empty() {164
details.push_str("\n\n");165
}166
details.push_str(join_url);167
let mut body = json!({168
"subject": event.subject,169
"start": graph_time(event, event.local_start, event.start),170
"end": graph_time(event, event.local_end, event.end),171
"attendees": event.attendees.iter().map(|attendee| json!({172
"type": "required",173
"emailAddress": {"address": attendee.address, "name": attendee.name},174
})).collect::<Vec<_>>(),175
"location": {"displayName": join_url},176
"body": {"contentType": "text", "content": details},177
"isOnlineMeeting": false,178
});179
if let Some(recurrence) = recurrence(event.repeat, event.local_start) {180
body["recurrence"] = recurrence;181
}182
body183
}184
160
pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> {185
pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> {161
Some(CreatedEvent {186
Some(CreatedEvent {162
id: body.get("id")?.as_str()?.to_owned(),187
id: body.get("id")?.as_str()?.to_owned(),@@ -171,8 +196,12 @@ fn events_url() -> String {171
format!("{GRAPH}/v1.0/me/events")196
format!("{GRAPH}/v1.0/me/events")172
}197
}173
198
199
fn event_item_url(event_id: &str) -> String {200
format!("{}/{}", events_url(), encode(event_id))201
}202
174
fn reply_url(event_id: &str, reply: Reply) -> String {203
fn reply_url(event_id: &str, reply: Reply) -> String {175
format!("{}/{}/{}", events_url(), encode(event_id), reply.action())204
format!("{}/{}", event_item_url(event_id), reply.action())176
}205
}177
206
178
fn lookup_url(ical_uid: &str) -> String {207
fn lookup_url(ical_uid: &str) -> String {@@ -189,8 +218,27 @@ fn api_error(answer: session::ApiResponse, url: &str) -> Error {189
218
190
impl<T: CardTransport> Calendar<T> {219
impl<T: CardTransport> Calendar<T> {191
pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {220
pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {221
self.create_event_body(event, new_event_body(event)).await222
}223
224
pub async fn create_event_with_join(225
&self,226
event: &NewEvent,227
join_url: &str,228
) -> Result<CreatedEvent> {229
let mut created = self230
.create_event_body(event, new_event_body_with_join(event, join_url))231
.await?;232
if created.join_url.is_none() {233
created.join_url = Some(join_url.to_owned());234
}235
Ok(created)236
}237
238
async fn create_event_body(&self, event: &NewEvent, body: Value) -> Result<CreatedEvent> {239
let _ = event;192
let url = events_url();240
let url = events_url();193
let request = Request::with_body(Method::Post, &url, new_event_body(event));241
let request = Request::with_body(Method::Post, &url, body);194
let answer = self242
let answer = self195
.transport243
.transport196
.send(request, Scope::graph(CALENDARS_SCOPE))244
.send(request, Scope::graph(CALENDARS_SCOPE))@@ -223,6 +271,31 @@ impl<T: CardTransport> Calendar<T> {223
Err(api_error(retried, &reply_url(&graph_id, reply)))271
Err(api_error(retried, &reply_url(&graph_id, reply)))224
}272
}225
273
274
pub async fn delete_event(&self, event_id: &str, ical_uid: Option<&str>) -> Result<()> {275
let answer = self.send_delete(event_id).await?;276
if answer.is_success() {277
return Ok(());278
}279
let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else {280
return Err(api_error(answer, &event_item_url(event_id)));281
};282
let graph_id = self.graph_event_id(ical_uid).await?;283
let retried = self.send_delete(&graph_id).await?;284
if retried.is_success() {285
return Ok(());286
}287
Err(api_error(retried, &event_item_url(&graph_id)))288
}289
290
async fn send_delete(&self, event_id: &str) -> Result<session::ApiResponse> {291
self.transport292
.send(293
Request::delete(event_item_url(event_id)),294
Scope::graph(CALENDARS_SCOPE),295
)296
.await297
}298
226
async fn send_reply(299
async fn send_reply(227
&self,300
&self,228
event_id: &str,301
event_id: &str,@@ -332,6 +405,25 @@ mod tests {332
}405
}333
}406
}334
407
408
#[test]409
fn join_first_body_puts_link_in_location_without_online_meeting() {410
let body = new_event_body_with_join(411
&event(Repeat::Never),412
"https://teams.microsoft.com/l/meetup-join/x",413
);414
assert_eq!(body["isOnlineMeeting"], false);415
assert_eq!(416
body["location"]["displayName"],417
"https://teams.microsoft.com/l/meetup-join/x"418
);419
assert!(420
body["body"]["content"]421
.as_str()422
.unwrap()423
.contains("teams.microsoft.com")424
);425
}426
335
#[test]427
#[test]336
fn the_body_asks_for_a_teams_meeting_with_utc_times() {428
fn the_body_asks_for_a_teams_meeting_with_utc_times() {337
let body = new_event_body(&event(Repeat::Never));429
let body = new_event_body(&event(Repeat::Never));@@ -479,6 +571,15 @@ mod tests {479
);571
);480
}572
}481
573
574
#[tokio::test]575
async fn delete_event_sends_graph_delete() {576
let calendar = Calendar::with_transport(Scripted::new(vec![(204, Value::Null)]), "emea");577
calendar.delete_event("AAMk=", None).await.unwrap();578
let sent = calendar.transport.sent.lock().unwrap();579
assert_eq!(sent[0].0, Method::Delete);580
assert_eq!(sent[0].1, "https://graph.microsoft.com/v1.0/me/events/AAMk%3D");581
}582
482
#[tokio::test]583
#[tokio::test]483
async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() {584
async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() {484
let calendar = Calendar::with_transport(585
let calendar = Calendar::with_transport(@@ -0,0 +1,112 @@
1
use std::net::SocketAddr;
2
use std::time::Duration;
3
4
use tokio::io::{AsyncReadExt, AsyncWriteExt};
5
use tokio::net::TcpListener;
6
7
use crate::error::{Error, Result};
8
9
use super::oauth::AuthPending;
10
11
/// Bind a free loopback port and return `http://127.0.0.1:<port>/`.
12
pub async fn allocate_redirect_uri() -> Result<(String, TcpListener)> {
13
let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))
14
.await
15
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
16
let port = listener
17
.local_addr()
18
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?
19
.port();
20
Ok((format!("http://127.0.0.1:{port}/"), listener))
21
}
22
23
/// Wait for the browser redirect, validate `state`, return the authorization code.
24
pub async fn wait_for_code(pending: &AuthPending, listener: TcpListener) -> Result<String> {
25
let accept = tokio::time::timeout(Duration::from_secs(180), listener.accept());
26
let (mut stream, _) = accept
27
.await
28
.map_err(|_| Error::UnexpectedAnswer("Google sign-in timed out".into()))?
29
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
30
let mut buffer = vec![0_u8; 4096];
31
let read = stream
32
.read(&mut buffer)
33
.await
34
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
35
let request = String::from_utf8_lossy(&buffer[..read]);
36
let line = request.lines().next().unwrap_or_default();
37
let path = line
38
.strip_prefix("GET ")
39
.and_then(|rest| rest.split_whitespace().next())
40
.unwrap_or("/");
41
let query = path.split('?').nth(1).unwrap_or("");
42
let mut code = None;
43
let mut state = None;
44
for pair in query.split('&') {
45
let mut parts = pair.splitn(2, '=');
46
match (parts.next(), parts.next()) {
47
(Some("code"), Some(value)) => code = Some(urlencoding_decode(value)),
48
(Some("state"), Some(value)) => state = Some(urlencoding_decode(value)),
49
_ => {}
50
}
51
}
52
let body = if state.as_deref() == Some(pending.state.as_str()) && code.is_some() {
53
"You can close this window and return to Rusty Teams."
54
} else {
55
"Sign-in failed. You can close this window."
56
};
57
let response = format!(
58
"HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
59
body.len()
60
);
61
let _ = stream.write_all(response.as_bytes()).await;
62
let _ = stream.shutdown().await;
63
if state.as_deref() != Some(pending.state.as_str()) {
64
return Err(Error::UnexpectedAnswer("Google OAuth state mismatch".into()));
65
}
66
code.ok_or_else(|| Error::UnexpectedAnswer("Google OAuth code missing".into()))
67
}
68
69
fn urlencoding_decode(value: &str) -> String {
70
percent_encoding::percent_decode_str(value)
71
.decode_utf8_lossy()
72
.into_owned()
73
}
74
75
#[cfg(test)]
76
mod tests {
77
use super::*;
78
use crate::google_calendar::oauth::GoogleOAuth;
79
80
#[tokio::test]
81
async fn allocate_redirect_is_loopback() {
82
let (uri, listener) = allocate_redirect_uri().await.unwrap();
83
assert!(uri.starts_with("http://127.0.0.1:"));
84
assert!(uri.ends_with('/'));
85
drop(listener);
86
}
87
88
#[tokio::test]
89
async fn wait_for_code_reads_query() {
90
let oauth = GoogleOAuth {
91
client_id: "cid".into(),
92
client_secret: String::new(),
93
};
94
let (uri, listener) = allocate_redirect_uri().await.unwrap();
95
let pending = oauth.begin(&uri);
96
let port = listener.local_addr().unwrap().port();
97
let state = pending.state.clone();
98
let code_value = "the-code";
99
tokio::spawn(async move {
100
tokio::time::sleep(Duration::from_millis(50)).await;
101
let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))
102
.await
103
.unwrap();
104
let request = format!(
105
"GET /?code={code_value}&state={state} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"
106
);
107
stream.write_all(request.as_bytes()).await.unwrap();
108
});
109
let code = wait_for_code(&pending, listener).await.unwrap();
110
assert_eq!(code, code_value);
111
}
112
}
@@ -0,0 +1,112 @@1
use std::net::SocketAddr;2
use std::time::Duration;3
4
use tokio::io::{AsyncReadExt, AsyncWriteExt};5
use tokio::net::TcpListener;6
7
use crate::error::{Error, Result};8
9
use super::oauth::AuthPending;10
11
/// Bind a free loopback port and return `http://127.0.0.1:<port>/`.12
pub async fn allocate_redirect_uri() -> Result<(String, TcpListener)> {13
let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))14
.await15
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;16
let port = listener17
.local_addr()18
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?19
.port();20
Ok((format!("http://127.0.0.1:{port}/"), listener))21
}22
23
/// Wait for the browser redirect, validate `state`, return the authorization code.24
pub async fn wait_for_code(pending: &AuthPending, listener: TcpListener) -> Result<String> {25
let accept = tokio::time::timeout(Duration::from_secs(180), listener.accept());26
let (mut stream, _) = accept27
.await28
.map_err(|_| Error::UnexpectedAnswer("Google sign-in timed out".into()))?29
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;30
let mut buffer = vec![0_u8; 4096];31
let read = stream32
.read(&mut buffer)33
.await34
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;35
let request = String::from_utf8_lossy(&buffer[..read]);36
let line = request.lines().next().unwrap_or_default();37
let path = line38
.strip_prefix("GET ")39
.and_then(|rest| rest.split_whitespace().next())40
.unwrap_or("/");41
let query = path.split('?').nth(1).unwrap_or("");42
let mut code = None;43
let mut state = None;44
for pair in query.split('&') {45
let mut parts = pair.splitn(2, '=');46
match (parts.next(), parts.next()) {47
(Some("code"), Some(value)) => code = Some(urlencoding_decode(value)),48
(Some("state"), Some(value)) => state = Some(urlencoding_decode(value)),49
_ => {}50
}51
}52
let body = if state.as_deref() == Some(pending.state.as_str()) && code.is_some() {53
"You can close this window and return to Rusty Teams."54
} else {55
"Sign-in failed. You can close this window."56
};57
let response = format!(58
"HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",59
body.len()60
);61
let _ = stream.write_all(response.as_bytes()).await;62
let _ = stream.shutdown().await;63
if state.as_deref() != Some(pending.state.as_str()) {64
return Err(Error::UnexpectedAnswer("Google OAuth state mismatch".into()));65
}66
code.ok_or_else(|| Error::UnexpectedAnswer("Google OAuth code missing".into()))67
}68
69
fn urlencoding_decode(value: &str) -> String {70
percent_encoding::percent_decode_str(value)71
.decode_utf8_lossy()72
.into_owned()73
}74
75
#[cfg(test)]76
mod tests {77
use super::*;78
use crate::google_calendar::oauth::GoogleOAuth;79
80
#[tokio::test]81
async fn allocate_redirect_is_loopback() {82
let (uri, listener) = allocate_redirect_uri().await.unwrap();83
assert!(uri.starts_with("http://127.0.0.1:"));84
assert!(uri.ends_with('/'));85
drop(listener);86
}87
88
#[tokio::test]89
async fn wait_for_code_reads_query() {90
let oauth = GoogleOAuth {91
client_id: "cid".into(),92
client_secret: String::new(),93
};94
let (uri, listener) = allocate_redirect_uri().await.unwrap();95
let pending = oauth.begin(&uri);96
let port = listener.local_addr().unwrap().port();97
let state = pending.state.clone();98
let code_value = "the-code";99
tokio::spawn(async move {100
tokio::time::sleep(Duration::from_millis(50)).await;101
let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))102
.await103
.unwrap();104
let request = format!(105
"GET /?code={code_value}&state={state} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"106
);107
stream.write_all(request.as_bytes()).await.unwrap();108
});109
let code = wait_for_code(&pending, listener).await.unwrap();110
assert_eq!(code, code_value);111
}112
}@@ -0,0 +1,122 @@
1
use crate::calendar::{CalendarEvent, CalendarSource};
2
3
/// Collapse duplicate meetings that share an iCal UID or the same Teams join URL.
4
pub fn merge_calendar_events(events: Vec<CalendarEvent>) -> Vec<CalendarEvent> {
5
let mut merged: Vec<CalendarEvent> = Vec::new();
6
for event in events {
7
if let Some(existing) = merged.iter_mut().find(|candidate| same_meeting(candidate, &event))
8
{
9
if !existing.sources.contains(&event.source) {
10
existing.sources.push(event.source);
11
}
12
if existing.join_url.is_none() {
13
existing.join_url = event.join_url.clone();
14
existing.online = existing.online || event.online;
15
}
16
if existing.thread_id.is_none() {
17
existing.thread_id = event.thread_id.clone();
18
}
19
// Prefer Outlook object id when both sides contribute.
20
if existing.source == CalendarSource::Google && event.source == CalendarSource::Outlook
21
{
22
existing.object_id = event.object_id.clone();
23
existing.source = CalendarSource::Outlook;
24
existing.account_id = event.account_id.clone();
25
existing.calendar_id = event.calendar_id.clone();
26
existing.response = event.response;
27
existing.show_as = event.show_as;
28
}
29
continue;
30
}
31
merged.push(event);
32
}
33
merged.sort_by_key(|event| (event.start, event.end));
34
merged
35
}
36
37
fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
38
if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
39
if !a.is_empty() && a == b {
40
return true;
41
}
42
}
43
match (
44
left.join_url.as_deref().map(normalize_join_url),
45
right.join_url.as_deref().map(normalize_join_url),
46
) {
47
(Some(a), Some(b)) if !a.is_empty() && a == b => true,
48
_ => false,
49
}
50
}
51
52
pub fn normalize_join_url(url: &str) -> String {
53
let trimmed = url.trim().trim_end_matches('/');
54
let without_query = trimmed.split('?').next().unwrap_or(trimmed);
55
without_query.to_ascii_lowercase()
56
}
57
58
#[cfg(test)]
59
mod tests {
60
use chrono::TimeZone;
61
62
use super::*;
63
64
fn event(
65
id: &str,
66
source: CalendarSource,
67
ical: Option<&str>,
68
join: Option<&str>,
69
) -> CalendarEvent {
70
CalendarEvent {
71
object_id: id.into(),
72
subject: "Sync".into(),
73
start: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 10, 0, 0).unwrap(),
74
end: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 10, 30, 0).unwrap(),
75
ical_uid: ical.map(str::to_owned),
76
join_url: join.map(str::to_owned),
77
online: join.is_some(),
78
source,
79
sources: vec![source],
80
..Default::default()
81
}
82
}
83
84
#[test]
85
fn merges_on_ical_uid_and_keeps_both_sources() {
86
let merged = merge_calendar_events(vec![
87
event("o1", CalendarSource::Outlook, Some("uid"), None),
88
event("g1", CalendarSource::Google, Some("uid"), Some("https://teams.microsoft.com/l/meetup-join/x")),
89
]);
90
assert_eq!(merged.len(), 1);
91
assert_eq!(merged[0].sources.len(), 2);
92
assert_eq!(merged[0].object_id, "o1");
93
assert!(merged[0].join_url.is_some());
94
}
95
96
#[test]
97
fn merges_on_normalized_join_url() {
98
let merged = merge_calendar_events(vec![
99
event(
100
"o1",
101
CalendarSource::Outlook,
102
None,
103
Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),
104
),
105
event(
106
"g1",
107
CalendarSource::Google,
108
None,
109
Some("https://teams.microsoft.com/l/meetup-join/x/"),
110
),
111
]);
112
assert_eq!(merged.len(), 1);
113
}
114
115
#[test]
116
fn does_not_merge_on_title_and_time_alone() {
117
let a = event("a", CalendarSource::Outlook, Some("a"), None);
118
let mut b = event("b", CalendarSource::Google, Some("b"), None);
119
b.subject = a.subject.clone();
120
assert_eq!(merge_calendar_events(vec![a, b]).len(), 2);
121
}
122
}
@@ -0,0 +1,122 @@1
use crate::calendar::{CalendarEvent, CalendarSource};2
3
/// Collapse duplicate meetings that share an iCal UID or the same Teams join URL.4
pub fn merge_calendar_events(events: Vec<CalendarEvent>) -> Vec<CalendarEvent> {5
let mut merged: Vec<CalendarEvent> = Vec::new();6
for event in events {7
if let Some(existing) = merged.iter_mut().find(|candidate| same_meeting(candidate, &event))8
{9
if !existing.sources.contains(&event.source) {10
existing.sources.push(event.source);11
}12
if existing.join_url.is_none() {13
existing.join_url = event.join_url.clone();14
existing.online = existing.online || event.online;15
}16
if existing.thread_id.is_none() {17
existing.thread_id = event.thread_id.clone();18
}19
// Prefer Outlook object id when both sides contribute.20
if existing.source == CalendarSource::Google && event.source == CalendarSource::Outlook21
{22
existing.object_id = event.object_id.clone();23
existing.source = CalendarSource::Outlook;24
existing.account_id = event.account_id.clone();25
existing.calendar_id = event.calendar_id.clone();26
existing.response = event.response;27
existing.show_as = event.show_as;28
}29
continue;30
}31
merged.push(event);32
}33
merged.sort_by_key(|event| (event.start, event.end));34
merged35
}36
37
fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {38
if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {39
if !a.is_empty() && a == b {40
return true;41
}42
}43
match (44
left.join_url.as_deref().map(normalize_join_url),45
right.join_url.as_deref().map(normalize_join_url),46
) {47
(Some(a), Some(b)) if !a.is_empty() && a == b => true,48
_ => false,49
}50
}51
52
pub fn normalize_join_url(url: &str) -> String {53
let trimmed = url.trim().trim_end_matches('/');54
let without_query = trimmed.split('?').next().unwrap_or(trimmed);55
without_query.to_ascii_lowercase()56
}57
58
#[cfg(test)]59
mod tests {60
use chrono::TimeZone;61
62
use super::*;63
64
fn event(65
id: &str,66
source: CalendarSource,67
ical: Option<&str>,68
join: Option<&str>,69
) -> CalendarEvent {70
CalendarEvent {71
object_id: id.into(),72
subject: "Sync".into(),73
start: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 10, 0, 0).unwrap(),74
end: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 10, 30, 0).unwrap(),75
ical_uid: ical.map(str::to_owned),76
join_url: join.map(str::to_owned),77
online: join.is_some(),78
source,79
sources: vec![source],80
..Default::default()81
}82
}83
84
#[test]85
fn merges_on_ical_uid_and_keeps_both_sources() {86
let merged = merge_calendar_events(vec![87
event("o1", CalendarSource::Outlook, Some("uid"), None),88
event("g1", CalendarSource::Google, Some("uid"), Some("https://teams.microsoft.com/l/meetup-join/x")),89
]);90
assert_eq!(merged.len(), 1);91
assert_eq!(merged[0].sources.len(), 2);92
assert_eq!(merged[0].object_id, "o1");93
assert!(merged[0].join_url.is_some());94
}95
96
#[test]97
fn merges_on_normalized_join_url() {98
let merged = merge_calendar_events(vec![99
event(100
"o1",101
CalendarSource::Outlook,102
None,103
Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),104
),105
event(106
"g1",107
CalendarSource::Google,108
None,109
Some("https://teams.microsoft.com/l/meetup-join/x/"),110
),111
]);112
assert_eq!(merged.len(), 1);113
}114
115
#[test]116
fn does_not_merge_on_title_and_time_alone() {117
let a = event("a", CalendarSource::Outlook, Some("a"), None);118
let mut b = event("b", CalendarSource::Google, Some("b"), None);119
b.subject = a.subject.clone();120
assert_eq!(merge_calendar_events(vec![a, b]).len(), 2);121
}122
}@@ -0,0 +1,185 @@
1
//! Google Calendar OAuth + REST client for rusty-teams calendar accounts.
2
3
mod loopback;
4
mod merge;
5
mod oauth;
6
mod parse;
7
mod write;
8
9
pub use loopback::{allocate_redirect_uri, wait_for_code};
10
pub use merge::{merge_calendar_events, normalize_join_url};
11
pub use oauth::{
12
AuthPending, GoogleOAuth, TokenBundle, client_id_from_env, exchange_code, refresh_access_token,
13
};
14
pub use parse::{parse_calendar_list, parse_google_events};
15
pub use write::{
16
GoogleEventDraft, google_event_body, google_rsvp_query, google_rsvp_status, rrule_for_repeat,
17
};
18
19
use chrono::{DateTime, Utc};
20
use reqwest::Client;
21
use serde_json::Value;
22
23
use crate::calendar::CalendarEvent;
24
use crate::error::{Error, Result};
25
26
const CALENDAR_API: &str = "https://www.googleapis.com/calendar/v3";
27
28
pub struct GoogleCalendar {
29
client: Client,
30
access_token: String,
31
}
32
33
impl GoogleCalendar {
34
pub fn new(access_token: impl Into<String>) -> Self {
35
GoogleCalendar {
36
client: Client::new(),
37
access_token: access_token.into(),
38
}
39
}
40
41
pub async fn list_calendars(&self) -> Result<Value> {
42
self.get(&format!("{CALENDAR_API}/users/me/calendarList"))
43
.await
44
}
45
46
pub async fn events(
47
&self,
48
calendar_id: &str,
49
start: DateTime<Utc>,
50
end: DateTime<Utc>,
51
) -> Result<Vec<CalendarEvent>> {
52
let encoded = percent_encoding::utf8_percent_encode(
53
calendar_id,
54
percent_encoding::NON_ALPHANUMERIC,
55
);
56
let url = format!(
57
"{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&timeMin={}&timeMax={}",
58
start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
59
end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
60
);
61
let body = self.get(&url).await?;
62
Ok(parse_google_events(&body, None, Some(calendar_id)))
63
}
64
65
pub async fn insert_event(&self, calendar_id: &str, draft: &GoogleEventDraft) -> Result<Value> {
66
let encoded = percent_encoding::utf8_percent_encode(
67
calendar_id,
68
percent_encoding::NON_ALPHANUMERIC,
69
);
70
let url = format!("{CALENDAR_API}/calendars/{encoded}/events?sendUpdates=all");
71
self.post(&url, google_event_body(draft)).await
72
}
73
74
pub async fn respond(
75
&self,
76
calendar_id: &str,
77
event_id: &str,
78
status: &str,
79
send_updates: bool,
80
) -> Result<()> {
81
let encoded_cal = percent_encoding::utf8_percent_encode(
82
calendar_id,
83
percent_encoding::NON_ALPHANUMERIC,
84
);
85
let encoded_event =
86
percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);
87
let url = format!(
88
"{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",
89
google_rsvp_query(send_updates)
90
);
91
// Patch attendee self via conferenceData-free body: use attendees[].responseStatus
92
// by first getting the event is heavy; Google allows PATCH with only attendees when
93
// "self" is present. Simpler path: PATCH with a single attendees entry marked self.
94
let body = serde_json::json!({
95
"attendees": [{ "self": true, "responseStatus": status }]
96
});
97
self.patch(&url, body).await?;
98
Ok(())
99
}
100
101
pub async fn delete_event(
102
&self,
103
calendar_id: &str,
104
event_id: &str,
105
send_updates: bool,
106
) -> Result<()> {
107
let encoded_cal = percent_encoding::utf8_percent_encode(
108
calendar_id,
109
percent_encoding::NON_ALPHANUMERIC,
110
);
111
let encoded_event =
112
percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);
113
let url = format!(
114
"{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",
115
google_rsvp_query(send_updates)
116
);
117
self.delete(&url).await
118
}
119
120
async fn get(&self, url: &str) -> Result<Value> {
121
let response = self
122
.client
123
.get(url)
124
.bearer_auth(&self.access_token)
125
.send()
126
.await
127
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
128
Self::json_result(url, response).await
129
}
130
131
async fn post(&self, url: &str, body: Value) -> Result<Value> {
132
let response = self
133
.client
134
.post(url)
135
.bearer_auth(&self.access_token)
136
.json(&body)
137
.send()
138
.await
139
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
140
Self::json_result(url, response).await
141
}
142
143
async fn patch(&self, url: &str, body: Value) -> Result<Value> {
144
let response = self
145
.client
146
.patch(url)
147
.bearer_auth(&self.access_token)
148
.json(&body)
149
.send()
150
.await
151
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
152
Self::json_result(url, response).await
153
}
154
155
async fn delete(&self, url: &str) -> Result<()> {
156
let response = self
157
.client
158
.delete(url)
159
.bearer_auth(&self.access_token)
160
.send()
161
.await
162
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
163
let status = response.status().as_u16();
164
if (200..300).contains(&status) {
165
return Ok(());
166
}
167
let body = response
168
.json::<Value>()
169
.await
170
.unwrap_or_else(|_| Value::Null);
171
Err(Error::Session(session::Error::api(status, url, body)))
172
}
173
174
async fn json_result(url: &str, response: reqwest::Response) -> Result<Value> {
175
let status = response.status().as_u16();
176
let body = response
177
.json::<Value>()
178
.await
179
.unwrap_or_else(|_| Value::Null);
180
if !(200..300).contains(&status) {
181
return Err(Error::Session(session::Error::api(status, url, body)));
182
}
183
Ok(body)
184
}
185
}
@@ -0,0 +1,185 @@1
//! Google Calendar OAuth + REST client for rusty-teams calendar accounts.2
3
mod loopback;4
mod merge;5
mod oauth;6
mod parse;7
mod write;8
9
pub use loopback::{allocate_redirect_uri, wait_for_code};10
pub use merge::{merge_calendar_events, normalize_join_url};11
pub use oauth::{12
AuthPending, GoogleOAuth, TokenBundle, client_id_from_env, exchange_code, refresh_access_token,13
};14
pub use parse::{parse_calendar_list, parse_google_events};15
pub use write::{16
GoogleEventDraft, google_event_body, google_rsvp_query, google_rsvp_status, rrule_for_repeat,17
};18
19
use chrono::{DateTime, Utc};20
use reqwest::Client;21
use serde_json::Value;22
23
use crate::calendar::CalendarEvent;24
use crate::error::{Error, Result};25
26
const CALENDAR_API: &str = "https://www.googleapis.com/calendar/v3";27
28
pub struct GoogleCalendar {29
client: Client,30
access_token: String,31
}32
33
impl GoogleCalendar {34
pub fn new(access_token: impl Into<String>) -> Self {35
GoogleCalendar {36
client: Client::new(),37
access_token: access_token.into(),38
}39
}40
41
pub async fn list_calendars(&self) -> Result<Value> {42
self.get(&format!("{CALENDAR_API}/users/me/calendarList"))43
.await44
}45
46
pub async fn events(47
&self,48
calendar_id: &str,49
start: DateTime<Utc>,50
end: DateTime<Utc>,51
) -> Result<Vec<CalendarEvent>> {52
let encoded = percent_encoding::utf8_percent_encode(53
calendar_id,54
percent_encoding::NON_ALPHANUMERIC,55
);56
let url = format!(57
"{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&timeMin={}&timeMax={}",58
start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),59
end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),60
);61
let body = self.get(&url).await?;62
Ok(parse_google_events(&body, None, Some(calendar_id)))63
}64
65
pub async fn insert_event(&self, calendar_id: &str, draft: &GoogleEventDraft) -> Result<Value> {66
let encoded = percent_encoding::utf8_percent_encode(67
calendar_id,68
percent_encoding::NON_ALPHANUMERIC,69
);70
let url = format!("{CALENDAR_API}/calendars/{encoded}/events?sendUpdates=all");71
self.post(&url, google_event_body(draft)).await72
}73
74
pub async fn respond(75
&self,76
calendar_id: &str,77
event_id: &str,78
status: &str,79
send_updates: bool,80
) -> Result<()> {81
let encoded_cal = percent_encoding::utf8_percent_encode(82
calendar_id,83
percent_encoding::NON_ALPHANUMERIC,84
);85
let encoded_event =86
percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);87
let url = format!(88
"{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",89
google_rsvp_query(send_updates)90
);91
// Patch attendee self via conferenceData-free body: use attendees[].responseStatus92
// by first getting the event is heavy; Google allows PATCH with only attendees when93
// "self" is present. Simpler path: PATCH with a single attendees entry marked self.94
let body = serde_json::json!({95
"attendees": [{ "self": true, "responseStatus": status }]96
});97
self.patch(&url, body).await?;98
Ok(())99
}100
101
pub async fn delete_event(102
&self,103
calendar_id: &str,104
event_id: &str,105
send_updates: bool,106
) -> Result<()> {107
let encoded_cal = percent_encoding::utf8_percent_encode(108
calendar_id,109
percent_encoding::NON_ALPHANUMERIC,110
);111
let encoded_event =112
percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);113
let url = format!(114
"{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",115
google_rsvp_query(send_updates)116
);117
self.delete(&url).await118
}119
120
async fn get(&self, url: &str) -> Result<Value> {121
let response = self122
.client123
.get(url)124
.bearer_auth(&self.access_token)125
.send()126
.await127
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;128
Self::json_result(url, response).await129
}130
131
async fn post(&self, url: &str, body: Value) -> Result<Value> {132
let response = self133
.client134
.post(url)135
.bearer_auth(&self.access_token)136
.json(&body)137
.send()138
.await139
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;140
Self::json_result(url, response).await141
}142
143
async fn patch(&self, url: &str, body: Value) -> Result<Value> {144
let response = self145
.client146
.patch(url)147
.bearer_auth(&self.access_token)148
.json(&body)149
.send()150
.await151
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;152
Self::json_result(url, response).await153
}154
155
async fn delete(&self, url: &str) -> Result<()> {156
let response = self157
.client158
.delete(url)159
.bearer_auth(&self.access_token)160
.send()161
.await162
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;163
let status = response.status().as_u16();164
if (200..300).contains(&status) {165
return Ok(());166
}167
let body = response168
.json::<Value>()169
.await170
.unwrap_or_else(|_| Value::Null);171
Err(Error::Session(session::Error::api(status, url, body)))172
}173
174
async fn json_result(url: &str, response: reqwest::Response) -> Result<Value> {175
let status = response.status().as_u16();176
let body = response177
.json::<Value>()178
.await179
.unwrap_or_else(|_| Value::Null);180
if !(200..300).contains(&status) {181
return Err(Error::Session(session::Error::api(status, url, body)));182
}183
Ok(body)184
}185
}@@ -0,0 +1,183 @@
1
use base64::Engine as _;
2
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
3
use rand::RngCore;
4
use serde::Deserialize;
5
use sha2::{Digest, Sha256};
6
7
use crate::error::{Error, Result};
8
9
pub const GOOGLE_CLIENT_ID_ENV: &str = "TEAMS_GOOGLE_CLIENT_ID";
10
pub const GOOGLE_CLIENT_SECRET_ENV: &str = "TEAMS_GOOGLE_CLIENT_SECRET";
11
const AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
12
const TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
13
const SCOPES: &str = "https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email";
14
15
#[derive(Debug, Clone, PartialEq, Eq)]
16
pub struct GoogleOAuth {
17
pub client_id: String,
18
pub client_secret: String,
19
}
20
21
#[derive(Debug, Clone, PartialEq, Eq)]
22
pub struct AuthPending {
23
pub authorize_url: String,
24
pub redirect_uri: String,
25
pub state: String,
26
pub code_verifier: String,
27
}
28
29
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
30
pub struct TokenBundle {
31
pub access_token: String,
32
#[serde(default)]
33
pub refresh_token: String,
34
#[serde(default)]
35
pub expires_in: i64,
36
#[serde(default)]
37
pub token_type: String,
38
}
39
40
pub fn client_id_from_env() -> Option<GoogleOAuth> {
41
let client_id = std::env::var(GOOGLE_CLIENT_ID_ENV).ok()?;
42
if client_id.trim().is_empty() {
43
return None;
44
}
45
let client_secret = std::env::var(GOOGLE_CLIENT_SECRET_ENV).unwrap_or_default();
46
Some(GoogleOAuth {
47
client_id,
48
client_secret,
49
})
50
}
51
52
impl GoogleOAuth {
53
pub fn begin(&self, redirect_uri: &str) -> AuthPending {
54
let state = random_url_token(16);
55
let code_verifier = random_url_token(32);
56
let challenge = code_challenge(&code_verifier);
57
let mut url = url::Url::parse(AUTH_URL).expect("auth url");
58
{
59
let mut query = url.query_pairs_mut();
60
query.append_pair("client_id", &self.client_id);
61
query.append_pair("redirect_uri", redirect_uri);
62
query.append_pair("response_type", "code");
63
query.append_pair("scope", SCOPES);
64
query.append_pair("access_type", "offline");
65
query.append_pair("prompt", "consent");
66
query.append_pair("state", &state);
67
query.append_pair("code_challenge", &challenge);
68
query.append_pair("code_challenge_method", "S256");
69
}
70
AuthPending {
71
authorize_url: url.to_string(),
72
redirect_uri: redirect_uri.to_owned(),
73
state,
74
code_verifier,
75
}
76
}
77
}
78
79
pub async fn exchange_code(
80
oauth: &GoogleOAuth,
81
pending: &AuthPending,
82
code: &str,
83
) -> Result<TokenBundle> {
84
let client = reqwest::Client::new();
85
let mut form = vec![
86
("code", code.to_owned()),
87
("client_id", oauth.client_id.clone()),
88
("redirect_uri", pending.redirect_uri.clone()),
89
("grant_type", "authorization_code".to_owned()),
90
("code_verifier", pending.code_verifier.clone()),
91
];
92
if !oauth.client_secret.is_empty() {
93
form.push(("client_secret", oauth.client_secret.clone()));
94
}
95
let response = client
96
.post(TOKEN_URL)
97
.form(&form)
98
.send()
99
.await
100
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
101
let status = response.status().as_u16();
102
let body = response
103
.json::<serde_json::Value>()
104
.await
105
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
106
if !(200..300).contains(&status) {
107
return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));
108
}
109
serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))
110
}
111
112
pub async fn refresh_access_token(oauth: &GoogleOAuth, refresh_token: &str) -> Result<TokenBundle> {
113
let client = reqwest::Client::new();
114
let mut form = vec![
115
("client_id", oauth.client_id.clone()),
116
("grant_type", "refresh_token".to_owned()),
117
("refresh_token", refresh_token.to_owned()),
118
];
119
if !oauth.client_secret.is_empty() {
120
form.push(("client_secret", oauth.client_secret.clone()));
121
}
122
let response = client
123
.post(TOKEN_URL)
124
.form(&form)
125
.send()
126
.await
127
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
128
let status = response.status().as_u16();
129
let body = response
130
.json::<serde_json::Value>()
131
.await
132
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
133
if !(200..300).contains(&status) {
134
return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));
135
}
136
let mut bundle: TokenBundle =
137
serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
138
if bundle.refresh_token.is_empty() {
139
bundle.refresh_token = refresh_token.to_owned();
140
}
141
Ok(bundle)
142
}
143
144
fn random_url_token(bytes: usize) -> String {
145
let mut buffer = vec![0_u8; bytes];
146
rand::rng().fill_bytes(&mut buffer);
147
URL_SAFE_NO_PAD.encode(buffer)
148
}
149
150
fn code_challenge(verifier: &str) -> String {
151
let digest = Sha256::digest(verifier.as_bytes());
152
URL_SAFE_NO_PAD.encode(digest)
153
}
154
155
#[cfg(test)]
156
mod tests {
157
use super::*;
158
159
#[test]
160
fn begin_builds_pkce_authorize_url() {
161
let oauth = GoogleOAuth {
162
client_id: "cid".into(),
163
client_secret: String::new(),
164
};
165
let pending = oauth.begin("http://127.0.0.1:8765/");
166
assert!(pending.authorize_url.contains("client_id=cid"));
167
assert!(pending.authorize_url.contains("code_challenge_method=S256"));
168
assert!(!pending.code_verifier.is_empty());
169
assert_eq!(
170
code_challenge("abc"),
171
URL_SAFE_NO_PAD.encode(Sha256::digest(b"abc"))
172
);
173
}
174
175
#[test]
176
fn token_bundle_deserializes() {
177
let json = r#"{"access_token":"a","refresh_token":"r","expires_in":3600,"token_type":"Bearer"}"#;
178
let bundle: TokenBundle = serde_json::from_str(json).unwrap();
179
assert_eq!(bundle.access_token, "a");
180
assert_eq!(bundle.refresh_token, "r");
181
assert_eq!(bundle.expires_in, 3600);
182
}
183
}
@@ -0,0 +1,183 @@1
use base64::Engine as _;2
use base64::engine::general_purpose::URL_SAFE_NO_PAD;3
use rand::RngCore;4
use serde::Deserialize;5
use sha2::{Digest, Sha256};6
7
use crate::error::{Error, Result};8
9
pub const GOOGLE_CLIENT_ID_ENV: &str = "TEAMS_GOOGLE_CLIENT_ID";10
pub const GOOGLE_CLIENT_SECRET_ENV: &str = "TEAMS_GOOGLE_CLIENT_SECRET";11
const AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";12
const TOKEN_URL: &str = "https://oauth2.googleapis.com/token";13
const SCOPES: &str = "https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email";14
15
#[derive(Debug, Clone, PartialEq, Eq)]16
pub struct GoogleOAuth {17
pub client_id: String,18
pub client_secret: String,19
}20
21
#[derive(Debug, Clone, PartialEq, Eq)]22
pub struct AuthPending {23
pub authorize_url: String,24
pub redirect_uri: String,25
pub state: String,26
pub code_verifier: String,27
}28
29
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]30
pub struct TokenBundle {31
pub access_token: String,32
#[serde(default)]33
pub refresh_token: String,34
#[serde(default)]35
pub expires_in: i64,36
#[serde(default)]37
pub token_type: String,38
}39
40
pub fn client_id_from_env() -> Option<GoogleOAuth> {41
let client_id = std::env::var(GOOGLE_CLIENT_ID_ENV).ok()?;42
if client_id.trim().is_empty() {43
return None;44
}45
let client_secret = std::env::var(GOOGLE_CLIENT_SECRET_ENV).unwrap_or_default();46
Some(GoogleOAuth {47
client_id,48
client_secret,49
})50
}51
52
impl GoogleOAuth {53
pub fn begin(&self, redirect_uri: &str) -> AuthPending {54
let state = random_url_token(16);55
let code_verifier = random_url_token(32);56
let challenge = code_challenge(&code_verifier);57
let mut url = url::Url::parse(AUTH_URL).expect("auth url");58
{59
let mut query = url.query_pairs_mut();60
query.append_pair("client_id", &self.client_id);61
query.append_pair("redirect_uri", redirect_uri);62
query.append_pair("response_type", "code");63
query.append_pair("scope", SCOPES);64
query.append_pair("access_type", "offline");65
query.append_pair("prompt", "consent");66
query.append_pair("state", &state);67
query.append_pair("code_challenge", &challenge);68
query.append_pair("code_challenge_method", "S256");69
}70
AuthPending {71
authorize_url: url.to_string(),72
redirect_uri: redirect_uri.to_owned(),73
state,74
code_verifier,75
}76
}77
}78
79
pub async fn exchange_code(80
oauth: &GoogleOAuth,81
pending: &AuthPending,82
code: &str,83
) -> Result<TokenBundle> {84
let client = reqwest::Client::new();85
let mut form = vec![86
("code", code.to_owned()),87
("client_id", oauth.client_id.clone()),88
("redirect_uri", pending.redirect_uri.clone()),89
("grant_type", "authorization_code".to_owned()),90
("code_verifier", pending.code_verifier.clone()),91
];92
if !oauth.client_secret.is_empty() {93
form.push(("client_secret", oauth.client_secret.clone()));94
}95
let response = client96
.post(TOKEN_URL)97
.form(&form)98
.send()99
.await100
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;101
let status = response.status().as_u16();102
let body = response103
.json::<serde_json::Value>()104
.await105
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;106
if !(200..300).contains(&status) {107
return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));108
}109
serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))110
}111
112
pub async fn refresh_access_token(oauth: &GoogleOAuth, refresh_token: &str) -> Result<TokenBundle> {113
let client = reqwest::Client::new();114
let mut form = vec![115
("client_id", oauth.client_id.clone()),116
("grant_type", "refresh_token".to_owned()),117
("refresh_token", refresh_token.to_owned()),118
];119
if !oauth.client_secret.is_empty() {120
form.push(("client_secret", oauth.client_secret.clone()));121
}122
let response = client123
.post(TOKEN_URL)124
.form(&form)125
.send()126
.await127
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;128
let status = response.status().as_u16();129
let body = response130
.json::<serde_json::Value>()131
.await132
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;133
if !(200..300).contains(&status) {134
return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));135
}136
let mut bundle: TokenBundle =137
serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;138
if bundle.refresh_token.is_empty() {139
bundle.refresh_token = refresh_token.to_owned();140
}141
Ok(bundle)142
}143
144
fn random_url_token(bytes: usize) -> String {145
let mut buffer = vec![0_u8; bytes];146
rand::rng().fill_bytes(&mut buffer);147
URL_SAFE_NO_PAD.encode(buffer)148
}149
150
fn code_challenge(verifier: &str) -> String {151
let digest = Sha256::digest(verifier.as_bytes());152
URL_SAFE_NO_PAD.encode(digest)153
}154
155
#[cfg(test)]156
mod tests {157
use super::*;158
159
#[test]160
fn begin_builds_pkce_authorize_url() {161
let oauth = GoogleOAuth {162
client_id: "cid".into(),163
client_secret: String::new(),164
};165
let pending = oauth.begin("http://127.0.0.1:8765/");166
assert!(pending.authorize_url.contains("client_id=cid"));167
assert!(pending.authorize_url.contains("code_challenge_method=S256"));168
assert!(!pending.code_verifier.is_empty());169
assert_eq!(170
code_challenge("abc"),171
URL_SAFE_NO_PAD.encode(Sha256::digest(b"abc"))172
);173
}174
175
#[test]176
fn token_bundle_deserializes() {177
let json = r#"{"access_token":"a","refresh_token":"r","expires_in":3600,"token_type":"Bearer"}"#;178
let bundle: TokenBundle = serde_json::from_str(json).unwrap();179
assert_eq!(bundle.access_token, "a");180
assert_eq!(bundle.refresh_token, "r");181
assert_eq!(bundle.expires_in, 3600);182
}183
}@@ -0,0 +1,201 @@
1
use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
2
use serde_json::Value;
3
4
use crate::calendar::{CalendarEvent, CalendarSource, ResponseType, ShowAs};
5
6
pub fn parse_calendar_list(body: &Value) -> Vec<(String, String, bool)> {
7
body.get("items")
8
.and_then(Value::as_array)
9
.into_iter()
10
.flatten()
11
.filter_map(|entry| {
12
Some((
13
entry.get("id")?.as_str()?.to_owned(),
14
entry
15
.get("summary")
16
.and_then(Value::as_str)
17
.unwrap_or("Calendar")
18
.to_owned(),
19
entry
20
.get("primary")
21
.and_then(Value::as_bool)
22
.unwrap_or(false),
23
))
24
})
25
.collect()
26
}
27
28
pub fn parse_google_events(
29
body: &Value,
30
account_id: Option<&str>,
31
calendar_id: Option<&str>,
32
) -> Vec<CalendarEvent> {
33
let mut events: Vec<CalendarEvent> = body
34
.get("items")
35
.and_then(Value::as_array)
36
.into_iter()
37
.flatten()
38
.filter_map(|entry| parse_event(entry, account_id, calendar_id))
39
.collect();
40
events.sort_by_key(|event| (event.start, event.end));
41
events
42
}
43
44
fn parse_event(
45
entry: &Value,
46
account_id: Option<&str>,
47
calendar_id: Option<&str>,
48
) -> Option<CalendarEvent> {
49
if entry.get("status").and_then(Value::as_str) == Some("cancelled") {
50
// Still show cancelled when times exist.
51
}
52
let object_id = entry.get("id")?.as_str()?.to_owned();
53
let (start, all_day) = event_instant(entry.get("start")?)?;
54
let (end, _) = event_instant(entry.get("end")?)?;
55
let join_url = conference_join_url(entry)
56
.or_else(|| text(entry, "location").filter(|value| value.contains("teams.microsoft.com")))
57
.or_else(|| {
58
text(entry, "description").and_then(|description| {
59
description
60
.split_whitespace()
61
.find(|token| token.contains("teams.microsoft.com"))
62
.map(str::to_owned)
63
})
64
});
65
Some(CalendarEvent {
66
object_id,
67
subject: text(entry, "summary").unwrap_or_default(),
68
start,
69
end,
70
all_day,
71
cancelled: entry.get("status").and_then(Value::as_str) == Some("cancelled"),
72
online: join_url.is_some(),
73
join_url,
74
thread_id: None,
75
organizer_name: entry
76
.pointer("/organizer/displayName")
77
.and_then(Value::as_str)
78
.map(str::to_owned),
79
organizer_address: entry
80
.pointer("/organizer/email")
81
.and_then(Value::as_str)
82
.map(str::to_owned),
83
ical_uid: text(entry, "iCalUID"),
84
response: response_status(entry),
85
show_as: ShowAs::Busy,
86
dial_in: None,
87
source: CalendarSource::Google,
88
account_id: account_id.map(str::to_owned),
89
calendar_id: calendar_id.map(str::to_owned),
90
sources: vec![CalendarSource::Google],
91
})
92
}
93
94
fn conference_join_url(entry: &Value) -> Option<String> {
95
entry
96
.pointer("/conferenceData/entryPoints")
97
.and_then(Value::as_array)?
98
.iter()
99
.find_map(|point| {
100
if point.get("entryPointType").and_then(Value::as_str) == Some("video") {
101
text(point, "uri")
102
} else {
103
None
104
}
105
})
106
}
107
108
fn event_instant(value: &Value) -> Option<(DateTime<Utc>, bool)> {
109
if let Some(date) = value.get("date").and_then(Value::as_str) {
110
let day = NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
111
let start = day.and_time(NaiveTime::MIN).and_utc();
112
return Some((start, true));
113
}
114
let date_time = value.get("dateTime")?.as_str()?;
115
DateTime::parse_from_rfc3339(date_time)
116
.ok()
117
.map(|time| (time.with_timezone(&Utc), false))
118
}
119
120
fn response_status(entry: &Value) -> ResponseType {
121
let status = entry
122
.get("attendees")
123
.and_then(Value::as_array)
124
.into_iter()
125
.flatten()
126
.find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true))
127
.and_then(|attendee| attendee.get("responseStatus").and_then(Value::as_str))
128
.or_else(|| {
129
entry
130
.pointer("/organizer/self")
131
.and_then(Value::as_bool)
132
.filter(|value| *value)
133
.map(|_| "accepted")
134
});
135
match status {
136
Some("accepted") if entry.pointer("/organizer/self").and_then(Value::as_bool) == Some(true) => {
137
ResponseType::Organizer
138
}
139
Some("accepted") => ResponseType::Accepted,
140
Some("tentative") => ResponseType::Tentative,
141
Some("declined") => ResponseType::Declined,
142
_ => ResponseType::NotResponded,
143
}
144
}
145
146
fn text(entry: &Value, key: &str) -> Option<String> {
147
entry.get(key)?.as_str().map(str::to_owned)
148
}
149
150
#[cfg(test)]
151
mod tests {
152
use super::*;
153
154
#[test]
155
fn parses_timed_event_with_teams_link_in_location() {
156
let body = serde_json::json!({
157
"items": [{
158
"id": "evt1",
159
"summary": "Standup",
160
"iCalUID": "uid-1",
161
"start": {"dateTime": "2026-11-11T09:00:00Z"},
162
"end": {"dateTime": "2026-11-11T09:30:00Z"},
163
"location": "https://teams.microsoft.com/l/meetup-join/abc",
164
"attendees": [{"self": true, "responseStatus": "accepted"}]
165
}]
166
});
167
let events = parse_google_events(&body, Some("acc"), Some("primary"));
168
assert_eq!(events.len(), 1);
169
assert_eq!(events[0].subject, "Standup");
170
assert_eq!(events[0].source, CalendarSource::Google);
171
assert_eq!(events[0].account_id.as_deref(), Some("acc"));
172
assert_eq!(
173
events[0].join_url.as_deref(),
174
Some("https://teams.microsoft.com/l/meetup-join/abc")
175
);
176
assert_eq!(events[0].response, ResponseType::Accepted);
177
}
178
179
#[test]
180
fn parses_all_day_and_calendar_list() {
181
let body = serde_json::json!({
182
"items": [{
183
"id": "day",
184
"summary": "Offsite",
185
"start": {"date": "2026-11-12"},
186
"end": {"date": "2026-11-13"},
187
"status": "confirmed"
188
}]
189
});
190
let events = parse_google_events(&body, None, None);
191
assert!(events[0].all_day);
192
let list = parse_calendar_list(&serde_json::json!({
193
"items": [
194
{"id": "primary", "summary": "Joe", "primary": true},
195
{"id": "work", "summary": "Work"}
196
]
197
}));
198
assert_eq!(list[0].0, "primary");
199
assert!(list[0].2);
200
}
201
}
@@ -0,0 +1,201 @@1
use chrono::{DateTime, NaiveDate, NaiveTime, Utc};2
use serde_json::Value;3
4
use crate::calendar::{CalendarEvent, CalendarSource, ResponseType, ShowAs};5
6
pub fn parse_calendar_list(body: &Value) -> Vec<(String, String, bool)> {7
body.get("items")8
.and_then(Value::as_array)9
.into_iter()10
.flatten()11
.filter_map(|entry| {12
Some((13
entry.get("id")?.as_str()?.to_owned(),14
entry15
.get("summary")16
.and_then(Value::as_str)17
.unwrap_or("Calendar")18
.to_owned(),19
entry20
.get("primary")21
.and_then(Value::as_bool)22
.unwrap_or(false),23
))24
})25
.collect()26
}27
28
pub fn parse_google_events(29
body: &Value,30
account_id: Option<&str>,31
calendar_id: Option<&str>,32
) -> Vec<CalendarEvent> {33
let mut events: Vec<CalendarEvent> = body34
.get("items")35
.and_then(Value::as_array)36
.into_iter()37
.flatten()38
.filter_map(|entry| parse_event(entry, account_id, calendar_id))39
.collect();40
events.sort_by_key(|event| (event.start, event.end));41
events42
}43
44
fn parse_event(45
entry: &Value,46
account_id: Option<&str>,47
calendar_id: Option<&str>,48
) -> Option<CalendarEvent> {49
if entry.get("status").and_then(Value::as_str) == Some("cancelled") {50
// Still show cancelled when times exist.51
}52
let object_id = entry.get("id")?.as_str()?.to_owned();53
let (start, all_day) = event_instant(entry.get("start")?)?;54
let (end, _) = event_instant(entry.get("end")?)?;55
let join_url = conference_join_url(entry)56
.or_else(|| text(entry, "location").filter(|value| value.contains("teams.microsoft.com")))57
.or_else(|| {58
text(entry, "description").and_then(|description| {59
description60
.split_whitespace()61
.find(|token| token.contains("teams.microsoft.com"))62
.map(str::to_owned)63
})64
});65
Some(CalendarEvent {66
object_id,67
subject: text(entry, "summary").unwrap_or_default(),68
start,69
end,70
all_day,71
cancelled: entry.get("status").and_then(Value::as_str) == Some("cancelled"),72
online: join_url.is_some(),73
join_url,74
thread_id: None,75
organizer_name: entry76
.pointer("/organizer/displayName")77
.and_then(Value::as_str)78
.map(str::to_owned),79
organizer_address: entry80
.pointer("/organizer/email")81
.and_then(Value::as_str)82
.map(str::to_owned),83
ical_uid: text(entry, "iCalUID"),84
response: response_status(entry),85
show_as: ShowAs::Busy,86
dial_in: None,87
source: CalendarSource::Google,88
account_id: account_id.map(str::to_owned),89
calendar_id: calendar_id.map(str::to_owned),90
sources: vec![CalendarSource::Google],91
})92
}93
94
fn conference_join_url(entry: &Value) -> Option<String> {95
entry96
.pointer("/conferenceData/entryPoints")97
.and_then(Value::as_array)?98
.iter()99
.find_map(|point| {100
if point.get("entryPointType").and_then(Value::as_str) == Some("video") {101
text(point, "uri")102
} else {103
None104
}105
})106
}107
108
fn event_instant(value: &Value) -> Option<(DateTime<Utc>, bool)> {109
if let Some(date) = value.get("date").and_then(Value::as_str) {110
let day = NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;111
let start = day.and_time(NaiveTime::MIN).and_utc();112
return Some((start, true));113
}114
let date_time = value.get("dateTime")?.as_str()?;115
DateTime::parse_from_rfc3339(date_time)116
.ok()117
.map(|time| (time.with_timezone(&Utc), false))118
}119
120
fn response_status(entry: &Value) -> ResponseType {121
let status = entry122
.get("attendees")123
.and_then(Value::as_array)124
.into_iter()125
.flatten()126
.find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true))127
.and_then(|attendee| attendee.get("responseStatus").and_then(Value::as_str))128
.or_else(|| {129
entry130
.pointer("/organizer/self")131
.and_then(Value::as_bool)132
.filter(|value| *value)133
.map(|_| "accepted")134
});135
match status {136
Some("accepted") if entry.pointer("/organizer/self").and_then(Value::as_bool) == Some(true) => {137
ResponseType::Organizer138
}139
Some("accepted") => ResponseType::Accepted,140
Some("tentative") => ResponseType::Tentative,141
Some("declined") => ResponseType::Declined,142
_ => ResponseType::NotResponded,143
}144
}145
146
fn text(entry: &Value, key: &str) -> Option<String> {147
entry.get(key)?.as_str().map(str::to_owned)148
}149
150
#[cfg(test)]151
mod tests {152
use super::*;153
154
#[test]155
fn parses_timed_event_with_teams_link_in_location() {156
let body = serde_json::json!({157
"items": [{158
"id": "evt1",159
"summary": "Standup",160
"iCalUID": "uid-1",161
"start": {"dateTime": "2026-11-11T09:00:00Z"},162
"end": {"dateTime": "2026-11-11T09:30:00Z"},163
"location": "https://teams.microsoft.com/l/meetup-join/abc",164
"attendees": [{"self": true, "responseStatus": "accepted"}]165
}]166
});167
let events = parse_google_events(&body, Some("acc"), Some("primary"));168
assert_eq!(events.len(), 1);169
assert_eq!(events[0].subject, "Standup");170
assert_eq!(events[0].source, CalendarSource::Google);171
assert_eq!(events[0].account_id.as_deref(), Some("acc"));172
assert_eq!(173
events[0].join_url.as_deref(),174
Some("https://teams.microsoft.com/l/meetup-join/abc")175
);176
assert_eq!(events[0].response, ResponseType::Accepted);177
}178
179
#[test]180
fn parses_all_day_and_calendar_list() {181
let body = serde_json::json!({182
"items": [{183
"id": "day",184
"summary": "Offsite",185
"start": {"date": "2026-11-12"},186
"end": {"date": "2026-11-13"},187
"status": "confirmed"188
}]189
});190
let events = parse_google_events(&body, None, None);191
assert!(events[0].all_day);192
let list = parse_calendar_list(&serde_json::json!({193
"items": [194
{"id": "primary", "summary": "Joe", "primary": true},195
{"id": "work", "summary": "Work"}196
]197
}));198
assert_eq!(list[0].0, "primary");199
assert!(list[0].2);200
}201
}@@ -0,0 +1,153 @@
1
use chrono::{Datelike, Timelike};
2
use serde_json::{Value, json};
3
4
use crate::calendar::{Attendee, NewEvent, Repeat, Reply};
5
6
#[derive(Debug, Clone, PartialEq, Eq)]
7
pub struct GoogleEventDraft {
8
pub subject: String,
9
pub start: chrono::DateTime<chrono::Utc>,
10
pub end: chrono::DateTime<chrono::Utc>,
11
pub attendees: Vec<Attendee>,
12
pub details: String,
13
pub join_url: Option<String>,
14
pub repeat: Repeat,
15
}
16
17
impl From<&NewEvent> for GoogleEventDraft {
18
fn from(event: &NewEvent) -> Self {
19
GoogleEventDraft {
20
subject: event.subject.clone(),
21
start: event.start,
22
end: event.end,
23
attendees: event.attendees.clone(),
24
details: event.details.clone(),
25
join_url: None,
26
repeat: event.repeat,
27
}
28
}
29
}
30
31
pub fn rrule_for_repeat(repeat: Repeat, start: chrono::DateTime<chrono::Utc>) -> Option<String> {
32
match repeat {
33
Repeat::Never => None,
34
Repeat::Daily => Some("RRULE:FREQ=DAILY".to_owned()),
35
Repeat::Weekdays => Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR".to_owned()),
36
Repeat::Weekly => {
37
let day = match start.weekday() {
38
chrono::Weekday::Mon => "MO",
39
chrono::Weekday::Tue => "TU",
40
chrono::Weekday::Wed => "WE",
41
chrono::Weekday::Thu => "TH",
42
chrono::Weekday::Fri => "FR",
43
chrono::Weekday::Sat => "SA",
44
chrono::Weekday::Sun => "SU",
45
};
46
Some(format!("RRULE:FREQ=WEEKLY;BYDAY={day}"))
47
}
48
}
49
}
50
51
pub fn google_event_body(draft: &GoogleEventDraft) -> Value {
52
let mut description = draft.details.clone();
53
if let Some(join_url) = &draft.join_url {
54
if !description.is_empty() {
55
description.push_str("\n\n");
56
}
57
description.push_str(join_url);
58
}
59
let mut body = json!({
60
"summary": draft.subject,
61
"start": {
62
"dateTime": draft.start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
63
"timeZone": "UTC",
64
},
65
"end": {
66
"dateTime": draft.end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
67
"timeZone": "UTC",
68
},
69
"attendees": draft.attendees.iter().map(|attendee| json!({
70
"email": attendee.address,
71
"displayName": attendee.name,
72
})).collect::<Vec<_>>(),
73
});
74
if let Some(join_url) = &draft.join_url {
75
body["location"] = json!(join_url);
76
}
77
if !description.is_empty() {
78
body["description"] = json!(description);
79
}
80
if let Some(rrule) = rrule_for_repeat(draft.repeat, draft.start) {
81
body["recurrence"] = json!([rrule]);
82
}
83
let _ = (draft.start.hour(), draft.start.minute());
84
body
85
}
86
87
pub fn google_rsvp_status(reply: Reply) -> &'static str {
88
match reply {
89
Reply::Accept => "accepted",
90
Reply::Tentative => "tentative",
91
Reply::Decline => "declined",
92
}
93
}
94
95
pub fn google_rsvp_query(send_updates: bool) -> String {
96
format!(
97
"sendUpdates={}",
98
if send_updates { "all" } else { "none" }
99
)
100
}
101
102
#[cfg(test)]
103
mod tests {
104
use chrono::TimeZone;
105
106
use super::*;
107
108
fn draft(repeat: Repeat) -> GoogleEventDraft {
109
GoogleEventDraft {
110
subject: "Sync".into(),
111
start: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap(),
112
end: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 30, 0).unwrap(),
113
attendees: vec![Attendee {
114
name: "Mara".into(),
115
address: "mara@example.com".into(),
116
}],
117
details: "Notes".into(),
118
join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
119
repeat,
120
}
121
}
122
123
#[test]
124
fn body_puts_join_link_in_location_and_description() {
125
let body = google_event_body(&draft(Repeat::Never));
126
assert_eq!(
127
body["location"],
128
"https://teams.microsoft.com/l/meetup-join/x"
129
);
130
assert!(
131
body["description"]
132
.as_str()
133
.unwrap()
134
.contains("teams.microsoft.com")
135
);
136
assert!(body.get("recurrence").is_none());
137
}
138
139
#[test]
140
fn weekdays_rrule_and_rsvp_query() {
141
assert_eq!(
142
rrule_for_repeat(
143
Repeat::Weekdays,
144
chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap()
145
)
146
.as_deref(),
147
Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR")
148
);
149
assert_eq!(google_rsvp_status(Reply::Decline), "declined");
150
assert_eq!(google_rsvp_query(true), "sendUpdates=all");
151
assert_eq!(google_rsvp_query(false), "sendUpdates=none");
152
}
153
}
@@ -0,0 +1,153 @@1
use chrono::{Datelike, Timelike};2
use serde_json::{Value, json};3
4
use crate::calendar::{Attendee, NewEvent, Repeat, Reply};5
6
#[derive(Debug, Clone, PartialEq, Eq)]7
pub struct GoogleEventDraft {8
pub subject: String,9
pub start: chrono::DateTime<chrono::Utc>,10
pub end: chrono::DateTime<chrono::Utc>,11
pub attendees: Vec<Attendee>,12
pub details: String,13
pub join_url: Option<String>,14
pub repeat: Repeat,15
}16
17
impl From<&NewEvent> for GoogleEventDraft {18
fn from(event: &NewEvent) -> Self {19
GoogleEventDraft {20
subject: event.subject.clone(),21
start: event.start,22
end: event.end,23
attendees: event.attendees.clone(),24
details: event.details.clone(),25
join_url: None,26
repeat: event.repeat,27
}28
}29
}30
31
pub fn rrule_for_repeat(repeat: Repeat, start: chrono::DateTime<chrono::Utc>) -> Option<String> {32
match repeat {33
Repeat::Never => None,34
Repeat::Daily => Some("RRULE:FREQ=DAILY".to_owned()),35
Repeat::Weekdays => Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR".to_owned()),36
Repeat::Weekly => {37
let day = match start.weekday() {38
chrono::Weekday::Mon => "MO",39
chrono::Weekday::Tue => "TU",40
chrono::Weekday::Wed => "WE",41
chrono::Weekday::Thu => "TH",42
chrono::Weekday::Fri => "FR",43
chrono::Weekday::Sat => "SA",44
chrono::Weekday::Sun => "SU",45
};46
Some(format!("RRULE:FREQ=WEEKLY;BYDAY={day}"))47
}48
}49
}50
51
pub fn google_event_body(draft: &GoogleEventDraft) -> Value {52
let mut description = draft.details.clone();53
if let Some(join_url) = &draft.join_url {54
if !description.is_empty() {55
description.push_str("\n\n");56
}57
description.push_str(join_url);58
}59
let mut body = json!({60
"summary": draft.subject,61
"start": {62
"dateTime": draft.start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),63
"timeZone": "UTC",64
},65
"end": {66
"dateTime": draft.end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),67
"timeZone": "UTC",68
},69
"attendees": draft.attendees.iter().map(|attendee| json!({70
"email": attendee.address,71
"displayName": attendee.name,72
})).collect::<Vec<_>>(),73
});74
if let Some(join_url) = &draft.join_url {75
body["location"] = json!(join_url);76
}77
if !description.is_empty() {78
body["description"] = json!(description);79
}80
if let Some(rrule) = rrule_for_repeat(draft.repeat, draft.start) {81
body["recurrence"] = json!([rrule]);82
}83
let _ = (draft.start.hour(), draft.start.minute());84
body85
}86
87
pub fn google_rsvp_status(reply: Reply) -> &'static str {88
match reply {89
Reply::Accept => "accepted",90
Reply::Tentative => "tentative",91
Reply::Decline => "declined",92
}93
}94
95
pub fn google_rsvp_query(send_updates: bool) -> String {96
format!(97
"sendUpdates={}",98
if send_updates { "all" } else { "none" }99
)100
}101
102
#[cfg(test)]103
mod tests {104
use chrono::TimeZone;105
106
use super::*;107
108
fn draft(repeat: Repeat) -> GoogleEventDraft {109
GoogleEventDraft {110
subject: "Sync".into(),111
start: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap(),112
end: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 30, 0).unwrap(),113
attendees: vec![Attendee {114
name: "Mara".into(),115
address: "mara@example.com".into(),116
}],117
details: "Notes".into(),118
join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),119
repeat,120
}121
}122
123
#[test]124
fn body_puts_join_link_in_location_and_description() {125
let body = google_event_body(&draft(Repeat::Never));126
assert_eq!(127
body["location"],128
"https://teams.microsoft.com/l/meetup-join/x"129
);130
assert!(131
body["description"]132
.as_str()133
.unwrap()134
.contains("teams.microsoft.com")135
);136
assert!(body.get("recurrence").is_none());137
}138
139
#[test]140
fn weekdays_rrule_and_rsvp_query() {141
assert_eq!(142
rrule_for_repeat(143
Repeat::Weekdays,144
chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap()145
)146
.as_deref(),147
Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR")148
);149
assert_eq!(google_rsvp_status(Reply::Decline), "declined");150
assert_eq!(google_rsvp_query(true), "sendUpdates=all");151
assert_eq!(google_rsvp_query(false), "sendUpdates=none");152
}153
}@@ -10,6 +10,7 @@ chrono.workspace = true
10
10
directories.workspace = true
11
11
rusqlite.workspace = true
12
12
scraper.workspace = true
13
serde = { workspace = true, features = ["derive"] }
13
14
serde_json.workspace = true
14
15
thiserror.workspace = true
15
16
@@ -10,6 +10,7 @@ chrono.workspace = true10
directories.workspace = true10
directories.workspace = true11
rusqlite.workspace = true11
rusqlite.workspace = true12
scraper.workspace = true12
scraper.workspace = true13
serde = { workspace = true, features = ["derive"] }13
serde_json.workspace = true14
serde_json.workspace = true14
thiserror.workspace = true15
thiserror.workspace = true15
16
@@ -0,0 +1,238 @@
1
use serde::{Deserialize, Serialize};
2
use serde_json::json;
3
4
use crate::error::Result;
5
use crate::store::Store;
6
7
pub const CALENDAR_ACCOUNTS_KEY: &str = "calendar.accounts";
8
9
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
10
#[serde(rename_all = "snake_case")]
11
pub enum CalendarProvider {
12
#[default]
13
Outlook,
14
Google,
15
}
16
17
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18
pub struct CalendarRef {
19
pub provider: CalendarProvider,
20
/// Stable account id (empty for the single Outlook mailbox).
21
#[serde(default)]
22
pub account_id: String,
23
/// Provider calendar id (`primary` for Google default, empty for Outlook).
24
#[serde(default)]
25
pub calendar_id: String,
26
}
27
28
impl CalendarRef {
29
pub fn outlook() -> Self {
30
CalendarRef {
31
provider: CalendarProvider::Outlook,
32
account_id: String::new(),
33
calendar_id: String::new(),
34
}
35
}
36
37
pub fn google(account_id: impl Into<String>, calendar_id: impl Into<String>) -> Self {
38
CalendarRef {
39
provider: CalendarProvider::Google,
40
account_id: account_id.into(),
41
calendar_id: calendar_id.into(),
42
}
43
}
44
45
pub fn key(&self) -> String {
46
format!(
47
"{}:{}:{}",
48
match self.provider {
49
CalendarProvider::Outlook => "outlook",
50
CalendarProvider::Google => "google",
51
},
52
self.account_id,
53
self.calendar_id
54
)
55
}
56
}
57
58
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59
pub struct GoogleCalendarInfo {
60
pub id: String,
61
pub summary: String,
62
#[serde(default = "default_true")]
63
pub selected: bool,
64
#[serde(default)]
65
pub primary: bool,
66
}
67
68
fn default_true() -> bool {
69
true
70
}
71
72
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
73
pub struct GoogleTokenSet {
74
#[serde(default)]
75
pub access_token: String,
76
#[serde(default)]
77
pub refresh_token: String,
78
/// Unix seconds when the access token expires.
79
#[serde(default)]
80
pub expires_at: i64,
81
}
82
83
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84
pub struct GoogleAccount {
85
pub id: String,
86
#[serde(default)]
87
pub email: String,
88
#[serde(default)]
89
pub calendars: Vec<GoogleCalendarInfo>,
90
#[serde(default)]
91
pub tokens: GoogleTokenSet,
92
}
93
94
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95
pub struct CalendarAccounts {
96
#[serde(default = "CalendarRef::outlook")]
97
pub home: CalendarRef,
98
/// Extra write targets beyond home (may include Google calendars).
99
#[serde(default)]
100
pub write_targets: Vec<CalendarRef>,
101
/// Show Outlook mailbox events in the calendar grid.
102
#[serde(default = "default_true")]
103
pub outlook_selected: bool,
104
#[serde(default)]
105
pub google_accounts: Vec<GoogleAccount>,
106
}
107
108
impl Default for CalendarAccounts {
109
fn default() -> Self {
110
CalendarAccounts {
111
home: CalendarRef::outlook(),
112
write_targets: Vec::new(),
113
outlook_selected: true,
114
google_accounts: Vec::new(),
115
}
116
}
117
}
118
119
impl CalendarAccounts {
120
pub fn from_json(text: &str) -> std::result::Result<Self, serde_json::Error> {
121
serde_json::from_str(text)
122
}
123
124
pub fn to_json(&self) -> String {
125
serde_json::to_string(self).unwrap_or_else(|_| json!({}).to_string())
126
}
127
128
pub fn has_google(&self) -> bool {
129
!self.google_accounts.is_empty()
130
}
131
132
pub fn google_account(&self, id: &str) -> Option<&GoogleAccount> {
133
self.google_accounts.iter().find(|account| account.id == id)
134
}
135
136
pub fn google_account_mut(&mut self, id: &str) -> Option<&mut GoogleAccount> {
137
self.google_accounts
138
.iter_mut()
139
.find(|account| account.id == id)
140
}
141
142
pub fn disconnect_google(&mut self, account_id: &str) {
143
self.google_accounts
144
.retain(|account| account.id != account_id);
145
if self.home.provider == CalendarProvider::Google && self.home.account_id == account_id {
146
self.home = CalendarRef::outlook();
147
}
148
self.write_targets
149
.retain(|target| !(target.provider == CalendarProvider::Google && target.account_id == account_id));
150
}
151
152
/// Home plus extra write targets, de-duplicated by key.
153
pub fn resolved_write_targets(&self) -> Vec<CalendarRef> {
154
let mut targets = vec![self.home.clone()];
155
for target in &self.write_targets {
156
if targets.iter().all(|existing| existing.key() != target.key()) {
157
targets.push(target.clone());
158
}
159
}
160
targets
161
}
162
}
163
164
pub fn load_calendar_accounts(store: &Store) -> CalendarAccounts {
165
store
166
.meta(CALENDAR_ACCOUNTS_KEY)
167
.ok()
168
.flatten()
169
.and_then(|json| CalendarAccounts::from_json(&json).ok())
170
.unwrap_or_default()
171
}
172
173
pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Result<()> {
174
store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())
175
}
176
177
#[cfg(test)]
178
mod tests {
179
use super::*;
180
use crate::store::Store;
181
use tempfile::tempdir;
182
183
#[test]
184
fn defaults_to_outlook_home() {
185
let accounts = CalendarAccounts::default();
186
assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
187
assert!(accounts.write_targets.is_empty());
188
assert!(!accounts.has_google());
189
}
190
191
#[test]
192
fn roundtrips_through_store_meta() {
193
let directory = tempdir().unwrap();
194
let store = Store::open(&directory.path().join("db.sqlite")).unwrap();
195
let mut accounts = CalendarAccounts::default();
196
accounts.google_accounts.push(GoogleAccount {
197
id: "g1".into(),
198
email: "joe@example.com".into(),
199
calendars: vec![GoogleCalendarInfo {
200
id: "primary".into(),
201
summary: "Joe".into(),
202
selected: true,
203
primary: true,
204
}],
205
tokens: GoogleTokenSet {
206
access_token: "access".into(),
207
refresh_token: "refresh".into(),
208
expires_at: 1,
209
},
210
});
211
accounts.home = CalendarRef::google("g1", "primary");
212
accounts.write_targets.push(CalendarRef::outlook());
213
save_calendar_accounts(&store, &accounts).unwrap();
214
let loaded = load_calendar_accounts(&store);
215
assert_eq!(loaded.home, accounts.home);
216
assert_eq!(loaded.google_accounts[0].email, "joe@example.com");
217
assert_eq!(loaded.resolved_write_targets().len(), 2);
218
}
219
220
#[test]
221
fn disconnect_clears_home_and_write_targets() {
222
let mut accounts = CalendarAccounts {
223
home: CalendarRef::google("g1", "primary"),
224
write_targets: vec![CalendarRef::google("g1", "work")],
225
outlook_selected: true,
226
google_accounts: vec![GoogleAccount {
227
id: "g1".into(),
228
email: "a@b.c".into(),
229
calendars: Vec::new(),
230
tokens: GoogleTokenSet::default(),
231
}],
232
};
233
accounts.disconnect_google("g1");
234
assert!(!accounts.has_google());
235
assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
236
assert!(accounts.write_targets.is_empty());
237
}
238
}
@@ -0,0 +1,238 @@1
use serde::{Deserialize, Serialize};2
use serde_json::json;3
4
use crate::error::Result;5
use crate::store::Store;6
7
pub const CALENDAR_ACCOUNTS_KEY: &str = "calendar.accounts";8
9
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]10
#[serde(rename_all = "snake_case")]11
pub enum CalendarProvider {12
#[default]13
Outlook,14
Google,15
}16
17
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]18
pub struct CalendarRef {19
pub provider: CalendarProvider,20
/// Stable account id (empty for the single Outlook mailbox).21
#[serde(default)]22
pub account_id: String,23
/// Provider calendar id (`primary` for Google default, empty for Outlook).24
#[serde(default)]25
pub calendar_id: String,26
}27
28
impl CalendarRef {29
pub fn outlook() -> Self {30
CalendarRef {31
provider: CalendarProvider::Outlook,32
account_id: String::new(),33
calendar_id: String::new(),34
}35
}36
37
pub fn google(account_id: impl Into<String>, calendar_id: impl Into<String>) -> Self {38
CalendarRef {39
provider: CalendarProvider::Google,40
account_id: account_id.into(),41
calendar_id: calendar_id.into(),42
}43
}44
45
pub fn key(&self) -> String {46
format!(47
"{}:{}:{}",48
match self.provider {49
CalendarProvider::Outlook => "outlook",50
CalendarProvider::Google => "google",51
},52
self.account_id,53
self.calendar_id54
)55
}56
}57
58
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]59
pub struct GoogleCalendarInfo {60
pub id: String,61
pub summary: String,62
#[serde(default = "default_true")]63
pub selected: bool,64
#[serde(default)]65
pub primary: bool,66
}67
68
fn default_true() -> bool {69
true70
}71
72
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]73
pub struct GoogleTokenSet {74
#[serde(default)]75
pub access_token: String,76
#[serde(default)]77
pub refresh_token: String,78
/// Unix seconds when the access token expires.79
#[serde(default)]80
pub expires_at: i64,81
}82
83
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]84
pub struct GoogleAccount {85
pub id: String,86
#[serde(default)]87
pub email: String,88
#[serde(default)]89
pub calendars: Vec<GoogleCalendarInfo>,90
#[serde(default)]91
pub tokens: GoogleTokenSet,92
}93
94
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]95
pub struct CalendarAccounts {96
#[serde(default = "CalendarRef::outlook")]97
pub home: CalendarRef,98
/// Extra write targets beyond home (may include Google calendars).99
#[serde(default)]100
pub write_targets: Vec<CalendarRef>,101
/// Show Outlook mailbox events in the calendar grid.102
#[serde(default = "default_true")]103
pub outlook_selected: bool,104
#[serde(default)]105
pub google_accounts: Vec<GoogleAccount>,106
}107
108
impl Default for CalendarAccounts {109
fn default() -> Self {110
CalendarAccounts {111
home: CalendarRef::outlook(),112
write_targets: Vec::new(),113
outlook_selected: true,114
google_accounts: Vec::new(),115
}116
}117
}118
119
impl CalendarAccounts {120
pub fn from_json(text: &str) -> std::result::Result<Self, serde_json::Error> {121
serde_json::from_str(text)122
}123
124
pub fn to_json(&self) -> String {125
serde_json::to_string(self).unwrap_or_else(|_| json!({}).to_string())126
}127
128
pub fn has_google(&self) -> bool {129
!self.google_accounts.is_empty()130
}131
132
pub fn google_account(&self, id: &str) -> Option<&GoogleAccount> {133
self.google_accounts.iter().find(|account| account.id == id)134
}135
136
pub fn google_account_mut(&mut self, id: &str) -> Option<&mut GoogleAccount> {137
self.google_accounts138
.iter_mut()139
.find(|account| account.id == id)140
}141
142
pub fn disconnect_google(&mut self, account_id: &str) {143
self.google_accounts144
.retain(|account| account.id != account_id);145
if self.home.provider == CalendarProvider::Google && self.home.account_id == account_id {146
self.home = CalendarRef::outlook();147
}148
self.write_targets149
.retain(|target| !(target.provider == CalendarProvider::Google && target.account_id == account_id));150
}151
152
/// Home plus extra write targets, de-duplicated by key.153
pub fn resolved_write_targets(&self) -> Vec<CalendarRef> {154
let mut targets = vec![self.home.clone()];155
for target in &self.write_targets {156
if targets.iter().all(|existing| existing.key() != target.key()) {157
targets.push(target.clone());158
}159
}160
targets161
}162
}163
164
pub fn load_calendar_accounts(store: &Store) -> CalendarAccounts {165
store166
.meta(CALENDAR_ACCOUNTS_KEY)167
.ok()168
.flatten()169
.and_then(|json| CalendarAccounts::from_json(&json).ok())170
.unwrap_or_default()171
}172
173
pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Result<()> {174
store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())175
}176
177
#[cfg(test)]178
mod tests {179
use super::*;180
use crate::store::Store;181
use tempfile::tempdir;182
183
#[test]184
fn defaults_to_outlook_home() {185
let accounts = CalendarAccounts::default();186
assert_eq!(accounts.home.provider, CalendarProvider::Outlook);187
assert!(accounts.write_targets.is_empty());188
assert!(!accounts.has_google());189
}190
191
#[test]192
fn roundtrips_through_store_meta() {193
let directory = tempdir().unwrap();194
let store = Store::open(&directory.path().join("db.sqlite")).unwrap();195
let mut accounts = CalendarAccounts::default();196
accounts.google_accounts.push(GoogleAccount {197
id: "g1".into(),198
email: "joe@example.com".into(),199
calendars: vec![GoogleCalendarInfo {200
id: "primary".into(),201
summary: "Joe".into(),202
selected: true,203
primary: true,204
}],205
tokens: GoogleTokenSet {206
access_token: "access".into(),207
refresh_token: "refresh".into(),208
expires_at: 1,209
},210
});211
accounts.home = CalendarRef::google("g1", "primary");212
accounts.write_targets.push(CalendarRef::outlook());213
save_calendar_accounts(&store, &accounts).unwrap();214
let loaded = load_calendar_accounts(&store);215
assert_eq!(loaded.home, accounts.home);216
assert_eq!(loaded.google_accounts[0].email, "joe@example.com");217
assert_eq!(loaded.resolved_write_targets().len(), 2);218
}219
220
#[test]221
fn disconnect_clears_home_and_write_targets() {222
let mut accounts = CalendarAccounts {223
home: CalendarRef::google("g1", "primary"),224
write_targets: vec![CalendarRef::google("g1", "work")],225
outlook_selected: true,226
google_accounts: vec![GoogleAccount {227
id: "g1".into(),228
email: "a@b.c".into(),229
calendars: Vec::new(),230
tokens: GoogleTokenSet::default(),231
}],232
};233
accounts.disconnect_google("g1");234
assert!(!accounts.has_google());235
assert_eq!(accounts.home.provider, CalendarProvider::Outlook);236
assert!(accounts.write_targets.is_empty());237
}238
}