| 1 | //! Google Calendar OAuth + REST client for rusty-teams calendar accounts. |
| 2 | |
| 3 | mod loopback; |
| 4 | mod merge; |
| 5 | mod oauth; |
| 6 | mod parse; |
| 7 | mod write; |
| 8 | |
| 9 | pub use loopback::{allocate_redirect_uri, wait_for_code}; |
| 10 | pub use merge::{merge_calendar_events, normalize_join_url}; |
| 11 | pub use oauth::{ |
| 12 | AuthPending, GoogleOAuth, TokenBundle, client_from_stored, client_id_from_env, exchange_code, |
| 13 | refresh_access_token, |
| 14 | }; |
| 15 | pub use parse::{parse_calendar_list, parse_google_events}; |
| 16 | pub use write::{ |
| 17 | GoogleEventDraft, google_event_body, google_rsvp_query, google_rsvp_status, rrule_for_repeat, |
| 18 | }; |
| 19 | |
| 20 | use chrono::{DateTime, Utc}; |
| 21 | use reqwest::Client; |
| 22 | use serde_json::Value; |
| 23 | |
| 24 | use crate::calendar::CalendarEvent; |
| 25 | use crate::error::{Error, Result}; |
| 26 | |
| 27 | const CALENDAR_API: &str = "https://www.googleapis.com/calendar/v3"; |
| 28 | const EVENTS_PAGE_SIZE: u32 = 2500; |
| 29 | const MAX_EVENT_PAGES: usize = 20; |
| 30 | |
| 31 | fn attendees_with_own_reply(event: &Value, status: &str) -> Option<Vec<Value>> { |
| 32 | let mut attendees = event.get("attendees")?.as_array()?.clone(); |
| 33 | let own = attendees |
| 34 | .iter_mut() |
| 35 | .find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true))?; |
| 36 | own["responseStatus"] = Value::String(status.to_owned()); |
| 37 | Some(attendees) |
| 38 | } |
| 39 | |
| 40 | pub struct GoogleCalendar { |
| 41 | client: Client, |
| 42 | access_token: String, |
| 43 | } |
| 44 | |
| 45 | impl GoogleCalendar { |
| 46 | pub fn new(access_token: impl Into<String>) -> Self { |
| 47 | GoogleCalendar { |
| 48 | client: Client::new(), |
| 49 | access_token: access_token.into(), |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | pub async fn list_calendars(&self) -> Result<Value> { |
| 54 | self.get(&format!("{CALENDAR_API}/users/me/calendarList")) |
| 55 | .await |
| 56 | } |
| 57 | |
| 58 | pub async fn events( |
| 59 | &self, |
| 60 | calendar_id: &str, |
| 61 | start: DateTime<Utc>, |
| 62 | end: DateTime<Utc>, |
| 63 | ) -> Result<Vec<CalendarEvent>> { |
| 64 | let encoded = |
| 65 | percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC); |
| 66 | let url = format!( |
| 67 | "{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&maxResults={EVENTS_PAGE_SIZE}&timeMin={}&timeMax={}", |
| 68 | start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true), |
| 69 | end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true), |
| 70 | ); |
| 71 | let mut events = Vec::new(); |
| 72 | let mut page_token: Option<String> = None; |
| 73 | for _ in 0..MAX_EVENT_PAGES { |
| 74 | let page_url = match &page_token { |
| 75 | Some(token) => format!( |
| 76 | "{url}&pageToken={}", |
| 77 | percent_encoding::utf8_percent_encode( |
| 78 | token, |
| 79 | percent_encoding::NON_ALPHANUMERIC |
| 80 | ) |
| 81 | ), |
| 82 | None => url.clone(), |
| 83 | }; |
| 84 | let body = self.get(&page_url).await?; |
| 85 | events.extend(parse_google_events(&body, None, Some(calendar_id))); |
| 86 | page_token = body |
| 87 | .get("nextPageToken") |
| 88 | .and_then(Value::as_str) |
| 89 | .map(str::to_owned); |
| 90 | if page_token.is_none() { |
| 91 | break; |
| 92 | } |
| 93 | } |
| 94 | events.sort_by_key(|event| (event.start, event.end)); |
| 95 | Ok(events) |
| 96 | } |
| 97 | |
| 98 | pub async fn insert_event(&self, calendar_id: &str, draft: &GoogleEventDraft) -> Result<Value> { |
| 99 | let encoded = |
| 100 | percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC); |
| 101 | let url = format!("{CALENDAR_API}/calendars/{encoded}/events?sendUpdates=all"); |
| 102 | self.post(&url, google_event_body(draft)).await |
| 103 | } |
| 104 | |
| 105 | pub async fn respond( |
| 106 | &self, |
| 107 | calendar_id: &str, |
| 108 | event_id: &str, |
| 109 | status: &str, |
| 110 | send_updates: bool, |
| 111 | ) -> Result<()> { |
| 112 | let encoded_cal = |
| 113 | percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC); |
| 114 | let encoded_event = |
| 115 | percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC); |
| 116 | let url = format!( |
| 117 | "{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}", |
| 118 | google_rsvp_query(send_updates) |
| 119 | ); |
| 120 | let event_url = format!("{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}"); |
| 121 | let event = self.get(&event_url).await?; |
| 122 | let attendees = attendees_with_own_reply(&event, status).ok_or_else(|| { |
| 123 | Error::UnexpectedAnswer("the event lists no attendee for this account".into()) |
| 124 | })?; |
| 125 | self.patch(&url, serde_json::json!({ "attendees": attendees })) |
| 126 | .await?; |
| 127 | Ok(()) |
| 128 | } |
| 129 | |
| 130 | pub async fn delete_event( |
| 131 | &self, |
| 132 | calendar_id: &str, |
| 133 | event_id: &str, |
| 134 | send_updates: bool, |
| 135 | ) -> Result<()> { |
| 136 | let encoded_cal = |
| 137 | percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC); |
| 138 | let encoded_event = |
| 139 | percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC); |
| 140 | let url = format!( |
| 141 | "{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}", |
| 142 | google_rsvp_query(send_updates) |
| 143 | ); |
| 144 | self.delete(&url).await |
| 145 | } |
| 146 | |
| 147 | async fn get(&self, url: &str) -> Result<Value> { |
| 148 | let response = self |
| 149 | .client |
| 150 | .get(url) |
| 151 | .bearer_auth(&self.access_token) |
| 152 | .send() |
| 153 | .await |
| 154 | .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 155 | Self::json_result(url, response).await |
| 156 | } |
| 157 | |
| 158 | async fn post(&self, url: &str, body: Value) -> Result<Value> { |
| 159 | let response = self |
| 160 | .client |
| 161 | .post(url) |
| 162 | .bearer_auth(&self.access_token) |
| 163 | .json(&body) |
| 164 | .send() |
| 165 | .await |
| 166 | .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 167 | Self::json_result(url, response).await |
| 168 | } |
| 169 | |
| 170 | async fn patch(&self, url: &str, body: Value) -> Result<Value> { |
| 171 | let response = self |
| 172 | .client |
| 173 | .patch(url) |
| 174 | .bearer_auth(&self.access_token) |
| 175 | .json(&body) |
| 176 | .send() |
| 177 | .await |
| 178 | .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 179 | Self::json_result(url, response).await |
| 180 | } |
| 181 | |
| 182 | async fn delete(&self, url: &str) -> Result<()> { |
| 183 | let response = self |
| 184 | .client |
| 185 | .delete(url) |
| 186 | .bearer_auth(&self.access_token) |
| 187 | .send() |
| 188 | .await |
| 189 | .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 190 | let status = response.status().as_u16(); |
| 191 | if (200..300).contains(&status) { |
| 192 | return Ok(()); |
| 193 | } |
| 194 | let body = response |
| 195 | .json::<Value>() |
| 196 | .await |
| 197 | .unwrap_or_else(|_| Value::Null); |
| 198 | Err(Error::Session(session::Error::api(status, url, body))) |
| 199 | } |
| 200 | |
| 201 | async fn json_result(url: &str, response: reqwest::Response) -> Result<Value> { |
| 202 | let status = response.status().as_u16(); |
| 203 | let body = response |
| 204 | .json::<Value>() |
| 205 | .await |
| 206 | .unwrap_or_else(|_| Value::Null); |
| 207 | if !(200..300).contains(&status) { |
| 208 | return Err(Error::Session(session::Error::api(status, url, body))); |
| 209 | } |
| 210 | Ok(body) |
| 211 | } |
| 212 | } |