1use chrono::{DateTime, Duration, SecondsFormat, Utc};
13use serde::Deserialize;
14use serde_json::{json, Map, Value};
15
16use super::{clip, GoogleRequest, SCOPE_PREFIX};
17
18const API: &str = "https://www.googleapis.com/calendar/v3";
19
20pub const READ_ACTIONS: [&str; 4] = ["list_calendars", "list_events", "search_events", "free_busy"];
22
23const DEFAULT_RESULTS: u32 = 25;
25const MAX_RESULTS: u32 = 100;
26const DEFAULT_SPAN_DAYS: i64 = 7;
28const MAX_FREE_BUSY_DAYS: i64 = 62;
30const MAX_FREE_BUSY_CALENDARS: usize = 20;
32const DESCRIPTION_CHARS: usize = 2000;
34const ATTENDEES: usize = 50;
35
36#[derive(Debug, Default, Clone, Deserialize)]
38pub struct CalendarArgs {
39 #[serde(default)]
41 pub calendar_id: Option<String>,
42 #[serde(default)]
44 pub time_min: Option<String>,
45 #[serde(default)]
46 pub time_max: Option<String>,
47 #[serde(default)]
49 pub query: Option<String>,
50 #[serde(default)]
51 pub max_results: Option<u32>,
52 #[serde(default)]
53 pub page_token: Option<String>,
54 #[serde(default)]
56 pub time_zone: Option<String>,
57 #[serde(default)]
59 pub calendars: Option<Vec<String>>,
60}
61
62pub fn needs(action: &str) -> &'static [&'static str] {
65 match action {
66 "list_calendars" => &["calendar.calendarlist.readonly", "calendar.readonly", "calendar"],
67 "list_events" | "search_events" => &["calendar.events.readonly", "calendar.events", "calendar.readonly", "calendar"],
68 "free_busy" => &["calendar.events.freebusy", "calendar.freebusy", "calendar.readonly", "calendar"],
69 _ => &[],
70 }
71}
72
73pub fn granted_for(action: &str, granted: &[String]) -> bool {
75 needs(action)
76 .iter()
77 .any(|n| granted.iter().any(|g| g.strip_prefix(SCOPE_PREFIX).unwrap_or(g) == *n))
78}
79
80fn time_arg(name: &str, v: Option<&str>) -> Result<Option<DateTime<Utc>>, String> {
81 match v.map(str::trim).filter(|s| !s.is_empty()) {
82 None => Ok(None),
83 Some(s) => DateTime::parse_from_rfc3339(s)
84 .map(|t| Some(t.with_timezone(&Utc)))
85 .map_err(|_| format!("{name} \"{s}\" isn't an RFC 3339 time; write it like 2026-10-24T09:00:00Z")),
86 }
87}
88
89fn rfc3339(t: DateTime<Utc>) -> String {
90 t.to_rfc3339_opts(SecondsFormat::Secs, true)
91}
92
93fn window(args: &CalendarArgs, now: DateTime<Utc>) -> Result<(DateTime<Utc>, DateTime<Utc>), String> {
96 let min = time_arg("time_min", args.time_min.as_deref())?.unwrap_or(now);
97 let max = time_arg("time_max", args.time_max.as_deref())?.unwrap_or(min + Duration::days(DEFAULT_SPAN_DAYS));
98 if max <= min {
99 return Err("time_max must be after time_min".to_string());
100 }
101 Ok((min, max))
102}
103
104fn calendar_url(calendar_id: &str, tail: &str) -> Result<String, String> {
105 let mut url = url::Url::parse(API).map_err(|e| e.to_string())?;
106 url.path_segments_mut()
107 .map_err(|_| "bad Calendar API URL".to_string())?
108 .push("calendars")
109 .push(calendar_id)
110 .push(tail);
111 Ok(url.to_string())
112}
113
114fn calendar_id(args: &CalendarArgs) -> String {
115 args.calendar_id.as_deref().map(str::trim).filter(|s| !s.is_empty()).unwrap_or("primary").to_string()
116}
117
118fn page(args: &CalendarArgs, query: &mut Vec<(&'static str, String)>) {
119 let n = args.max_results.unwrap_or(DEFAULT_RESULTS).clamp(1, MAX_RESULTS);
120 query.push(("maxResults", n.to_string()));
121 if let Some(t) = args.page_token.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
122 query.push(("pageToken", t.to_string()));
123 }
124}
125
126pub fn plan(action: &str, args: &CalendarArgs, now: DateTime<Utc>) -> Result<GoogleRequest, String> {
128 let get = |url: String, query| GoogleRequest { method: reqwest::Method::GET, url, query, body: None, text: false };
129 let tz = args.time_zone.as_deref().map(str::trim).filter(|s| !s.is_empty());
130 match action {
131 "list_calendars" => {
132 let mut q = Vec::new();
133 page(args, &mut q);
134 Ok(get(format!("{API}/users/me/calendarList"), q))
135 }
136 "list_events" | "search_events" => {
137 let (min, max) = window(args, now)?;
138 let mut q = vec![
139 ("timeMin", rfc3339(min)),
140 ("timeMax", rfc3339(max)),
141 ("singleEvents", "true".to_string()),
142 ("orderBy", "startTime".to_string()),
143 ];
144 if action == "search_events" {
145 let text = args.query.as_deref().map(str::trim).unwrap_or("");
146 if text.is_empty() {
147 return Err("search_events needs query: the words to look for".to_string());
148 }
149 q.push(("q", clip(text, 200)));
150 }
151 if let Some(tz) = tz {
152 q.push(("timeZone", tz.to_string()));
153 }
154 page(args, &mut q);
155 Ok(get(calendar_url(&calendar_id(args), "events")?, q))
156 }
157 "free_busy" => {
158 let (min, max) = window(args, now)?;
159 if max - min > Duration::days(MAX_FREE_BUSY_DAYS) {
160 return Err(format!("free_busy covers at most {MAX_FREE_BUSY_DAYS} days at a time"));
161 }
162 let ids: Vec<String> = match &args.calendars {
163 Some(c) if !c.is_empty() => c.iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(),
164 _ => vec![calendar_id(args)],
165 };
166 if ids.len() > MAX_FREE_BUSY_CALENDARS {
167 return Err(format!("free_busy asks about at most {MAX_FREE_BUSY_CALENDARS} calendars at a time"));
168 }
169 let mut body = json!({
170 "timeMin": rfc3339(min),
171 "timeMax": rfc3339(max),
172 "items": ids.iter().map(|id| json!({ "id": id })).collect::<Vec<_>>(),
173 });
174 if let Some(tz) = tz {
175 body["timeZone"] = json!(tz);
176 }
177 Ok(GoogleRequest { method: reqwest::Method::POST, url: format!("{API}/freeBusy"), query: Vec::new(), body: Some(body), text: false })
178 }
179 other => Err(format!("Calendar has no action \"{other}\"; one of {}", READ_ACTIONS.join(", "))),
180 }
181}
182
183fn s<'a>(v: &'a Value, ptr: &str) -> &'a str {
184 v.pointer(ptr).and_then(Value::as_str).unwrap_or("")
185}
186
187fn copy(to: &mut Map<String, Value>, from: &Value, keys: &[(&str, &str)]) {
190 for (src, dst) in keys {
191 let v = s(from, src);
192 if !v.is_empty() {
193 to.insert((*dst).to_string(), json!(v));
194 }
195 }
196}
197
198fn when(v: &Value) -> Value {
200 match (v.get("dateTime").and_then(Value::as_str), v.get("date").and_then(Value::as_str)) {
201 (Some(t), _) => json!(t),
202 (None, Some(d)) => json!({ "date": d }),
203 _ => Value::Null,
204 }
205}
206
207fn shape_event(e: &Value) -> Value {
208 let mut out = Map::new();
209 copy(
210 &mut out,
211 e,
212 &[
213 ("/id", "id"),
214 ("/summary", "title"),
215 ("/status", "status"),
216 ("/location", "location"),
217 ("/organizer/email", "organizer"),
218 ("/htmlLink", "link"),
219 ("/hangoutLink", "meet_link"),
220 ("/recurringEventId", "recurring_event_id"),
221 ],
222 );
223 out.insert("start".into(), when(e.get("start").unwrap_or(&Value::Null)));
224 out.insert("end".into(), when(e.get("end").unwrap_or(&Value::Null)));
225 let desc = s(e, "/description");
226 if !desc.is_empty() {
227 out.insert("description".into(), json!(clip(desc, DESCRIPTION_CHARS)));
228 }
229 if let Some(att) = e.get("attendees").and_then(Value::as_array) {
230 let list: Vec<Value> = att
231 .iter()
232 .take(ATTENDEES)
233 .map(|a| {
234 let mut m = Map::new();
235 copy(&mut m, a, &[("/email", "email"), ("/displayName", "name"), ("/responseStatus", "response")]);
236 if a.get("self").and_then(Value::as_bool) == Some(true) {
237 m.insert("you".into(), json!(true));
238 }
239 Value::Object(m)
240 })
241 .collect();
242 out.insert("attendees".into(), json!(list));
243 if att.len() > ATTENDEES {
244 out.insert("attendees_not_shown".into(), json!(att.len() - ATTENDEES));
245 }
246 }
247 Value::Object(out)
248}
249
250fn next_page(body: &Value, out: &mut Map<String, Value>) {
251 let t = s(body, "/nextPageToken");
252 if !t.is_empty() {
253 out.insert("next_page_token".into(), json!(t));
254 }
255}
256
257pub fn shape(action: &str, body: &Value) -> Value {
259 let mut out = Map::new();
260 match action {
261 "list_calendars" => {
262 let items: Vec<Value> = body
263 .get("items")
264 .and_then(Value::as_array)
265 .map(|a| {
266 a.iter()
267 .map(|c| {
268 let mut m = Map::new();
269 copy(
270 &mut m,
271 c,
272 &[("/id", "id"), ("/summaryOverride", "name"), ("/summary", "calendar_name"), ("/accessRole", "access"), ("/timeZone", "time_zone")],
273 );
274 if c.get("primary").and_then(Value::as_bool) == Some(true) {
275 m.insert("primary".into(), json!(true));
276 }
277 Value::Object(m)
278 })
279 .collect()
280 })
281 .unwrap_or_default();
282 out.insert("calendars".into(), json!(items));
283 next_page(body, &mut out);
284 }
285 "list_events" | "search_events" => {
286 let items: Vec<Value> =
287 body.get("items").and_then(Value::as_array).map(|a| a.iter().map(shape_event).collect()).unwrap_or_default();
288 copy(&mut out, body, &[("/summary", "calendar"), ("/timeZone", "time_zone")]);
289 out.insert("events".into(), json!(items));
290 next_page(body, &mut out);
291 }
292 "free_busy" => {
293 let mut cals = Map::new();
294 if let Some(c) = body.get("calendars").and_then(Value::as_object) {
295 for (id, v) in c {
296 let busy: Vec<Value> = v
297 .get("busy")
298 .and_then(Value::as_array)
299 .map(|b| b.iter().map(|p| json!({ "start": s(p, "/start"), "end": s(p, "/end") })).collect())
300 .unwrap_or_default();
301 let mut m = Map::new();
302 m.insert("busy".into(), json!(busy));
303 if let Some(errs) = v.get("errors").and_then(Value::as_array).filter(|e| !e.is_empty()) {
304 let why: Vec<&str> = errs.iter().map(|e| s(e, "/reason")).collect();
305 m.insert("error".into(), json!(why.join(", ")));
306 }
307 cals.insert(id.clone(), Value::Object(m));
308 }
309 }
310 copy(&mut out, body, &[("/timeMin", "time_min"), ("/timeMax", "time_max")]);
311 out.insert("calendars".into(), Value::Object(cals));
312 }
313 _ => {}
314 }
315 Value::Object(out)
316}
317
318pub fn logged_ids(action: &str, args: &CalendarArgs) -> String {
321 match action {
322 "list_events" | "search_events" => calendar_id(args),
323 "free_busy" => match &args.calendars {
324 Some(c) if !c.is_empty() => c.iter().take(MAX_FREE_BUSY_CALENDARS).cloned().collect::<Vec<_>>().join(","),
325 _ => calendar_id(args),
326 },
327 _ => String::new(),
328 }
329}
330
331#[cfg(test)]
332#[path = "calendar_tests.rs"]
333mod tests;