| 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>, Vec<String>), String> { |
| 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. |
| 17 | if accounts.has_google() { |
| 18 | return Err(missing_client_id()); |
| 19 | } |
| 20 | return Ok((Vec::new(), Vec::new())); |
| 21 | }; |
| 22 | let mut all = Vec::new(); |
| 23 | // One rejected token must not hide calendars that still refresh. |
| 24 | let mut account_errors = Vec::new(); |
| 25 | for index in 0..accounts.google_accounts.len() { |
| 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 | } |
| 33 | } |
| 34 | let account = &accounts.google_accounts[index]; |
| 35 | let access = account.tokens.access_token.clone(); |
| 36 | let account_id = account.id.clone(); |
| 37 | let calendars: Vec<(String, String)> = account |
| 38 | .calendars |
| 39 | .iter() |
| 40 | .filter(|calendar| calendar.selected) |
| 41 | .map(|calendar| (calendar.id.clone(), calendar.summary.clone())) |
| 42 | .collect(); |
| 43 | // Every calendar turned off (group check box): the account shows nothing. |
| 44 | if calendars.is_empty() && !account.calendars.is_empty() { |
| 45 | continue; |
| 46 | } |
| 47 | let calendars = if calendars.is_empty() { |
| 48 | vec![( |
| 49 | "primary".to_owned(), |
| 50 | app_base::ui_locale::tr("settings.calendar.primary"), |
| 51 | )] |
| 52 | } else { |
| 53 | calendars |
| 54 | }; |
| 55 | let client = GoogleCalendar::new(access); |
| 56 | for (calendar_id, calendar_name) in calendars { |
| 57 | match client.events(&calendar_id, start, end).await { |
| 58 | Ok(mut events) => { |
| 59 | for event in &mut events { |
| 60 | event.account_id = Some(account_id.clone()); |
| 61 | event.calendar_id = Some(calendar_id.clone()); |
| 62 | event.calendar_name = Some(calendar_name.clone()); |
| 63 | } |
| 64 | all.extend(events); |
| 65 | } |
| 66 | Err(error) => crate::diagnostics::record(format!( |
| 67 | "calls: google calendar {calendar_id} not loaded: {error}" |
| 68 | )), |
| 69 | } |
| 70 | } |
| 71 | } |
| 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 | } |
| 86 | } |
| 87 | |
| 88 | pub async fn insert_google_event( |
| 89 | accounts: &mut CalendarAccounts, |
| 90 | account_id: &str, |
| 91 | calendar_id: &str, |
| 92 | draft: &GoogleEventDraft, |
| 93 | ) -> Result<(), String> { |
| 94 | let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?; |
| 95 | let index = accounts |
| 96 | .google_accounts |
| 97 | .iter() |
| 98 | .position(|account| account.id == account_id) |
| 99 | .ok_or_else(|| format!("Google account {account_id} missing"))?; |
| 100 | if !ensure_access_token(accounts, index, &oauth).await? { |
| 101 | return Err("Google access token missing".into()); |
| 102 | } |
| 103 | let access = accounts.google_accounts[index].tokens.access_token.clone(); |
| 104 | GoogleCalendar::new(access) |
| 105 | .insert_event(calendar_id, draft) |
| 106 | .await |
| 107 | .map(|_| ()) |
| 108 | .map_err(|error| error.to_string()) |
| 109 | } |
| 110 | |
| 111 | pub async fn respond_google_event( |
| 112 | accounts: &mut CalendarAccounts, |
| 113 | account_id: &str, |
| 114 | calendar_id: &str, |
| 115 | event_id: &str, |
| 116 | reply: Reply, |
| 117 | send_updates: bool, |
| 118 | ) -> Result<(), String> { |
| 119 | let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?; |
| 120 | let index = accounts |
| 121 | .google_accounts |
| 122 | .iter() |
| 123 | .position(|account| account.id == account_id) |
| 124 | .ok_or_else(|| format!("Google account {account_id} missing"))?; |
| 125 | if !ensure_access_token(accounts, index, &oauth).await? { |
| 126 | return Err("Google access token missing".into()); |
| 127 | } |
| 128 | let access = accounts.google_accounts[index].tokens.access_token.clone(); |
| 129 | GoogleCalendar::new(access) |
| 130 | .respond( |
| 131 | calendar_id, |
| 132 | event_id, |
| 133 | google_rsvp_status(reply), |
| 134 | send_updates, |
| 135 | ) |
| 136 | .await |
| 137 | .map_err(|error| error.to_string()) |
| 138 | } |
| 139 | |
| 140 | pub async fn delete_google_event( |
| 141 | accounts: &mut CalendarAccounts, |
| 142 | account_id: &str, |
| 143 | calendar_id: &str, |
| 144 | event_id: &str, |
| 145 | send_updates: bool, |
| 146 | ) -> Result<(), String> { |
| 147 | let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?; |
| 148 | let index = accounts |
| 149 | .google_accounts |
| 150 | .iter() |
| 151 | .position(|account| account.id == account_id) |
| 152 | .ok_or_else(|| format!("Google account {account_id} missing"))?; |
| 153 | if !ensure_access_token(accounts, index, &oauth).await? { |
| 154 | return Err("Google access token missing".into()); |
| 155 | } |
| 156 | let access = accounts.google_accounts[index].tokens.access_token.clone(); |
| 157 | GoogleCalendar::new(access) |
| 158 | .delete_event(calendar_id, event_id, send_updates) |
| 159 | .await |
| 160 | .map_err(|error| error.to_string()) |
| 161 | } |
| 162 | |
| 163 | async fn ensure_access_token( |
| 164 | accounts: &mut CalendarAccounts, |
| 165 | index: usize, |
| 166 | oauth: &GoogleOAuth, |
| 167 | ) -> Result<bool, String> { |
| 168 | let now = Utc::now().timestamp(); |
| 169 | let account = &mut accounts.google_accounts[index]; |
| 170 | if account.tokens.refresh_token.is_empty() && account.tokens.access_token.is_empty() { |
| 171 | return Ok(false); |
| 172 | } |
| 173 | if account.tokens.expires_at <= now + 60 && !account.tokens.refresh_token.is_empty() { |
| 174 | match refresh_access_token(oauth, &account.tokens.refresh_token).await { |
| 175 | Ok(bundle) => { |
| 176 | account.tokens = GoogleTokenSet { |
| 177 | access_token: bundle.access_token, |
| 178 | refresh_token: if bundle.refresh_token.is_empty() { |
| 179 | account.tokens.refresh_token.clone() |
| 180 | } else { |
| 181 | bundle.refresh_token |
| 182 | }, |
| 183 | expires_at: now + bundle.expires_in.max(60), |
| 184 | }; |
| 185 | } |
| 186 | Err(error) => { |
| 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); |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | Ok(!account.tokens.access_token.is_empty()) |
| 195 | } |
| 196 | |
| 197 | fn missing_client_id() -> String { |
| 198 | app_base::ui_locale::tr("settings.calendar.not_in_build") |
| 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 | } |