BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / google_calendar / mod.rs

mod.rs

mod.rs 5.9 KiB Download Raw
1//! Google Calendar OAuth + REST client for rusty-teams calendar accounts.
2
3mod loopback;
4mod merge;
5mod oauth;
6mod parse;
7mod write;
8
9pub use loopback::{allocate_redirect_uri, wait_for_code};
10pub use merge::{merge_calendar_events, normalize_join_url};
11pub use oauth::{
12 AuthPending, GoogleOAuth, TokenBundle, client_id_from_env, exchange_code, refresh_access_token,
13};
14pub use parse::{parse_calendar_list, parse_google_events};
15pub use write::{
16 GoogleEventDraft, google_event_body, google_rsvp_query, google_rsvp_status, rrule_for_repeat,
17};
18
19use chrono::{DateTime, Utc};
20use reqwest::Client;
21use serde_json::Value;
22
23use crate::calendar::CalendarEvent;
24use crate::error::{Error, Result};
25
26const CALENDAR_API: &str = "https://www.googleapis.com/calendar/v3";
27
28pub struct GoogleCalendar {
29 client: Client,
30 access_token: String,
31}
32
33impl GoogleCalendar {
34 pub fn new(access_token: impl Into<String>) -> Self {
35 GoogleCalendar {
36 client: Client::new(),
37 access_token: access_token.into(),
38 }
39 }
40
41 pub async fn list_calendars(&self) -> Result<Value> {
42 self.get(&format!("{CALENDAR_API}/users/me/calendarList"))
43 .await
44 }
45
46 pub async fn events(
47 &self,
48 calendar_id: &str,
49 start: DateTime<Utc>,
50 end: DateTime<Utc>,
51 ) -> Result<Vec<CalendarEvent>> {
52 let encoded =
53 percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
54 let url = format!(
55 "{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&timeMin={}&timeMax={}",
56 start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
57 end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
58 );
59 let body = self.get(&url).await?;
60 Ok(parse_google_events(&body, None, Some(calendar_id)))
61 }
62
63 pub async fn insert_event(&self, calendar_id: &str, draft: &GoogleEventDraft) -> Result<Value> {
64 let encoded =
65 percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
66 let url = format!("{CALENDAR_API}/calendars/{encoded}/events?sendUpdates=all");
67 self.post(&url, google_event_body(draft)).await
68 }
69
70 pub async fn respond(
71 &self,
72 calendar_id: &str,
73 event_id: &str,
74 status: &str,
75 send_updates: bool,
76 ) -> Result<()> {
77 let encoded_cal =
78 percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
79 let encoded_event =
80 percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);
81 let url = format!(
82 "{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",
83 google_rsvp_query(send_updates)
84 );
85 // Patch attendee self via conferenceData-free body: use attendees[].responseStatus
86 // by first getting the event is heavy; Google allows PATCH with only attendees when
87 // "self" is present. Simpler path: PATCH with a single attendees entry marked self.
88 let body = serde_json::json!({
89 "attendees": [{ "self": true, "responseStatus": status }]
90 });
91 self.patch(&url, body).await?;
92 Ok(())
93 }
94
95 pub async fn delete_event(
96 &self,
97 calendar_id: &str,
98 event_id: &str,
99 send_updates: bool,
100 ) -> Result<()> {
101 let encoded_cal =
102 percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
103 let encoded_event =
104 percent_encoding::utf8_percent_encode(event_id, percent_encoding::NON_ALPHANUMERIC);
105 let url = format!(
106 "{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",
107 google_rsvp_query(send_updates)
108 );
109 self.delete(&url).await
110 }
111
112 async fn get(&self, url: &str) -> Result<Value> {
113 let response = self
114 .client
115 .get(url)
116 .bearer_auth(&self.access_token)
117 .send()
118 .await
119 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
120 Self::json_result(url, response).await
121 }
122
123 async fn post(&self, url: &str, body: Value) -> Result<Value> {
124 let response = self
125 .client
126 .post(url)
127 .bearer_auth(&self.access_token)
128 .json(&body)
129 .send()
130 .await
131 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
132 Self::json_result(url, response).await
133 }
134
135 async fn patch(&self, url: &str, body: Value) -> Result<Value> {
136 let response = self
137 .client
138 .patch(url)
139 .bearer_auth(&self.access_token)
140 .json(&body)
141 .send()
142 .await
143 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
144 Self::json_result(url, response).await
145 }
146
147 async fn delete(&self, url: &str) -> Result<()> {
148 let response = self
149 .client
150 .delete(url)
151 .bearer_auth(&self.access_token)
152 .send()
153 .await
154 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
155 let status = response.status().as_u16();
156 if (200..300).contains(&status) {
157 return Ok(());
158 }
159 let body = response
160 .json::<Value>()
161 .await
162 .unwrap_or_else(|_| Value::Null);
163 Err(Error::Session(session::Error::api(status, url, body)))
164 }
165
166 async fn json_result(url: &str, response: reqwest::Response) -> Result<Value> {
167 let status = response.status().as_u16();
168 let body = response
169 .json::<Value>()
170 .await
171 .unwrap_or_else(|_| Value::Null);
172 if !(200..300).contains(&status) {
173 return Err(Error::Session(session::Error::api(status, url, body)));
174 }
175 Ok(body)
176 }
177}