BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / google_calendar_sync.rs

google_calendar_sync.rs

google_calendar_sync.rs 6.2 KiB Download Raw
1use chrono::{DateTime, Utc};
2use store::{CalendarAccounts, GoogleTokenSet};
3
4use 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.
10pub async fn fetch_google_events(
11 accounts: &mut CalendarAccounts,
12 start: DateTime<Utc>,
13 end: DateTime<Utc>,
14) -> Result<Vec<CalendarEvent>, 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());
21 };
22 let mut all = Vec::new();
23 for index in 0..accounts.google_accounts.len() {
24 if !ensure_access_token(accounts, index, &oauth).await? {
25 continue;
26 }
27 let account = &accounts.google_accounts[index];
28 let access = account.tokens.access_token.clone();
29 let account_id = account.id.clone();
30 let calendars: Vec<(String, String)> = account
31 .calendars
32 .iter()
33 .filter(|calendar| calendar.selected)
34 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
35 .collect();
36 // Every calendar turned off (group check box): the account shows nothing.
37 if calendars.is_empty() && !account.calendars.is_empty() {
38 continue;
39 }
40 let calendars = if calendars.is_empty() {
41 vec![(
42 "primary".to_owned(),
43 app_base::ui_locale::tr("settings.calendar.primary"),
44 )]
45 } else {
46 calendars
47 };
48 let client = GoogleCalendar::new(access);
49 for (calendar_id, calendar_name) in calendars {
50 match client.events(&calendar_id, start, end).await {
51 Ok(mut events) => {
52 for event in &mut events {
53 event.account_id = Some(account_id.clone());
54 event.calendar_id = Some(calendar_id.clone());
55 event.calendar_name = Some(calendar_name.clone());
56 }
57 all.extend(events);
58 }
59 Err(error) => crate::diagnostics::record(format!(
60 "calls: google calendar {calendar_id} not loaded: {error}"
61 )),
62 }
63 }
64 }
65 Ok(all)
66}
67
68pub async fn insert_google_event(
69 accounts: &mut CalendarAccounts,
70 account_id: &str,
71 calendar_id: &str,
72 draft: &GoogleEventDraft,
73) -> Result<(), String> {
74 let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
75 let index = accounts
76 .google_accounts
77 .iter()
78 .position(|account| account.id == account_id)
79 .ok_or_else(|| format!("Google account {account_id} missing"))?;
80 if !ensure_access_token(accounts, index, &oauth).await? {
81 return Err("Google access token missing".into());
82 }
83 let access = accounts.google_accounts[index].tokens.access_token.clone();
84 GoogleCalendar::new(access)
85 .insert_event(calendar_id, draft)
86 .await
87 .map(|_| ())
88 .map_err(|error| error.to_string())
89}
90
91pub async fn respond_google_event(
92 accounts: &mut CalendarAccounts,
93 account_id: &str,
94 calendar_id: &str,
95 event_id: &str,
96 reply: Reply,
97 send_updates: bool,
98) -> Result<(), String> {
99 let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
100 let index = accounts
101 .google_accounts
102 .iter()
103 .position(|account| account.id == account_id)
104 .ok_or_else(|| format!("Google account {account_id} missing"))?;
105 if !ensure_access_token(accounts, index, &oauth).await? {
106 return Err("Google access token missing".into());
107 }
108 let access = accounts.google_accounts[index].tokens.access_token.clone();
109 GoogleCalendar::new(access)
110 .respond(
111 calendar_id,
112 event_id,
113 google_rsvp_status(reply),
114 send_updates,
115 )
116 .await
117 .map_err(|error| error.to_string())
118}
119
120pub async fn delete_google_event(
121 accounts: &mut CalendarAccounts,
122 account_id: &str,
123 calendar_id: &str,
124 event_id: &str,
125 send_updates: bool,
126) -> Result<(), String> {
127 let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
128 let index = accounts
129 .google_accounts
130 .iter()
131 .position(|account| account.id == account_id)
132 .ok_or_else(|| format!("Google account {account_id} missing"))?;
133 if !ensure_access_token(accounts, index, &oauth).await? {
134 return Err("Google access token missing".into());
135 }
136 let access = accounts.google_accounts[index].tokens.access_token.clone();
137 GoogleCalendar::new(access)
138 .delete_event(calendar_id, event_id, send_updates)
139 .await
140 .map_err(|error| error.to_string())
141}
142
143async fn ensure_access_token(
144 accounts: &mut CalendarAccounts,
145 index: usize,
146 oauth: &GoogleOAuth,
147) -> Result<bool, String> {
148 let now = Utc::now().timestamp();
149 let account = &mut accounts.google_accounts[index];
150 if account.tokens.refresh_token.is_empty() && account.tokens.access_token.is_empty() {
151 return Ok(false);
152 }
153 if account.tokens.expires_at <= now + 60 && !account.tokens.refresh_token.is_empty() {
154 match refresh_access_token(oauth, &account.tokens.refresh_token).await {
155 Ok(bundle) => {
156 account.tokens = GoogleTokenSet {
157 access_token: bundle.access_token,
158 refresh_token: if bundle.refresh_token.is_empty() {
159 account.tokens.refresh_token.clone()
160 } else {
161 bundle.refresh_token
162 },
163 expires_at: now + bundle.expires_in.max(60),
164 };
165 }
166 Err(error) => {
167 crate::diagnostics::record(format!("calls: google token refresh failed: {error}"));
168 return Ok(false);
169 }
170 }
171 }
172 Ok(!account.tokens.access_token.is_empty())
173}
174
175fn missing_client_id() -> String {
176 app_base::ui_locale::tr("settings.calendar.not_in_build")
177}