| 1 | use chrono::{DateTime, Utc}; |
| 2 | use store::{CalendarAccounts, GoogleTokenSet, Store}; |
| 3 | |
| 4 | use chatsvc::{ |
| 5 | CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, google_rsvp_status, |
| 6 | 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 | store: &Store, |
| 12 | accounts: &mut CalendarAccounts, |
| 13 | start: DateTime<Utc>, |
| 14 | end: DateTime<Utc>, |
| 15 | ) -> Result<(Vec<CalendarEvent>, Vec<String>), String> { |
| 16 | let Some(oauth) = crate::google_oauth_client::resolve(store).await else { |
| 17 | // Connected accounts but no client id compiled in: say so instead of an empty week. |
| 18 | if accounts.has_google() { |
| 19 | return Err(missing_client_id()); |
| 20 | } |
| 21 | return Ok((Vec::new(), Vec::new())); |
| 22 | }; |
| 23 | let mut all = Vec::new(); |
| 24 | // One rejected token must not hide calendars that still refresh. |
| 25 | let mut account_errors = Vec::new(); |
| 26 | for index in 0..accounts.google_accounts.len() { |
| 27 | match ensure_access_token(accounts, index, &oauth).await { |
| 28 | Ok(true) => {} |
| 29 | Ok(false) => continue, |
| 30 | Err(error) => { |
| 31 | remember_account_error(&mut account_errors, error); |
| 32 | continue; |
| 33 | } |
| 34 | } |
| 35 | let account = &accounts.google_accounts[index]; |
| 36 | let access = account.tokens.access_token.clone(); |
| 37 | let account_id = account.id.clone(); |
| 38 | let calendars: Vec<(String, String)> = account |
| 39 | .calendars |
| 40 | .iter() |
| 41 | .filter(|calendar| calendar.selected) |
| 42 | .map(|calendar| (calendar.id.clone(), calendar.summary.clone())) |
| 43 | .collect(); |
| 44 | // Every calendar turned off (group check box): the account shows nothing. |
| 45 | if calendars.is_empty() && !account.calendars.is_empty() { |
| 46 | continue; |
| 47 | } |
| 48 | let calendars = if calendars.is_empty() { |
| 49 | vec![( |
| 50 | "primary".to_owned(), |
| 51 | app_base::ui_locale::tr("settings.calendar.primary"), |
| 52 | )] |
| 53 | } else { |
| 54 | calendars |
| 55 | }; |
| 56 | let client = GoogleCalendar::new(access); |
| 57 | for (calendar_id, calendar_name) in calendars { |
| 58 | match client.events(&calendar_id, start, end).await { |
| 59 | Ok(mut events) => { |
| 60 | for event in &mut events { |
| 61 | event.account_id = Some(account_id.clone()); |
| 62 | event.calendar_id = Some(calendar_id.clone()); |
| 63 | event.calendar_name = Some(calendar_name.clone()); |
| 64 | } |
| 65 | all.extend(events); |
| 66 | } |
| 67 | Err(error) => crate::diagnostics::record(format!( |
| 68 | "calls: google calendar {calendar_id} not loaded: {error}" |
| 69 | )), |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | Ok((all, account_errors)) |
| 74 | } |
| 75 | |
| 76 | /// Keeps a sign-in failure ahead of any other account error. One notice is enough. |
| 77 | fn remember_account_error(errors: &mut Vec<String>, error: String) { |
| 78 | if errors.iter().any(|existing| needs_sign_in(existing)) && !needs_sign_in(&error) { |
| 79 | return; |
| 80 | } |
| 81 | if needs_sign_in(&error) { |
| 82 | errors.clear(); |
| 83 | } |
| 84 | if errors.is_empty() { |
| 85 | errors.push(error); |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | pub async fn insert_google_event( |
| 90 | store: &Store, |
| 91 | accounts: &mut CalendarAccounts, |
| 92 | account_id: &str, |
| 93 | calendar_id: &str, |
| 94 | draft: &GoogleEventDraft, |
| 95 | ) -> Result<(), String> { |
| 96 | let oauth = crate::google_oauth_client::resolve(store) |
| 97 | .await |
| 98 | .ok_or_else(|| missing_client_id())?; |
| 99 | let index = accounts |
| 100 | .google_accounts |
| 101 | .iter() |
| 102 | .position(|account| account.id == account_id) |
| 103 | .ok_or_else(|| format!("Google account {account_id} missing"))?; |
| 104 | if !ensure_access_token(accounts, index, &oauth).await? { |
| 105 | return Err("Google access token missing".into()); |
| 106 | } |
| 107 | let access = accounts.google_accounts[index].tokens.access_token.clone(); |
| 108 | GoogleCalendar::new(access) |
| 109 | .insert_event(calendar_id, draft) |
| 110 | .await |
| 111 | .map(|_| ()) |
| 112 | .map_err(|error| error.to_string()) |
| 113 | } |
| 114 | |
| 115 | pub async fn respond_google_event( |
| 116 | store: &Store, |
| 117 | accounts: &mut CalendarAccounts, |
| 118 | account_id: &str, |
| 119 | calendar_id: &str, |
| 120 | event_id: &str, |
| 121 | reply: Reply, |
| 122 | send_updates: bool, |
| 123 | ) -> Result<(), String> { |
| 124 | let oauth = crate::google_oauth_client::resolve(store) |
| 125 | .await |
| 126 | .ok_or_else(|| missing_client_id())?; |
| 127 | let index = accounts |
| 128 | .google_accounts |
| 129 | .iter() |
| 130 | .position(|account| account.id == account_id) |
| 131 | .ok_or_else(|| format!("Google account {account_id} missing"))?; |
| 132 | if !ensure_access_token(accounts, index, &oauth).await? { |
| 133 | return Err("Google access token missing".into()); |
| 134 | } |
| 135 | let access = accounts.google_accounts[index].tokens.access_token.clone(); |
| 136 | GoogleCalendar::new(access) |
| 137 | .respond( |
| 138 | calendar_id, |
| 139 | event_id, |
| 140 | google_rsvp_status(reply), |
| 141 | send_updates, |
| 142 | ) |
| 143 | .await |
| 144 | .map_err(|error| error.to_string()) |
| 145 | } |
| 146 | |
| 147 | pub async fn delete_google_event( |
| 148 | store: &Store, |
| 149 | accounts: &mut CalendarAccounts, |
| 150 | account_id: &str, |
| 151 | calendar_id: &str, |
| 152 | event_id: &str, |
| 153 | send_updates: bool, |
| 154 | ) -> Result<(), String> { |
| 155 | let oauth = crate::google_oauth_client::resolve(store) |
| 156 | .await |
| 157 | .ok_or_else(|| missing_client_id())?; |
| 158 | let index = accounts |
| 159 | .google_accounts |
| 160 | .iter() |
| 161 | .position(|account| account.id == account_id) |
| 162 | .ok_or_else(|| format!("Google account {account_id} missing"))?; |
| 163 | if !ensure_access_token(accounts, index, &oauth).await? { |
| 164 | return Err("Google access token missing".into()); |
| 165 | } |
| 166 | let access = accounts.google_accounts[index].tokens.access_token.clone(); |
| 167 | GoogleCalendar::new(access) |
| 168 | .delete_event(calendar_id, event_id, send_updates) |
| 169 | .await |
| 170 | .map_err(|error| error.to_string()) |
| 171 | } |
| 172 | |
| 173 | async fn ensure_access_token( |
| 174 | accounts: &mut CalendarAccounts, |
| 175 | index: usize, |
| 176 | oauth: &GoogleOAuth, |
| 177 | ) -> Result<bool, String> { |
| 178 | let now = Utc::now().timestamp(); |
| 179 | let account = &mut accounts.google_accounts[index]; |
| 180 | if account.tokens.refresh_token.is_empty() && account.tokens.access_token.is_empty() { |
| 181 | return Ok(false); |
| 182 | } |
| 183 | if account.tokens.expires_at <= now + 60 && !account.tokens.refresh_token.is_empty() { |
| 184 | match refresh_access_token(oauth, &account.tokens.refresh_token).await { |
| 185 | Ok(bundle) => { |
| 186 | account.tokens = GoogleTokenSet { |
| 187 | access_token: bundle.access_token, |
| 188 | refresh_token: if bundle.refresh_token.is_empty() { |
| 189 | account.tokens.refresh_token.clone() |
| 190 | } else { |
| 191 | bundle.refresh_token |
| 192 | }, |
| 193 | expires_at: now + bundle.expires_in.max(60), |
| 194 | }; |
| 195 | } |
| 196 | Err(error) => { |
| 197 | let message = format!("google token refresh failed: {error}"); |
| 198 | crate::diagnostics::record(format!("calls: {message}")); |
| 199 | // Surface to week load as CalendarLoadFailure — never Ok([]) for auth fail. |
| 200 | return Err(message); |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | Ok(!account.tokens.access_token.is_empty()) |
| 205 | } |
| 206 | |
| 207 | fn missing_client_id() -> String { |
| 208 | app_base::ui_locale::tr("settings.calendar.not_in_build") |
| 209 | } |
| 210 | |
| 211 | /// True when another fetch cannot succeed until the user signs in to Google again. |
| 212 | pub fn needs_sign_in(message: &str) -> bool { |
| 213 | message.starts_with("google token refresh failed:") || message == missing_client_id() |
| 214 | } |
| 215 | |
| 216 | #[cfg(test)] |
| 217 | mod tests { |
| 218 | use super::{needs_sign_in, remember_account_error}; |
| 219 | |
| 220 | #[test] |
| 221 | fn a_rejected_token_does_not_hide_another_accounts_error_notice() { |
| 222 | let mut errors = Vec::new(); |
| 223 | remember_account_error(&mut errors, "HTTP 503".into()); |
| 224 | remember_account_error( |
| 225 | &mut errors, |
| 226 | "google token refresh failed: HTTP 400: invalid_grant".into(), |
| 227 | ); |
| 228 | remember_account_error(&mut errors, "HTTP 500".into()); |
| 229 | assert_eq!(errors.len(), 1); |
| 230 | assert!(needs_sign_in(&errors[0])); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn google_sign_in_is_required_only_for_a_rejected_token() { |
| 235 | assert!(needs_sign_in( |
| 236 | "google token refresh failed: HTTP 400: invalid_grant" |
| 237 | )); |
| 238 | assert!(!needs_sign_in("HTTP 503")); |
| 239 | assert!(!needs_sign_in("client_secret is missing")); |
| 240 | } |
| 241 | } |