Skip to main content

google_tool/
calendar_list.rs

1//! Google Calendar list discovery for an individual OAuth connection.
2use crate::{GoogleOAuthConfig, GoogleOAuthError, refresh_access_token};
3use serde::Deserialize;
4
5const CALENDAR_LIST_URL: &str = "https://www.googleapis.com/calendar/v3/users/me/calendarList";
6
7#[derive(Debug, Clone, Deserialize)]
8#[serde(rename_all = "camelCase")]
9struct CalendarListPage {
10    #[serde(default)]
11    items: Vec<GoogleCalendarSummary>,
12    next_page_token: Option<String>,
13}
14
15#[derive(Debug, Clone, Deserialize)]
16#[serde(rename_all = "camelCase")]
17pub struct GoogleCalendarSummary {
18    pub id: String,
19    pub summary: Option<String>,
20    pub time_zone: Option<String>,
21    pub access_role: Option<String>,
22}
23
24/// Fetch every calendar visible to the connected Google account.
25///
26/// The refresh token is supplied by the server-side connection store. It must
27/// never be passed to browser clients or agent-facing tools.
28pub async fn list_calendars(
29    config: &GoogleOAuthConfig,
30    refresh_token: &str,
31) -> Result<Vec<GoogleCalendarSummary>, GoogleOAuthError> {
32    let token = refresh_access_token(config, refresh_token).await?;
33    list_calendars_with_access_token(&token.access_token).await
34}
35
36/// Fetch calendars using an already-refreshed access token. The caller must
37/// coordinate refreshes through `GoogleOAuthTokenManager`.
38pub async fn list_calendars_with_access_token(
39    access_token: &str,
40) -> Result<Vec<GoogleCalendarSummary>, GoogleOAuthError> {
41    let client = oauth2::reqwest::ClientBuilder::new()
42        .redirect(oauth2::reqwest::redirect::Policy::none())
43        .build()
44        .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
45
46    let mut calendars = Vec::new();
47    let mut page_token: Option<String> = None;
48    loop {
49        let mut request = client
50            .get(CALENDAR_LIST_URL)
51            .bearer_auth(access_token)
52            .query(&[("maxResults", "250")]);
53        if let Some(token) = page_token.as_deref() {
54            request = request.query(&[("pageToken", token)]);
55        }
56        let response = request
57            .send()
58            .await
59            .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
60        let status = response.status();
61        let body = response
62            .text()
63            .await
64            .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
65        if !status.is_success() {
66            let detail = serde_json::from_str::<serde_json::Value>(&body)
67                .ok()
68                .and_then(|value| {
69                    value
70                        .pointer("/error/message")
71                        .and_then(serde_json::Value::as_str)
72                        .map(str::to_owned)
73                })
74                .unwrap_or(body);
75            return Err(GoogleOAuthError::Request(format!(
76                "Google Calendar API returned {status}: {detail}"
77            )));
78        }
79        let page: CalendarListPage = serde_json::from_str(&body)
80            .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
81        calendars.extend(page.items);
82        page_token = page.next_page_token;
83        if page_token.is_none() {
84            break;
85        }
86    }
87    Ok(calendars)
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn deserializes_calendar_list_metadata() {
96        let page: CalendarListPage = serde_json::from_value(serde_json::json!({
97            "items": [{
98                "id": "primary",
99                "summary": "Personal",
100                "timeZone": "Europe/Madrid",
101                "accessRole": "owner"
102            }],
103            "nextPageToken": "next"
104        }))
105        .unwrap();
106        assert_eq!(page.items.len(), 1);
107        assert_eq!(page.items[0].id, "primary");
108        assert_eq!(page.items[0].time_zone.as_deref(), Some("Europe/Madrid"));
109        assert_eq!(page.items[0].access_role.as_deref(), Some("owner"));
110        assert_eq!(page.next_page_token.as_deref(), Some("next"));
111    }
112}