BlueGit

ict rusty-teams

fix(calendar): offer sign-in when Google rejects the token (#103)

Co-authored-by: Daniel Däschle <daniel.daeschle@gmail.com>

metis Joe Mild · pushed by metis

Authored 2026-11-25 · 6 days ago

Hash
68207d3ebb17e4ac8587e5544de3dbf607c07b3b
Parent
befd73a1
6 files changed +143 −13
crates/app-state/src/backend.rs +7 −1
@@ -569,10 +569,16 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
569 569 match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
570 570 .await
571 571 {
572 Ok(google_events) => {
572 Ok((google_events, account_errors)) => {
573 573 // Only refreshed tokens: a calendar toggle made during the fetch stays.
574 574 let _ = store::merge_google_tokens(&store, &fetched_accounts);
575 575 combined.extend(google_events);
576 for message in account_errors {
577 crate::diagnostics::record(format!(
578 "calls: google account not loaded: {}",
579 shorten(&message)
580 ));
581 }
576 582 }
577 583 Err(error) => crate::diagnostics::record(format!(
578 584 "calls: google calendar not loaded: {}",
@@ -569,10 +569,16 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
569 match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
569 match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
570 .await
570 .await
571 {
571 {
572 Ok(google_events) => {
572 Ok((google_events, account_errors)) => {
573 // Only refreshed tokens: a calendar toggle made during the fetch stays.
573 // Only refreshed tokens: a calendar toggle made during the fetch stays.
574 let _ = store::merge_google_tokens(&store, &fetched_accounts);
574 let _ = store::merge_google_tokens(&store, &fetched_accounts);
575 combined.extend(google_events);
575 combined.extend(google_events);
576 for message in account_errors {
577 crate::diagnostics::record(format!(
578 "calls: google account not loaded: {}",
579 shorten(&message)
580 ));
581 }
576 }
582 }
577 Err(error) => crate::diagnostics::record(format!(
583 Err(error) => crate::diagnostics::record(format!(
578 "calls: google calendar not loaded: {}",
584 "calls: google calendar not loaded: {}",
crates/app-state/src/calendar_accounts_actions.rs +1 −1
@@ -418,7 +418,7 @@ async fn finish_google_connect(
418 418 },
419 419 };
420 420 let mut accounts = load_calendar_accounts(&store);
421 accounts.google_accounts.push(account);
421 accounts.connect_google(account);
422 422 save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
423 423 Ok(email)
424 424 }
@@ -418,7 +418,7 @@ async fn finish_google_connect(
418 },
418 },
419 };
419 };
420 let mut accounts = load_calendar_accounts(&store);
420 let mut accounts = load_calendar_accounts(&store);
421 accounts.google_accounts.push(account);
421 accounts.connect_google(account);
422 save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
422 save_calendar_accounts(&store, &accounts).map_err(|error| error.to_string())?;
423 Ok(email)
423 Ok(email)
424}
424}
crates/app-state/src/call/week.rs +20 −1
@@ -19,6 +19,8 @@ pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
19 19 pub struct CalendarLoadFailure {
20 20 pub source: CalendarSource,
21 21 pub message: String,
22 /// The user must sign in again. Retry would use the same rejected token.
23 pub sign_in: bool,
22 24 }
23 25
24 26 #[derive(Debug, Clone, Default)]
@@ -256,6 +258,7 @@ impl AppState {
256 258 Err(error) => failures.push(CalendarLoadFailure {
257 259 source: CalendarSource::Outlook,
258 260 message: error.to_string(),
261 sign_in: false,
259 262 }),
260 263 }
261 264 }
@@ -268,14 +271,22 @@ impl AppState {
268 271 )
269 272 .await
270 273 {
271 Ok(events) => {
274 Ok((events, account_errors)) => {
272 275 // Keep only refreshed tokens: a toggle made meanwhile must survive.
273 276 let _ = store::merge_google_tokens(&store, &fetched_accounts);
274 277 google_count = Some(events.len());
275 278 combined.extend(events);
279 for message in account_errors {
280 failures.push(CalendarLoadFailure {
281 source: CalendarSource::Google,
282 sign_in: crate::google_calendar_sync::needs_sign_in(&message),
283 message,
284 });
285 }
276 286 }
277 287 Err(error) => failures.push(CalendarLoadFailure {
278 288 source: CalendarSource::Google,
289 sign_in: crate::google_calendar_sync::needs_sign_in(&error),
279 290 message: error,
280 291 }),
281 292 }
@@ -292,12 +303,14 @@ impl AppState {
292 303 failures.push(CalendarLoadFailure {
293 304 source: CalendarSource::CalDav,
294 305 message,
306 sign_in: false,
295 307 });
296 308 }
297 309 }
298 310 Err(error) => failures.push(CalendarLoadFailure {
299 311 source: CalendarSource::CalDav,
300 312 message: error,
313 sign_in: false,
301 314 }),
302 315 }
303 316 }
@@ -309,12 +322,14 @@ impl AppState {
309 322 failures.push(CalendarLoadFailure {
310 323 source: CalendarSource::Ics,
311 324 message,
325 sign_in: false,
312 326 });
313 327 }
314 328 }
315 329 Err(error) => failures.push(CalendarLoadFailure {
316 330 source: CalendarSource::Ics,
317 331 message: error,
332 sign_in: false,
318 333 }),
319 334 }
320 335 }
@@ -337,6 +352,7 @@ impl AppState {
337 352 vec![CalendarLoadFailure {
338 353 source: CalendarSource::Outlook,
339 354 message: CALENDAR_LOAD_FAILURE.to_owned(),
355 sign_in: false,
340 356 }],
341 357 )
342 358 });
@@ -709,6 +725,7 @@ mod tests {
709 725 let failures = [CalendarLoadFailure {
710 726 source: CalendarSource::Outlook,
711 727 message: "HTTP 503".into(),
728 sign_in: false,
712 729 }];
713 730 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
714 731 .into_iter()
@@ -732,6 +749,7 @@ mod tests {
732 749 let failures = [CalendarLoadFailure {
733 750 source: CalendarSource::CalDav,
734 751 message: "CalDAV Work: timeout".into(),
752 sign_in: false,
735 753 }];
736 754 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &failures)
737 755 .into_iter()
@@ -747,6 +765,7 @@ mod tests {
747 765 let failures = [CalendarLoadFailure {
748 766 source: CalendarSource::Google,
749 767 message: "client_secret is missing".into(),
768 sign_in: false,
750 769 }];
751 770 assert_eq!(
752 771 load_summary(from, to, Some(3), None, None, 412, &failures),
@@ -19,6 +19,8 @@ pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
19pub struct CalendarLoadFailure {
19pub struct CalendarLoadFailure {
20 pub source: CalendarSource,
20 pub source: CalendarSource,
21 pub message: String,
21 pub message: String,
22 /// The user must sign in again. Retry would use the same rejected token.
23 pub sign_in: bool,
22}
24}
23
25
24#[derive(Debug, Clone, Default)]
26#[derive(Debug, Clone, Default)]
@@ -256,6 +258,7 @@ impl AppState {
256 Err(error) => failures.push(CalendarLoadFailure {
258 Err(error) => failures.push(CalendarLoadFailure {
257 source: CalendarSource::Outlook,
259 source: CalendarSource::Outlook,
258 message: error.to_string(),
260 message: error.to_string(),
261 sign_in: false,
259 }),
262 }),
260 }
263 }
261 }
264 }
@@ -268,14 +271,22 @@ impl AppState {
268 )
271 )
269 .await
272 .await
270 {
273 {
271 Ok(events) => {
274 Ok((events, account_errors)) => {
272 // Keep only refreshed tokens: a toggle made meanwhile must survive.
275 // Keep only refreshed tokens: a toggle made meanwhile must survive.
273 let _ = store::merge_google_tokens(&store, &fetched_accounts);
276 let _ = store::merge_google_tokens(&store, &fetched_accounts);
274 google_count = Some(events.len());
277 google_count = Some(events.len());
275 combined.extend(events);
278 combined.extend(events);
279 for message in account_errors {
280 failures.push(CalendarLoadFailure {
281 source: CalendarSource::Google,
282 sign_in: crate::google_calendar_sync::needs_sign_in(&message),
283 message,
284 });
285 }
276 }
286 }
277 Err(error) => failures.push(CalendarLoadFailure {
287 Err(error) => failures.push(CalendarLoadFailure {
278 source: CalendarSource::Google,
288 source: CalendarSource::Google,
289 sign_in: crate::google_calendar_sync::needs_sign_in(&error),
279 message: error,
290 message: error,
280 }),
291 }),
281 }
292 }
@@ -292,12 +303,14 @@ impl AppState {
292 failures.push(CalendarLoadFailure {
303 failures.push(CalendarLoadFailure {
293 source: CalendarSource::CalDav,
304 source: CalendarSource::CalDav,
294 message,
305 message,
306 sign_in: false,
295 });
307 });
296 }
308 }
297 }
309 }
298 Err(error) => failures.push(CalendarLoadFailure {
310 Err(error) => failures.push(CalendarLoadFailure {
299 source: CalendarSource::CalDav,
311 source: CalendarSource::CalDav,
300 message: error,
312 message: error,
313 sign_in: false,
301 }),
314 }),
302 }
315 }
303 }
316 }
@@ -309,12 +322,14 @@ impl AppState {
309 failures.push(CalendarLoadFailure {
322 failures.push(CalendarLoadFailure {
310 source: CalendarSource::Ics,
323 source: CalendarSource::Ics,
311 message,
324 message,
325 sign_in: false,
312 });
326 });
313 }
327 }
314 }
328 }
315 Err(error) => failures.push(CalendarLoadFailure {
329 Err(error) => failures.push(CalendarLoadFailure {
316 source: CalendarSource::Ics,
330 source: CalendarSource::Ics,
317 message: error,
331 message: error,
332 sign_in: false,
318 }),
333 }),
319 }
334 }
320 }
335 }
@@ -337,6 +352,7 @@ impl AppState {
337 vec![CalendarLoadFailure {
352 vec![CalendarLoadFailure {
338 source: CalendarSource::Outlook,
353 source: CalendarSource::Outlook,
339 message: CALENDAR_LOAD_FAILURE.to_owned(),
354 message: CALENDAR_LOAD_FAILURE.to_owned(),
355 sign_in: false,
340 }],
356 }],
341 )
357 )
342 });
358 });
@@ -709,6 +725,7 @@ mod tests {
709 let failures = [CalendarLoadFailure {
725 let failures = [CalendarLoadFailure {
710 source: CalendarSource::Outlook,
726 source: CalendarSource::Outlook,
711 message: "HTTP 503".into(),
727 message: "HTTP 503".into(),
728 sign_in: false,
712 }];
729 }];
713 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
730 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
714 .into_iter()
731 .into_iter()
@@ -732,6 +749,7 @@ mod tests {
732 let failures = [CalendarLoadFailure {
749 let failures = [CalendarLoadFailure {
733 source: CalendarSource::CalDav,
750 source: CalendarSource::CalDav,
734 message: "CalDAV Work: timeout".into(),
751 message: "CalDAV Work: timeout".into(),
752 sign_in: false,
735 }];
753 }];
736 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &failures)
754 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &failures)
737 .into_iter()
755 .into_iter()
@@ -747,6 +765,7 @@ mod tests {
747 let failures = [CalendarLoadFailure {
765 let failures = [CalendarLoadFailure {
748 source: CalendarSource::Google,
766 source: CalendarSource::Google,
749 message: "client_secret is missing".into(),
767 message: "client_secret is missing".into(),
768 sign_in: false,
750 }];
769 }];
751 assert_eq!(
770 assert_eq!(
752 load_summary(from, to, Some(3), None, None, 412, &failures),
771 load_summary(from, to, Some(3), None, None, 412, &failures),
crates/app-state/src/google_calendar_sync.rs +61 −7
@@ -11,18 +11,25 @@ pub async fn fetch_google_events(
11 11 accounts: &mut CalendarAccounts,
12 12 start: DateTime<Utc>,
13 13 end: DateTime<Utc>,
14 ) -> Result<Vec<CalendarEvent>, String> {
14 ) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {
15 15 let Some(oauth) = client_id_from_env() else {
16 16 // Connected accounts but no client id compiled in: say so instead of an empty week.
17 17 if accounts.has_google() {
18 18 return Err(missing_client_id());
19 19 }
20 return Ok(Vec::new());
20 return Ok((Vec::new(), Vec::new()));
21 21 };
22 22 let mut all = Vec::new();
23 // One rejected token must not hide calendars that still refresh.
24 let mut account_errors = Vec::new();
23 25 for index in 0..accounts.google_accounts.len() {
24 if !ensure_access_token(accounts, index, &oauth).await? {
25 continue;
26 match ensure_access_token(accounts, index, &oauth).await {
27 Ok(true) => {}
28 Ok(false) => continue,
29 Err(error) => {
30 remember_account_error(&mut account_errors, error);
31 continue;
32 }
26 33 }
27 34 let account = &accounts.google_accounts[index];
28 35 let access = account.tokens.access_token.clone();
@@ -62,7 +69,20 @@ pub async fn fetch_google_events(
62 69 }
63 70 }
64 71 }
65 Ok(all)
72 Ok((all, account_errors))
73 }
74
75 /// Keeps a sign-in failure ahead of any other account error. One notice is enough.
76 fn remember_account_error(errors: &mut Vec<String>, error: String) {
77 if errors.iter().any(|existing| needs_sign_in(existing)) && !needs_sign_in(&error) {
78 return;
79 }
80 if needs_sign_in(&error) {
81 errors.clear();
82 }
83 if errors.is_empty() {
84 errors.push(error);
85 }
66 86 }
67 87
68 88 pub async fn insert_google_event(
@@ -164,8 +184,10 @@ async fn ensure_access_token(
164 184 };
165 185 }
166 186 Err(error) => {
167 crate::diagnostics::record(format!("calls: google token refresh failed: {error}"));
168 return Ok(false);
187 let message = format!("google token refresh failed: {error}");
188 crate::diagnostics::record(format!("calls: {message}"));
189 // Surface to week load as CalendarLoadFailure — never Ok([]) for auth fail.
190 return Err(message);
169 191 }
170 192 }
171 193 }
@@ -175,3 +197,35 @@ async fn ensure_access_token(
175 197 fn missing_client_id() -> String {
176 198 app_base::ui_locale::tr("settings.calendar.not_in_build")
177 199 }
200
201 /// True when another fetch cannot succeed until the user signs in to Google again.
202 pub fn needs_sign_in(message: &str) -> bool {
203 message.starts_with("google token refresh failed:") || message == missing_client_id()
204 }
205
206 #[cfg(test)]
207 mod tests {
208 use super::{needs_sign_in, remember_account_error};
209
210 #[test]
211 fn a_rejected_token_does_not_hide_another_accounts_error_notice() {
212 let mut errors = Vec::new();
213 remember_account_error(&mut errors, "HTTP 503".into());
214 remember_account_error(
215 &mut errors,
216 "google token refresh failed: HTTP 400: invalid_grant".into(),
217 );
218 remember_account_error(&mut errors, "HTTP 500".into());
219 assert_eq!(errors.len(), 1);
220 assert!(needs_sign_in(&errors[0]));
221 }
222
223 #[test]
224 fn google_sign_in_is_required_only_for_a_rejected_token() {
225 assert!(needs_sign_in(
226 "google token refresh failed: HTTP 400: invalid_grant"
227 ));
228 assert!(!needs_sign_in("HTTP 503"));
229 assert!(!needs_sign_in("client_secret is missing"));
230 }
231 }
@@ -11,18 +11,25 @@ pub async fn fetch_google_events(
11 accounts: &mut CalendarAccounts,
11 accounts: &mut CalendarAccounts,
12 start: DateTime<Utc>,
12 start: DateTime<Utc>,
13 end: DateTime<Utc>,
13 end: DateTime<Utc>,
14) -> Result<Vec<CalendarEvent>, String> {
14) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {
15 let Some(oauth) = client_id_from_env() else {
15 let Some(oauth) = client_id_from_env() else {
16 // Connected accounts but no client id compiled in: say so instead of an empty week.
16 // Connected accounts but no client id compiled in: say so instead of an empty week.
17 if accounts.has_google() {
17 if accounts.has_google() {
18 return Err(missing_client_id());
18 return Err(missing_client_id());
19 }
19 }
20 return Ok(Vec::new());
20 return Ok((Vec::new(), Vec::new()));
21 };
21 };
22 let mut all = Vec::new();
22 let mut all = Vec::new();
23 // One rejected token must not hide calendars that still refresh.
24 let mut account_errors = Vec::new();
23 for index in 0..accounts.google_accounts.len() {
25 for index in 0..accounts.google_accounts.len() {
24 if !ensure_access_token(accounts, index, &oauth).await? {
26 match ensure_access_token(accounts, index, &oauth).await {
25 continue;
27 Ok(true) => {}
28 Ok(false) => continue,
29 Err(error) => {
30 remember_account_error(&mut account_errors, error);
31 continue;
32 }
26 }
33 }
27 let account = &accounts.google_accounts[index];
34 let account = &accounts.google_accounts[index];
28 let access = account.tokens.access_token.clone();
35 let access = account.tokens.access_token.clone();
@@ -62,7 +69,20 @@ pub async fn fetch_google_events(
62 }
69 }
63 }
70 }
64 }
71 }
65 Ok(all)
72 Ok((all, account_errors))
73}
74
75/// Keeps a sign-in failure ahead of any other account error. One notice is enough.
76fn remember_account_error(errors: &mut Vec<String>, error: String) {
77 if errors.iter().any(|existing| needs_sign_in(existing)) && !needs_sign_in(&error) {
78 return;
79 }
80 if needs_sign_in(&error) {
81 errors.clear();
82 }
83 if errors.is_empty() {
84 errors.push(error);
85 }
66}
86}
67
87
68pub async fn insert_google_event(
88pub async fn insert_google_event(
@@ -164,8 +184,10 @@ async fn ensure_access_token(
164 };
184 };
165 }
185 }
166 Err(error) => {
186 Err(error) => {
167 crate::diagnostics::record(format!("calls: google token refresh failed: {error}"));
187 let message = format!("google token refresh failed: {error}");
168 return Ok(false);
188 crate::diagnostics::record(format!("calls: {message}"));
189 // Surface to week load as CalendarLoadFailure — never Ok([]) for auth fail.
190 return Err(message);
169 }
191 }
170 }
192 }
171 }
193 }
@@ -175,3 +197,35 @@ async fn ensure_access_token(
175fn missing_client_id() -> String {
197fn missing_client_id() -> String {
176 app_base::ui_locale::tr("settings.calendar.not_in_build")
198 app_base::ui_locale::tr("settings.calendar.not_in_build")
177}
199}
200
201/// True when another fetch cannot succeed until the user signs in to Google again.
202pub fn needs_sign_in(message: &str) -> bool {
203 message.starts_with("google token refresh failed:") || message == missing_client_id()
204}
205
206#[cfg(test)]
207mod tests {
208 use super::{needs_sign_in, remember_account_error};
209
210 #[test]
211 fn a_rejected_token_does_not_hide_another_accounts_error_notice() {
212 let mut errors = Vec::new();
213 remember_account_error(&mut errors, "HTTP 503".into());
214 remember_account_error(
215 &mut errors,
216 "google token refresh failed: HTTP 400: invalid_grant".into(),
217 );
218 remember_account_error(&mut errors, "HTTP 500".into());
219 assert_eq!(errors.len(), 1);
220 assert!(needs_sign_in(&errors[0]));
221 }
222
223 #[test]
224 fn google_sign_in_is_required_only_for_a_rejected_token() {
225 assert!(needs_sign_in(
226 "google token refresh failed: HTTP 400: invalid_grant"
227 ));
228 assert!(!needs_sign_in("HTTP 503"));
229 assert!(!needs_sign_in("client_secret is missing"));
230 }
231}
crates/app/src/views/calendar_view.rs +15 −3
@@ -766,9 +766,15 @@ fn load_notices(
766 766 );
767 767 }
768 768 for failure in failures {
769 let retry = state.clone();
769 let action = state.clone();
770 let sign_in = failure.sign_in;
770 771 let mut args = std::collections::HashMap::new();
771 772 args.insert("source".to_owned(), failure.source.label().to_owned());
773 let label = if sign_in {
774 tr("auth.sign_in")
775 } else {
776 tr("common.retry")
777 };
772 778 rows.push(
773 779 h_flex()
774 780 .flex_none()
@@ -796,10 +802,16 @@ fn load_notices(
796 802 )))
797 803 .xsmall()
798 804 .outline()
799 .label(tr("common.retry"))
805 .label(label)
800 806 .tooltip(failure.message.clone())
801 807 .on_click(move |_, _, cx| {
802 retry.update(cx, |state, cx| state.retry_calendar_week(cx))
808 action.update(cx, |state, cx| {
809 if sign_in {
810 state.connect_google_calendar(cx);
811 } else {
812 state.retry_calendar_week(cx);
813 }
814 })
803 815 }),
804 816 ),
805 817 );
@@ -766,9 +766,15 @@ fn load_notices(
766 );
766 );
767 }
767 }
768 for failure in failures {
768 for failure in failures {
769 let retry = state.clone();
769 let action = state.clone();
770 let sign_in = failure.sign_in;
770 let mut args = std::collections::HashMap::new();
771 let mut args = std::collections::HashMap::new();
771 args.insert("source".to_owned(), failure.source.label().to_owned());
772 args.insert("source".to_owned(), failure.source.label().to_owned());
773 let label = if sign_in {
774 tr("auth.sign_in")
775 } else {
776 tr("common.retry")
777 };
772 rows.push(
778 rows.push(
773 h_flex()
779 h_flex()
774 .flex_none()
780 .flex_none()
@@ -796,10 +802,16 @@ fn load_notices(
796 )))
802 )))
797 .xsmall()
803 .xsmall()
798 .outline()
804 .outline()
799 .label(tr("common.retry"))
805 .label(label)
800 .tooltip(failure.message.clone())
806 .tooltip(failure.message.clone())
801 .on_click(move |_, _, cx| {
807 .on_click(move |_, _, cx| {
802 retry.update(cx, |state, cx| state.retry_calendar_week(cx))
808 action.update(cx, |state, cx| {
809 if sign_in {
810 state.connect_google_calendar(cx);
811 } else {
812 state.retry_calendar_week(cx);
813 }
814 })
803 }),
815 }),
804 ),
816 ),
805 );
817 );
crates/store/src/calendar_accounts.rs +39 −0
@@ -212,6 +212,20 @@ impl CalendarAccounts {
212 212 .find(|account| account.id == id)
213 213 }
214 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
215 229 pub fn disconnect_google(&mut self, account_id: &str) {
216 230 self.google_accounts
217 231 .retain(|account| account.id != account_id);
@@ -402,6 +416,31 @@ mod tests {
402 416 assert!(accounts.write_targets.is_empty());
403 417 }
404 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
405 444 #[test]
406 445 fn disconnect_caldav_clears_refs() {
407 446 let mut accounts = CalendarAccounts {
@@ -212,6 +212,20 @@ impl CalendarAccounts {
212 .find(|account| account.id == id)
212 .find(|account| account.id == id)
213 }
213 }
214
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
215 pub fn disconnect_google(&mut self, account_id: &str) {
229 pub fn disconnect_google(&mut self, account_id: &str) {
216 self.google_accounts
230 self.google_accounts
217 .retain(|account| account.id != account_id);
231 .retain(|account| account.id != account_id);
@@ -402,6 +416,31 @@ mod tests {
402 assert!(accounts.write_targets.is_empty());
416 assert!(accounts.write_targets.is_empty());
403 }
417 }
404
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
405 #[test]
444 #[test]
406 fn disconnect_caldav_clears_refs() {
445 fn disconnect_caldav_clears_refs() {
407 let mut accounts = CalendarAccounts {
446 let mut accounts = CalendarAccounts {