BlueGit

ict rusty-teams

Files

rusty-teams / crates / store / src / calendar_accounts.rs

calendar_accounts.rs

calendar_accounts.rs 7.3 KiB Download Raw
1use serde::{Deserialize, Serialize};
2use serde_json::json;
3
4use crate::error::Result;
5use crate::store::Store;
6
7pub const CALENDAR_ACCOUNTS_KEY: &str = "calendar.accounts";
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
10#[serde(rename_all = "snake_case")]
11pub enum CalendarProvider {
12 #[default]
13 Outlook,
14 Google,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub 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
28impl 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)]
59pub 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
68fn default_true() -> bool {
69 true
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
73pub 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)]
84pub 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)]
95pub 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
108impl 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
119impl CalendarAccounts {
120 pub fn from_json(text: &str) -> std::result::Result<Self, serde_json::Error> {
121 serde_json::from_str(text)
122 }
123
124 pub fn to_json(&self) -> String {
125 serde_json::to_string(self).unwrap_or_else(|_| json!({}).to_string())
126 }
127
128 pub fn has_google(&self) -> bool {
129 !self.google_accounts.is_empty()
130 }
131
132 pub fn google_account(&self, id: &str) -> Option<&GoogleAccount> {
133 self.google_accounts.iter().find(|account| account.id == id)
134 }
135
136 pub fn google_account_mut(&mut self, id: &str) -> Option<&mut GoogleAccount> {
137 self.google_accounts
138 .iter_mut()
139 .find(|account| account.id == id)
140 }
141
142 pub fn disconnect_google(&mut self, account_id: &str) {
143 self.google_accounts
144 .retain(|account| account.id != account_id);
145 if self.home.provider == CalendarProvider::Google && self.home.account_id == account_id {
146 self.home = CalendarRef::outlook();
147 }
148 self.write_targets.retain(|target| {
149 !(target.provider == CalendarProvider::Google && target.account_id == account_id)
150 });
151 }
152
153 /// Home plus extra write targets, de-duplicated by key.
154 pub fn resolved_write_targets(&self) -> Vec<CalendarRef> {
155 let mut targets = vec![self.home.clone()];
156 for target in &self.write_targets {
157 if targets
158 .iter()
159 .all(|existing| existing.key() != target.key())
160 {
161 targets.push(target.clone());
162 }
163 }
164 targets
165 }
166}
167
168pub fn load_calendar_accounts(store: &Store) -> CalendarAccounts {
169 store
170 .meta(CALENDAR_ACCOUNTS_KEY)
171 .ok()
172 .flatten()
173 .and_then(|json| CalendarAccounts::from_json(&json).ok())
174 .unwrap_or_default()
175}
176
177pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Result<()> {
178 store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184 use crate::store::Store;
185 use tempfile::tempdir;
186
187 #[test]
188 fn defaults_to_outlook_home() {
189 let accounts = CalendarAccounts::default();
190 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
191 assert!(accounts.write_targets.is_empty());
192 assert!(!accounts.has_google());
193 }
194
195 #[test]
196 fn roundtrips_through_store_meta() {
197 let directory = tempdir().unwrap();
198 let store = Store::open(&directory.path().join("db.sqlite")).unwrap();
199 let mut accounts = CalendarAccounts::default();
200 accounts.google_accounts.push(GoogleAccount {
201 id: "g1".into(),
202 email: "joe@example.com".into(),
203 calendars: vec![GoogleCalendarInfo {
204 id: "primary".into(),
205 summary: "Joe".into(),
206 selected: true,
207 primary: true,
208 }],
209 tokens: GoogleTokenSet {
210 access_token: "access".into(),
211 refresh_token: "refresh".into(),
212 expires_at: 1,
213 },
214 });
215 accounts.home = CalendarRef::google("g1", "primary");
216 accounts.write_targets.push(CalendarRef::outlook());
217 save_calendar_accounts(&store, &accounts).unwrap();
218 let loaded = load_calendar_accounts(&store);
219 assert_eq!(loaded.home, accounts.home);
220 assert_eq!(loaded.google_accounts[0].email, "joe@example.com");
221 assert_eq!(loaded.resolved_write_targets().len(), 2);
222 }
223
224 #[test]
225 fn disconnect_clears_home_and_write_targets() {
226 let mut accounts = CalendarAccounts {
227 home: CalendarRef::google("g1", "primary"),
228 write_targets: vec![CalendarRef::google("g1", "work")],
229 outlook_selected: true,
230 google_accounts: vec![GoogleAccount {
231 id: "g1".into(),
232 email: "a@b.c".into(),
233 calendars: Vec::new(),
234 tokens: GoogleTokenSet::default(),
235 }],
236 };
237 accounts.disconnect_google("g1");
238 assert!(!accounts.has_google());
239 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
240 assert!(accounts.write_targets.is_empty());
241 }
242}