| 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 | CalDav, |
| 16 | } |
| 17 | |
| 18 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 19 | pub struct CalendarRef { |
| 20 | pub provider: CalendarProvider, |
| 21 | /// Stable account id (empty for the single Outlook mailbox). |
| 22 | #[serde(default)] |
| 23 | pub account_id: String, |
| 24 | /// Provider calendar id (`primary` for Google default, empty for Outlook, href for CalDAV). |
| 25 | #[serde(default)] |
| 26 | pub calendar_id: String, |
| 27 | } |
| 28 | |
| 29 | impl CalendarRef { |
| 30 | pub fn outlook() -> Self { |
| 31 | CalendarRef { |
| 32 | provider: CalendarProvider::Outlook, |
| 33 | account_id: String::new(), |
| 34 | calendar_id: String::new(), |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | pub fn google(account_id: impl Into<String>, calendar_id: impl Into<String>) -> Self { |
| 39 | CalendarRef { |
| 40 | provider: CalendarProvider::Google, |
| 41 | account_id: account_id.into(), |
| 42 | calendar_id: calendar_id.into(), |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | pub fn caldav(account_id: impl Into<String>, calendar_id: impl Into<String>) -> Self { |
| 47 | CalendarRef { |
| 48 | provider: CalendarProvider::CalDav, |
| 49 | account_id: account_id.into(), |
| 50 | calendar_id: calendar_id.into(), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | pub fn key(&self) -> String { |
| 55 | format!( |
| 56 | "{}:{}:{}", |
| 57 | match self.provider { |
| 58 | CalendarProvider::Outlook => "outlook", |
| 59 | CalendarProvider::Google => "google", |
| 60 | CalendarProvider::CalDav => "caldav", |
| 61 | }, |
| 62 | self.account_id, |
| 63 | self.calendar_id |
| 64 | ) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 69 | pub struct GoogleCalendarInfo { |
| 70 | pub id: String, |
| 71 | pub summary: String, |
| 72 | #[serde(default = "default_true")] |
| 73 | pub selected: bool, |
| 74 | #[serde(default)] |
| 75 | pub primary: bool, |
| 76 | } |
| 77 | |
| 78 | fn default_true() -> bool { |
| 79 | true |
| 80 | } |
| 81 | |
| 82 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 83 | pub struct GoogleTokenSet { |
| 84 | #[serde(default)] |
| 85 | pub access_token: String, |
| 86 | #[serde(default)] |
| 87 | pub refresh_token: String, |
| 88 | /// Unix seconds when the access token expires. |
| 89 | #[serde(default)] |
| 90 | pub expires_at: i64, |
| 91 | } |
| 92 | |
| 93 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 94 | pub struct GoogleAccount { |
| 95 | pub id: String, |
| 96 | #[serde(default)] |
| 97 | pub email: String, |
| 98 | #[serde(default)] |
| 99 | pub calendars: Vec<GoogleCalendarInfo>, |
| 100 | #[serde(default)] |
| 101 | pub tokens: GoogleTokenSet, |
| 102 | } |
| 103 | |
| 104 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 105 | pub struct CalDavCalendarInfo { |
| 106 | /// Collection href (calendar id). |
| 107 | pub id: String, |
| 108 | pub summary: String, |
| 109 | #[serde(default = "default_true")] |
| 110 | pub selected: bool, |
| 111 | #[serde(default)] |
| 112 | pub writable: bool, |
| 113 | #[serde(default)] |
| 114 | pub color: Option<String>, |
| 115 | } |
| 116 | |
| 117 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 118 | pub struct CalDavAccount { |
| 119 | pub id: String, |
| 120 | /// Normalized base URL without userinfo. |
| 121 | pub url: String, |
| 122 | pub username: String, |
| 123 | #[serde(default)] |
| 124 | pub display_name: String, |
| 125 | #[serde(default)] |
| 126 | pub calendars: Vec<CalDavCalendarInfo>, |
| 127 | /// mailto: addresses from calendar-user-address-set. |
| 128 | #[serde(default)] |
| 129 | pub user_addresses: Vec<String>, |
| 130 | #[serde(default)] |
| 131 | pub schedule_outbox: Option<String>, |
| 132 | } |
| 133 | |
| 134 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 135 | pub struct IcsSubscription { |
| 136 | pub id: String, |
| 137 | pub url: String, |
| 138 | pub summary: String, |
| 139 | #[serde(default = "default_true")] |
| 140 | pub selected: bool, |
| 141 | } |
| 142 | |
| 143 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 144 | pub struct CalendarAccounts { |
| 145 | #[serde(default = "CalendarRef::outlook")] |
| 146 | pub home: CalendarRef, |
| 147 | /// Extra write targets beyond home (may include Google / CalDAV calendars). |
| 148 | #[serde(default)] |
| 149 | pub write_targets: Vec<CalendarRef>, |
| 150 | /// Show Outlook mailbox events in the calendar grid. |
| 151 | #[serde(default = "default_true")] |
| 152 | pub outlook_selected: bool, |
| 153 | #[serde(default)] |
| 154 | pub google_accounts: Vec<GoogleAccount>, |
| 155 | #[serde(default)] |
| 156 | pub caldav_accounts: Vec<CalDavAccount>, |
| 157 | #[serde(default)] |
| 158 | pub ics_subscriptions: Vec<IcsSubscription>, |
| 159 | } |
| 160 | |
| 161 | impl Default for CalendarAccounts { |
| 162 | fn default() -> Self { |
| 163 | CalendarAccounts { |
| 164 | home: CalendarRef::outlook(), |
| 165 | write_targets: Vec::new(), |
| 166 | outlook_selected: true, |
| 167 | google_accounts: Vec::new(), |
| 168 | caldav_accounts: Vec::new(), |
| 169 | ics_subscriptions: Vec::new(), |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | impl CalendarAccounts { |
| 175 | pub fn from_json(text: &str) -> std::result::Result<Self, serde_json::Error> { |
| 176 | serde_json::from_str(text) |
| 177 | } |
| 178 | |
| 179 | pub fn to_json(&self) -> String { |
| 180 | serde_json::to_string(self).unwrap_or_else(|_| json!({}).to_string()) |
| 181 | } |
| 182 | |
| 183 | pub fn has_google(&self) -> bool { |
| 184 | !self.google_accounts.is_empty() |
| 185 | } |
| 186 | |
| 187 | pub fn has_caldav(&self) -> bool { |
| 188 | !self.caldav_accounts.is_empty() |
| 189 | } |
| 190 | |
| 191 | pub fn has_ics(&self) -> bool { |
| 192 | !self.ics_subscriptions.is_empty() |
| 193 | } |
| 194 | |
| 195 | pub fn google_account(&self, id: &str) -> Option<&GoogleAccount> { |
| 196 | self.google_accounts.iter().find(|account| account.id == id) |
| 197 | } |
| 198 | |
| 199 | pub fn google_account_mut(&mut self, id: &str) -> Option<&mut GoogleAccount> { |
| 200 | self.google_accounts |
| 201 | .iter_mut() |
| 202 | .find(|account| account.id == id) |
| 203 | } |
| 204 | |
| 205 | pub fn caldav_account(&self, id: &str) -> Option<&CalDavAccount> { |
| 206 | self.caldav_accounts.iter().find(|account| account.id == id) |
| 207 | } |
| 208 | |
| 209 | pub fn caldav_account_mut(&mut self, id: &str) -> Option<&mut CalDavAccount> { |
| 210 | self.caldav_accounts |
| 211 | .iter_mut() |
| 212 | .find(|account| account.id == id) |
| 213 | } |
| 214 | |
| 215 | /// Adds the account, or replaces the one with the same email and keeps its id. |
| 216 | pub fn connect_google(&mut self, mut account: GoogleAccount) { |
| 217 | if let Some(existing) = self |
| 218 | .google_accounts |
| 219 | .iter_mut() |
| 220 | .find(|item| item.email.eq_ignore_ascii_case(&account.email)) |
| 221 | { |
| 222 | account.id = existing.id.clone(); |
| 223 | *existing = account; |
| 224 | return; |
| 225 | } |
| 226 | self.google_accounts.push(account); |
| 227 | } |
| 228 | |
| 229 | pub fn disconnect_google(&mut self, account_id: &str) { |
| 230 | self.google_accounts |
| 231 | .retain(|account| account.id != account_id); |
| 232 | self.clear_refs_for(CalendarProvider::Google, account_id); |
| 233 | } |
| 234 | |
| 235 | pub fn disconnect_caldav(&mut self, account_id: &str) { |
| 236 | self.caldav_accounts |
| 237 | .retain(|account| account.id != account_id); |
| 238 | self.clear_refs_for(CalendarProvider::CalDav, account_id); |
| 239 | } |
| 240 | |
| 241 | pub fn disconnect_ics(&mut self, subscription_id: &str) { |
| 242 | self.ics_subscriptions |
| 243 | .retain(|subscription| subscription.id != subscription_id); |
| 244 | } |
| 245 | |
| 246 | fn clear_refs_for(&mut self, provider: CalendarProvider, account_id: &str) { |
| 247 | if self.home.provider == provider && self.home.account_id == account_id { |
| 248 | self.home = CalendarRef::outlook(); |
| 249 | } |
| 250 | self.write_targets |
| 251 | .retain(|target| !(target.provider == provider && target.account_id == account_id)); |
| 252 | } |
| 253 | |
| 254 | /// Home plus extra write targets, de-duplicated by key. |
| 255 | pub fn resolved_write_targets(&self) -> Vec<CalendarRef> { |
| 256 | let mut targets = vec![self.home.clone()]; |
| 257 | for target in &self.write_targets { |
| 258 | if targets |
| 259 | .iter() |
| 260 | .all(|existing| existing.key() != target.key()) |
| 261 | { |
| 262 | targets.push(target.clone()); |
| 263 | } |
| 264 | } |
| 265 | targets |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | pub fn load_calendar_accounts(store: &Store) -> CalendarAccounts { |
| 270 | store |
| 271 | .meta(CALENDAR_ACCOUNTS_KEY) |
| 272 | .ok() |
| 273 | .flatten() |
| 274 | .and_then(|json| CalendarAccounts::from_json(&json).ok()) |
| 275 | .unwrap_or_default() |
| 276 | } |
| 277 | |
| 278 | pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Result<()> { |
| 279 | store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json()) |
| 280 | } |
| 281 | |
| 282 | /// Save Google tokens refreshed during a fetch without touching anything else. |
| 283 | /// |
| 284 | /// A fetch works on a copy of the accounts it read before it started. Saving that copy |
| 285 | /// back would undo a calendar toggle the user made meanwhile, so only tokens are merged |
| 286 | /// into the accounts as they are stored now. |
| 287 | pub fn merge_google_tokens(store: &Store, fetched: &CalendarAccounts) -> Result<()> { |
| 288 | let mut current = load_calendar_accounts(store); |
| 289 | let mut changed = false; |
| 290 | for account in &mut current.google_accounts { |
| 291 | if let Some(fresh) = fetched.google_account(&account.id) |
| 292 | && fresh.tokens != account.tokens |
| 293 | { |
| 294 | account.tokens = fresh.tokens.clone(); |
| 295 | changed = true; |
| 296 | } |
| 297 | } |
| 298 | if changed { |
| 299 | save_calendar_accounts(store, ¤t)?; |
| 300 | } |
| 301 | Ok(()) |
| 302 | } |
| 303 | |
| 304 | /// Keep CalDAV metadata that a fetch refreshed without clobbering toggles. |
| 305 | pub fn merge_caldav_metadata(store: &Store, fetched: &CalendarAccounts) -> Result<()> { |
| 306 | let mut current = load_calendar_accounts(store); |
| 307 | let mut changed = false; |
| 308 | for account in &mut current.caldav_accounts { |
| 309 | if let Some(fresh) = fetched.caldav_account(&account.id) { |
| 310 | if fresh.user_addresses != account.user_addresses { |
| 311 | account.user_addresses = fresh.user_addresses.clone(); |
| 312 | changed = true; |
| 313 | } |
| 314 | if fresh.schedule_outbox != account.schedule_outbox { |
| 315 | account.schedule_outbox = fresh.schedule_outbox.clone(); |
| 316 | changed = true; |
| 317 | } |
| 318 | for calendar in &mut account.calendars { |
| 319 | if let Some(fresh_cal) = fresh.calendars.iter().find(|c| c.id == calendar.id) |
| 320 | && (fresh_cal.summary != calendar.summary |
| 321 | || fresh_cal.writable != calendar.writable |
| 322 | || fresh_cal.color != calendar.color) |
| 323 | { |
| 324 | calendar.summary = fresh_cal.summary.clone(); |
| 325 | calendar.writable = fresh_cal.writable; |
| 326 | calendar.color = fresh_cal.color.clone(); |
| 327 | changed = true; |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | if changed { |
| 333 | save_calendar_accounts(store, ¤t)?; |
| 334 | } |
| 335 | Ok(()) |
| 336 | } |
| 337 | |
| 338 | #[cfg(test)] |
| 339 | mod tests { |
| 340 | use super::*; |
| 341 | use crate::store::Store; |
| 342 | use tempfile::tempdir; |
| 343 | |
| 344 | #[test] |
| 345 | fn defaults_to_outlook_home() { |
| 346 | let accounts = CalendarAccounts::default(); |
| 347 | assert_eq!(accounts.home.provider, CalendarProvider::Outlook); |
| 348 | assert!(accounts.write_targets.is_empty()); |
| 349 | assert!(!accounts.has_google()); |
| 350 | assert!(!accounts.has_caldav()); |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn roundtrips_through_store_meta() { |
| 355 | let directory = tempdir().unwrap(); |
| 356 | let store = Store::open(&directory.path().join("db.sqlite")).unwrap(); |
| 357 | let mut accounts = CalendarAccounts::default(); |
| 358 | accounts.google_accounts.push(GoogleAccount { |
| 359 | id: "g1".into(), |
| 360 | email: "joe@example.com".into(), |
| 361 | calendars: vec![GoogleCalendarInfo { |
| 362 | id: "primary".into(), |
| 363 | summary: "Joe".into(), |
| 364 | selected: true, |
| 365 | primary: true, |
| 366 | }], |
| 367 | tokens: GoogleTokenSet { |
| 368 | access_token: "access".into(), |
| 369 | refresh_token: "refresh".into(), |
| 370 | expires_at: 1, |
| 371 | }, |
| 372 | }); |
| 373 | accounts.caldav_accounts.push(CalDavAccount { |
| 374 | id: "c1".into(), |
| 375 | url: "https://cloud.example/remote.php/dav/".into(), |
| 376 | username: "joe".into(), |
| 377 | display_name: "Nextcloud".into(), |
| 378 | calendars: vec![CalDavCalendarInfo { |
| 379 | id: "/calendars/joe/personal/".into(), |
| 380 | summary: "Personal".into(), |
| 381 | selected: true, |
| 382 | writable: true, |
| 383 | color: None, |
| 384 | }], |
| 385 | user_addresses: vec!["mailto:joe@example.com".into()], |
| 386 | schedule_outbox: None, |
| 387 | }); |
| 388 | accounts.home = CalendarRef::caldav("c1", "/calendars/joe/personal/"); |
| 389 | accounts.write_targets.push(CalendarRef::outlook()); |
| 390 | save_calendar_accounts(&store, &accounts).unwrap(); |
| 391 | let loaded = load_calendar_accounts(&store); |
| 392 | assert_eq!(loaded.home, accounts.home); |
| 393 | assert_eq!(loaded.google_accounts[0].email, "joe@example.com"); |
| 394 | assert_eq!(loaded.caldav_accounts[0].username, "joe"); |
| 395 | assert_eq!(loaded.resolved_write_targets().len(), 2); |
| 396 | } |
| 397 | |
| 398 | #[test] |
| 399 | fn disconnect_clears_home_and_write_targets() { |
| 400 | let mut accounts = CalendarAccounts { |
| 401 | home: CalendarRef::google("g1", "primary"), |
| 402 | write_targets: vec![CalendarRef::google("g1", "work")], |
| 403 | outlook_selected: true, |
| 404 | google_accounts: vec![GoogleAccount { |
| 405 | id: "g1".into(), |
| 406 | email: "a@b.c".into(), |
| 407 | calendars: Vec::new(), |
| 408 | tokens: GoogleTokenSet::default(), |
| 409 | }], |
| 410 | caldav_accounts: Vec::new(), |
| 411 | ics_subscriptions: Vec::new(), |
| 412 | }; |
| 413 | accounts.disconnect_google("g1"); |
| 414 | assert!(!accounts.has_google()); |
| 415 | assert_eq!(accounts.home.provider, CalendarProvider::Outlook); |
| 416 | assert!(accounts.write_targets.is_empty()); |
| 417 | } |
| 418 | |
| 419 | #[test] |
| 420 | fn connect_google_replaces_the_same_email_and_keeps_the_id() { |
| 421 | let mut accounts = CalendarAccounts { |
| 422 | google_accounts: vec![GoogleAccount { |
| 423 | id: "g1".into(), |
| 424 | email: "A@B.C".into(), |
| 425 | calendars: Vec::new(), |
| 426 | tokens: GoogleTokenSet::default(), |
| 427 | }], |
| 428 | ..CalendarAccounts::default() |
| 429 | }; |
| 430 | accounts.connect_google(GoogleAccount { |
| 431 | id: "fresh".into(), |
| 432 | email: "a@b.c".into(), |
| 433 | calendars: Vec::new(), |
| 434 | tokens: GoogleTokenSet { |
| 435 | access_token: "new".into(), |
| 436 | ..GoogleTokenSet::default() |
| 437 | }, |
| 438 | }); |
| 439 | assert_eq!(accounts.google_accounts.len(), 1); |
| 440 | assert_eq!(accounts.google_accounts[0].id, "g1"); |
| 441 | assert_eq!(accounts.google_accounts[0].tokens.access_token, "new"); |
| 442 | } |
| 443 | |
| 444 | #[test] |
| 445 | fn disconnect_caldav_clears_refs() { |
| 446 | let mut accounts = CalendarAccounts { |
| 447 | home: CalendarRef::caldav("c1", "/cal/"), |
| 448 | write_targets: vec![CalendarRef::caldav("c1", "/cal/")], |
| 449 | outlook_selected: true, |
| 450 | google_accounts: Vec::new(), |
| 451 | caldav_accounts: vec![CalDavAccount { |
| 452 | id: "c1".into(), |
| 453 | url: "https://example/dav/".into(), |
| 454 | username: "u".into(), |
| 455 | display_name: String::new(), |
| 456 | calendars: Vec::new(), |
| 457 | user_addresses: Vec::new(), |
| 458 | schedule_outbox: None, |
| 459 | }], |
| 460 | ics_subscriptions: Vec::new(), |
| 461 | }; |
| 462 | accounts.disconnect_caldav("c1"); |
| 463 | assert!(!accounts.has_caldav()); |
| 464 | assert_eq!(accounts.home.provider, CalendarProvider::Outlook); |
| 465 | assert!(accounts.write_targets.is_empty()); |
| 466 | } |
| 467 | |
| 468 | #[test] |
| 469 | fn token_merge_keeps_a_toggle_made_during_the_fetch() { |
| 470 | let directory = tempdir().unwrap(); |
| 471 | let store = Store::open(&directory.path().join("db.sqlite")).unwrap(); |
| 472 | let mut stored = CalendarAccounts::default(); |
| 473 | stored.google_accounts.push(GoogleAccount { |
| 474 | id: "g1".into(), |
| 475 | email: "me@example.com".into(), |
| 476 | calendars: vec![GoogleCalendarInfo { |
| 477 | id: "work".into(), |
| 478 | summary: "Work".into(), |
| 479 | selected: true, |
| 480 | primary: false, |
| 481 | }], |
| 482 | tokens: GoogleTokenSet::default(), |
| 483 | }); |
| 484 | save_calendar_accounts(&store, &stored).unwrap(); |
| 485 | let mut fetched = load_calendar_accounts(&store); |
| 486 | fetched.google_accounts[0].tokens.access_token = "fresh".into(); |
| 487 | stored.google_accounts[0].calendars[0].selected = false; |
| 488 | stored.outlook_selected = false; |
| 489 | save_calendar_accounts(&store, &stored).unwrap(); |
| 490 | |
| 491 | merge_google_tokens(&store, &fetched).unwrap(); |
| 492 | |
| 493 | let merged = load_calendar_accounts(&store); |
| 494 | assert!(!merged.outlook_selected); |
| 495 | assert!(!merged.google_accounts[0].calendars[0].selected); |
| 496 | assert_eq!(merged.google_accounts[0].tokens.access_token, "fresh"); |
| 497 | } |
| 498 | } |