| 1 | use std::collections::HashSet; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use chrono::{DateTime, Utc}; |
| 5 | use reqwest::{Client, Method, StatusCode, header}; |
| 6 | use uuid::Uuid; |
| 7 | |
| 8 | use crate::calendar::{ |
| 9 | AttendeeResponseCounts, CalendarEvent, CalendarSource, EventAttendee, ResponseType, ShowAs, |
| 10 | }; |
| 11 | use crate::error::{Error, Result}; |
| 12 | use crate::ical::{CalDavEventDraft, exclude_occurrence_from_ics, expand_events, parse_calendar}; |
| 13 | |
| 14 | use super::discovery::{DiscoverResult, discover, reject_https_downgrade, resolve_url}; |
| 15 | use super::xml::{calendar_query_body, parse_calendar_query, parse_multistatus, propfind_body}; |
| 16 | |
| 17 | const REQUEST_TIMEOUT: Duration = Duration::from_secs(20); |
| 18 | |
| 19 | #[derive(Debug, Clone)] |
| 20 | pub struct ListedCalendar { |
| 21 | pub href: String, |
| 22 | pub summary: String, |
| 23 | pub color: Option<String>, |
| 24 | pub writable: bool, |
| 25 | } |
| 26 | |
| 27 | #[derive(Debug, Clone)] |
| 28 | pub struct CalDavEvent { |
| 29 | pub event: CalendarEvent, |
| 30 | pub href: String, |
| 31 | pub etag: Option<String>, |
| 32 | } |
| 33 | |
| 34 | pub struct CalDavClient { |
| 35 | http: Client, |
| 36 | username: String, |
| 37 | password: String, |
| 38 | } |
| 39 | |
| 40 | impl CalDavClient { |
| 41 | pub fn new(username: impl Into<String>, password: impl Into<String>) -> Result<Self> { |
| 42 | let http = Client::builder() |
| 43 | .timeout(REQUEST_TIMEOUT) |
| 44 | .redirect(reqwest::redirect::Policy::custom(|attempt| { |
| 45 | let previous = attempt.previous().last().map(|u| u.as_str()).unwrap_or(""); |
| 46 | let next = attempt.url().as_str(); |
| 47 | if previous.starts_with("https://") && next.starts_with("http://") { |
| 48 | attempt.error(std::io::Error::other("https downgrade")) |
| 49 | } else if attempt.previous().len() > 10 { |
| 50 | attempt.stop() |
| 51 | } else { |
| 52 | attempt.follow() |
| 53 | } |
| 54 | })) |
| 55 | .build() |
| 56 | .map_err(map_reqwest)?; |
| 57 | Ok(CalDavClient { |
| 58 | http, |
| 59 | username: username.into(), |
| 60 | password: password.into(), |
| 61 | }) |
| 62 | } |
| 63 | |
| 64 | pub async fn discover(&self, url: &str) -> Result<DiscoverResult> { |
| 65 | discover(self, url).await |
| 66 | } |
| 67 | |
| 68 | pub async fn list_calendars(&self, home_set: &str) -> Result<Vec<ListedCalendar>> { |
| 69 | let body = propfind_body(&[ |
| 70 | "<d:displayname/>", |
| 71 | "<d:resourcetype/>", |
| 72 | "<d:current-user-privilege-set/>", |
| 73 | "<c:supported-calendar-component-set/>", |
| 74 | "<x:calendar-color/>", |
| 75 | ]); |
| 76 | let xml = self.propfind(home_set, "1", &body).await?; |
| 77 | let mut calendars = Vec::new(); |
| 78 | for response in parse_multistatus(&xml) { |
| 79 | if !response.resource_type_calendar { |
| 80 | continue; |
| 81 | } |
| 82 | // Prefer VEVENT; if component set absent, still include calendar collections. |
| 83 | if !response.supports_vevent |
| 84 | && xml.contains("supported-calendar-component-set") |
| 85 | && response.href.contains("todo") |
| 86 | { |
| 87 | continue; |
| 88 | } |
| 89 | let href = resolve_url(home_set, &response.href)?; |
| 90 | calendars.push(ListedCalendar { |
| 91 | href, |
| 92 | summary: response |
| 93 | .displayname |
| 94 | .unwrap_or_else(|| "Calendar".to_owned()), |
| 95 | color: response.calendar_color, |
| 96 | writable: response.writable, |
| 97 | }); |
| 98 | } |
| 99 | Ok(calendars) |
| 100 | } |
| 101 | |
| 102 | pub async fn fetch_events( |
| 103 | &self, |
| 104 | calendar_href: &str, |
| 105 | account_id: &str, |
| 106 | calendar_name: Option<&str>, |
| 107 | from: DateTime<Utc>, |
| 108 | to: DateTime<Utc>, |
| 109 | ) -> Result<Vec<CalDavEvent>> { |
| 110 | let start = from.format("%Y%m%dT%H%M%SZ").to_string(); |
| 111 | let end = to.format("%Y%m%dT%H%M%SZ").to_string(); |
| 112 | let mut resources = self.calendar_query(calendar_href, &start, &end, true).await; |
| 113 | if resources.is_err() { |
| 114 | resources = self |
| 115 | .calendar_query(calendar_href, &start, &end, false) |
| 116 | .await; |
| 117 | } |
| 118 | let resources = resources?; |
| 119 | let mut out = Vec::new(); |
| 120 | for (href, etag, data) in resources { |
| 121 | let absolute = resolve_url(calendar_href, &href).unwrap_or(href); |
| 122 | let parsed = parse_calendar(&data); |
| 123 | let series_uids: HashSet<String> = parsed |
| 124 | .iter() |
| 125 | .filter(|event| { |
| 126 | event.rrule.is_some() |
| 127 | || !event.rdates.is_empty() |
| 128 | || event.recurrence_id.is_some() |
| 129 | }) |
| 130 | .map(|event| event.uid.clone()) |
| 131 | .collect(); |
| 132 | let expanded = expand_events(parsed, from, to); |
| 133 | for item in expanded { |
| 134 | let mut event = to_calendar_event(&item, account_id, &absolute, calendar_name); |
| 135 | let uid = event.ical_uid.clone().unwrap_or_default(); |
| 136 | let series = series_uids.contains(&uid) || item.recurrence_id.is_some(); |
| 137 | event.series = series; |
| 138 | event.object_id = object_id_for(&absolute, &uid, series, item.start); |
| 139 | out.push(CalDavEvent { |
| 140 | event, |
| 141 | href: absolute.clone(), |
| 142 | etag: etag.clone(), |
| 143 | }); |
| 144 | } |
| 145 | } |
| 146 | Ok(out) |
| 147 | } |
| 148 | |
| 149 | pub async fn put_event( |
| 150 | &self, |
| 151 | calendar_href: &str, |
| 152 | draft: &CalDavEventDraft, |
| 153 | stamp: DateTime<Utc>, |
| 154 | ) -> Result<String> { |
| 155 | let href = format!("{}{}.ics", ensure_trailing_slash(calendar_href), draft.uid); |
| 156 | let body = crate::ical::build_vevent(draft, stamp); |
| 157 | let response = self |
| 158 | .http |
| 159 | .put(&href) |
| 160 | .basic_auth(&self.username, Some(&self.password)) |
| 161 | .header(header::CONTENT_TYPE, "text/calendar; charset=utf-8") |
| 162 | .header(header::IF_NONE_MATCH, "*") |
| 163 | .body(body) |
| 164 | .send() |
| 165 | .await |
| 166 | .map_err(map_reqwest)?; |
| 167 | ensure_auth(response.status())?; |
| 168 | if !response.status().is_success() { |
| 169 | return Err(Error::UnexpectedAnswer(format!( |
| 170 | "CalDAV PUT failed: {}", |
| 171 | response.status() |
| 172 | ))); |
| 173 | } |
| 174 | Ok(href) |
| 175 | } |
| 176 | |
| 177 | pub async fn delete(&self, href: &str, etag: Option<&str>) -> Result<()> { |
| 178 | let mut request = self |
| 179 | .http |
| 180 | .delete(href) |
| 181 | .basic_auth(&self.username, Some(&self.password)); |
| 182 | if let Some(etag) = etag { |
| 183 | request = request.header(header::IF_MATCH, format!("\"{etag}\"")); |
| 184 | } |
| 185 | let response = request.send().await.map_err(map_reqwest)?; |
| 186 | ensure_auth(response.status())?; |
| 187 | if response.status() == StatusCode::NOT_FOUND || response.status().is_success() { |
| 188 | return Ok(()); |
| 189 | } |
| 190 | Err(Error::UnexpectedAnswer(format!( |
| 191 | "CalDAV DELETE failed: {}", |
| 192 | response.status() |
| 193 | ))) |
| 194 | } |
| 195 | |
| 196 | /// Exclude one occurrence by EXDATE on the master; does not DELETE the series href. |
| 197 | pub async fn exclude_occurrence( |
| 198 | &self, |
| 199 | href: &str, |
| 200 | occurrence: DateTime<Utc>, |
| 201 | etag: Option<&str>, |
| 202 | ) -> Result<()> { |
| 203 | let response = self |
| 204 | .http |
| 205 | .get(href) |
| 206 | .basic_auth(&self.username, Some(&self.password)) |
| 207 | .send() |
| 208 | .await |
| 209 | .map_err(map_reqwest)?; |
| 210 | ensure_auth(response.status())?; |
| 211 | let fresh_etag = response |
| 212 | .headers() |
| 213 | .get(header::ETAG) |
| 214 | .and_then(|v| v.to_str().ok()) |
| 215 | .map(|v| v.trim_matches('"').to_owned()); |
| 216 | let body = response.text().await.map_err(map_reqwest)?; |
| 217 | let updated = |
| 218 | exclude_occurrence_from_ics(&body, occurrence).map_err(Error::UnexpectedAnswer)?; |
| 219 | let match_etag = etag.or(fresh_etag.as_deref()); |
| 220 | let mut request = self |
| 221 | .http |
| 222 | .put(href) |
| 223 | .basic_auth(&self.username, Some(&self.password)) |
| 224 | .header(header::CONTENT_TYPE, "text/calendar; charset=utf-8") |
| 225 | .body(updated); |
| 226 | if let Some(etag) = match_etag { |
| 227 | request = request.header(header::IF_MATCH, format!("\"{etag}\"")); |
| 228 | } |
| 229 | let response = request.send().await.map_err(map_reqwest)?; |
| 230 | if response.status() == StatusCode::PRECONDITION_FAILED { |
| 231 | return Err(Error::UnexpectedAnswer( |
| 232 | "CalDAV event changed on the server; reload and try again".into(), |
| 233 | )); |
| 234 | } |
| 235 | ensure_auth(response.status())?; |
| 236 | if !response.status().is_success() { |
| 237 | return Err(Error::UnexpectedAnswer(format!( |
| 238 | "CalDAV EXDATE failed: {}", |
| 239 | response.status() |
| 240 | ))); |
| 241 | } |
| 242 | Ok(()) |
| 243 | } |
| 244 | |
| 245 | pub async fn update_partstat( |
| 246 | &self, |
| 247 | href: &str, |
| 248 | etag: Option<&str>, |
| 249 | mailto: &str, |
| 250 | partstat: &str, |
| 251 | ) -> Result<()> { |
| 252 | let response = self |
| 253 | .http |
| 254 | .get(href) |
| 255 | .basic_auth(&self.username, Some(&self.password)) |
| 256 | .send() |
| 257 | .await |
| 258 | .map_err(map_reqwest)?; |
| 259 | ensure_auth(response.status())?; |
| 260 | let fresh_etag = response |
| 261 | .headers() |
| 262 | .get(header::ETAG) |
| 263 | .and_then(|v| v.to_str().ok()) |
| 264 | .map(|v| v.trim_matches('"').to_owned()); |
| 265 | let body = response.text().await.map_err(map_reqwest)?; |
| 266 | let updated = patch_partstat(&body, mailto, partstat); |
| 267 | let match_etag = etag.or(fresh_etag.as_deref()); |
| 268 | let mut request = self |
| 269 | .http |
| 270 | .put(href) |
| 271 | .basic_auth(&self.username, Some(&self.password)) |
| 272 | .header(header::CONTENT_TYPE, "text/calendar; charset=utf-8") |
| 273 | .body(updated); |
| 274 | if let Some(etag) = match_etag { |
| 275 | request = request.header(header::IF_MATCH, format!("\"{etag}\"")); |
| 276 | } |
| 277 | let response = request.send().await.map_err(map_reqwest)?; |
| 278 | if response.status() == StatusCode::PRECONDITION_FAILED { |
| 279 | return Err(Error::UnexpectedAnswer( |
| 280 | "CalDAV event changed on the server; reload and try again".into(), |
| 281 | )); |
| 282 | } |
| 283 | ensure_auth(response.status())?; |
| 284 | if !response.status().is_success() { |
| 285 | return Err(Error::UnexpectedAnswer(format!( |
| 286 | "CalDAV RSVP failed: {}", |
| 287 | response.status() |
| 288 | ))); |
| 289 | } |
| 290 | Ok(()) |
| 291 | } |
| 292 | |
| 293 | pub async fn propfind(&self, url: &str, depth: &str, body: &str) -> Result<String> { |
| 294 | let method = Method::from_bytes(b"PROPFIND").unwrap(); |
| 295 | let response = self |
| 296 | .http |
| 297 | .request(method, url) |
| 298 | .basic_auth(&self.username, Some(&self.password)) |
| 299 | .header("Depth", depth) |
| 300 | .header(header::CONTENT_TYPE, "application/xml; charset=utf-8") |
| 301 | .body(body.to_owned()) |
| 302 | .send() |
| 303 | .await |
| 304 | .map_err(map_reqwest)?; |
| 305 | reject_https_downgrade(url, response.url().as_str())?; |
| 306 | if response.status() == StatusCode::UNAUTHORIZED { |
| 307 | let www = response |
| 308 | .headers() |
| 309 | .get(header::WWW_AUTHENTICATE) |
| 310 | .and_then(|v| v.to_str().ok()) |
| 311 | .unwrap_or(""); |
| 312 | if www.to_ascii_lowercase().contains("digest") { |
| 313 | return Err(Error::UnexpectedAnswer( |
| 314 | "CalDAV Digest authentication is not supported; enable Basic auth or use an app password with Basic".into(), |
| 315 | )); |
| 316 | } |
| 317 | return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into())); |
| 318 | } |
| 319 | if !response.status().is_success() && response.status().as_u16() != 207 { |
| 320 | return Err(Error::UnexpectedAnswer(format!( |
| 321 | "CalDAV PROPFIND failed: {}", |
| 322 | response.status() |
| 323 | ))); |
| 324 | } |
| 325 | response.text().await.map_err(map_reqwest) |
| 326 | } |
| 327 | |
| 328 | async fn calendar_query( |
| 329 | &self, |
| 330 | url: &str, |
| 331 | start: &str, |
| 332 | end: &str, |
| 333 | expand: bool, |
| 334 | ) -> Result<Vec<(String, Option<String>, String)>> { |
| 335 | let method = Method::from_bytes(b"REPORT").unwrap(); |
| 336 | let body = calendar_query_body(start, end, expand); |
| 337 | let response = self |
| 338 | .http |
| 339 | .request(method, url) |
| 340 | .basic_auth(&self.username, Some(&self.password)) |
| 341 | .header("Depth", "1") |
| 342 | .header(header::CONTENT_TYPE, "application/xml; charset=utf-8") |
| 343 | .body(body) |
| 344 | .send() |
| 345 | .await |
| 346 | .map_err(map_reqwest)?; |
| 347 | ensure_auth(response.status())?; |
| 348 | if !response.status().is_success() && response.status().as_u16() != 207 { |
| 349 | return Err(Error::UnexpectedAnswer(format!( |
| 350 | "CalDAV REPORT failed: {}", |
| 351 | response.status() |
| 352 | ))); |
| 353 | } |
| 354 | let text = response.text().await.map_err(map_reqwest)?; |
| 355 | Ok(parse_calendar_query(&text)) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | fn to_calendar_event( |
| 360 | parsed: &crate::ical::ParsedEvent, |
| 361 | account_id: &str, |
| 362 | calendar_id: &str, |
| 363 | calendar_name: Option<&str>, |
| 364 | ) -> CalendarEvent { |
| 365 | let response = own_response(parsed); |
| 366 | CalendarEvent { |
| 367 | object_id: parsed.uid.clone(), |
| 368 | subject: parsed.summary.clone(), |
| 369 | start: parsed.start, |
| 370 | end: parsed.end, |
| 371 | all_day: parsed.all_day, |
| 372 | cancelled: parsed.cancelled, |
| 373 | online: parsed.join_url.is_some(), |
| 374 | join_url: parsed.join_url.clone(), |
| 375 | thread_id: None, |
| 376 | organizer_name: parsed.organizer.as_ref().map(|(n, _)| n.clone()), |
| 377 | organizer_address: parsed.organizer.as_ref().and_then(|(_, a)| a.clone()), |
| 378 | ical_uid: Some(parsed.uid.clone()), |
| 379 | response, |
| 380 | show_as: if parsed.transparent { |
| 381 | ShowAs::Free |
| 382 | } else { |
| 383 | ShowAs::Busy |
| 384 | }, |
| 385 | dial_in: None, |
| 386 | source: CalendarSource::CalDav, |
| 387 | account_id: Some(account_id.to_owned()), |
| 388 | calendar_id: Some(calendar_id.to_owned()), |
| 389 | sources: vec![CalendarSource::CalDav], |
| 390 | location: parsed.location.clone(), |
| 391 | body_preview: parsed.description.clone().map(|d| { |
| 392 | if d.chars().count() > 280 { |
| 393 | d.chars().take(280).collect() |
| 394 | } else { |
| 395 | d |
| 396 | } |
| 397 | }), |
| 398 | body_html: parsed.description.clone(), |
| 399 | // Overridden by fetch_events after expansion (RRULE is cleared on occurrences). |
| 400 | series: parsed.rrule.is_some() |
| 401 | || !parsed.rdates.is_empty() |
| 402 | || parsed.recurrence_id.is_some(), |
| 403 | series_master_id: None, |
| 404 | response_counts: None::<AttendeeResponseCounts>, |
| 405 | attendees: parsed |
| 406 | .attendees |
| 407 | .iter() |
| 408 | .map(|a| EventAttendee { |
| 409 | name: a.cn.clone().unwrap_or_else(|| a.mailto.clone()), |
| 410 | address: Some(a.mailto.clone()), |
| 411 | response: partstat_to_response(a.partstat.as_deref().unwrap_or("NEEDS-ACTION")), |
| 412 | required: a |
| 413 | .role |
| 414 | .as_deref() |
| 415 | .map(|r| !r.eq_ignore_ascii_case("OPT-PARTICIPANT")) |
| 416 | .unwrap_or(true), |
| 417 | }) |
| 418 | .collect(), |
| 419 | reminders: parsed.reminders_minutes.clone(), |
| 420 | source_link: None, |
| 421 | web_link: None, |
| 422 | calendar_name: calendar_name.map(str::to_owned), |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | fn own_response(parsed: &crate::ical::ParsedEvent) -> ResponseType { |
| 427 | parsed |
| 428 | .attendees |
| 429 | .iter() |
| 430 | .find_map(|a| a.partstat.as_deref().map(partstat_to_response)) |
| 431 | .unwrap_or(ResponseType::NotResponded) |
| 432 | } |
| 433 | |
| 434 | fn partstat_to_response(partstat: &str) -> ResponseType { |
| 435 | match partstat.to_ascii_uppercase().as_str() { |
| 436 | "ACCEPTED" => ResponseType::Accepted, |
| 437 | "TENTATIVE" => ResponseType::Tentative, |
| 438 | "DECLINED" => ResponseType::Declined, |
| 439 | "DELEGATED" => ResponseType::NotResponded, |
| 440 | _ => ResponseType::NotResponded, |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | pub fn partstat_for_reply(reply: crate::calendar::Reply) -> &'static str { |
| 445 | match reply { |
| 446 | crate::calendar::Reply::Accept => "ACCEPTED", |
| 447 | crate::calendar::Reply::Tentative => "TENTATIVE", |
| 448 | crate::calendar::Reply::Decline => "DECLINED", |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | fn patch_partstat(ics: &str, mailto: &str, partstat: &str) -> String { |
| 453 | let target = mailto.trim_start_matches("mailto:").to_ascii_lowercase(); |
| 454 | let mut out = String::with_capacity(ics.len() + 32); |
| 455 | for line in ics.lines() { |
| 456 | if line.to_ascii_uppercase().starts_with("ATTENDEE") |
| 457 | && line.to_ascii_lowercase().contains(&target) |
| 458 | { |
| 459 | let mut rewritten = line.to_owned(); |
| 460 | if let Some(start) = rewritten.to_ascii_uppercase().find("PARTSTAT=") { |
| 461 | let rest = &rewritten[start + 9..]; |
| 462 | let end = rest.find([';', ':']).unwrap_or(rest.len()); |
| 463 | rewritten.replace_range(start + 9..start + 9 + end, partstat); |
| 464 | } else if let Some(idx) = rewritten.find(':') { |
| 465 | rewritten.insert_str(idx, &format!(";PARTSTAT={partstat}")); |
| 466 | } |
| 467 | out.push_str(&rewritten); |
| 468 | out.push_str("\r\n"); |
| 469 | } else { |
| 470 | out.push_str(line); |
| 471 | out.push_str("\r\n"); |
| 472 | } |
| 473 | } |
| 474 | out |
| 475 | } |
| 476 | |
| 477 | fn ensure_trailing_slash(url: &str) -> String { |
| 478 | if url.ends_with('/') { |
| 479 | url.to_owned() |
| 480 | } else { |
| 481 | format!("{url}/") |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | fn ensure_auth(status: StatusCode) -> Result<()> { |
| 486 | if status == StatusCode::UNAUTHORIZED { |
| 487 | return Err(Error::UnexpectedAnswer("CalDAV unauthorized".into())); |
| 488 | } |
| 489 | Ok(()) |
| 490 | } |
| 491 | |
| 492 | fn map_reqwest(error: reqwest::Error) -> Error { |
| 493 | Error::UnexpectedAnswer(error.to_string()) |
| 494 | } |
| 495 | |
| 496 | pub fn new_event_uid() -> String { |
| 497 | format!("{}@rusty-teams", Uuid::new_v4()) |
| 498 | } |
| 499 | |
| 500 | pub fn object_id_for(href: &str, uid: &str, series: bool, start: DateTime<Utc>) -> String { |
| 501 | if series { |
| 502 | format!("{href}#{uid}#{}", start.format("%Y%m%dT%H%M%SZ")) |
| 503 | } else { |
| 504 | format!("{href}#{uid}") |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | pub fn href_from_object_id(object_id: &str) -> &str { |
| 509 | object_id.split('#').next().unwrap_or(object_id) |
| 510 | } |
| 511 | |
| 512 | #[cfg(test)] |
| 513 | mod object_id_tests { |
| 514 | use super::*; |
| 515 | use chrono::TimeZone; |
| 516 | |
| 517 | #[test] |
| 518 | fn series_occurrences_get_distinct_ids() { |
| 519 | let start_a = Utc.with_ymd_and_hms(2026, 1, 5, 9, 0, 0).unwrap(); |
| 520 | let start_b = Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap(); |
| 521 | let a = object_id_for("https://dav.example/cal/evt.ics", "series", true, start_a); |
| 522 | let b = object_id_for("https://dav.example/cal/evt.ics", "series", true, start_b); |
| 523 | assert_ne!(a, b); |
| 524 | assert!(a.ends_with("#20260105T090000Z")); |
| 525 | assert_eq!(href_from_object_id(&a), "https://dav.example/cal/evt.ics"); |
| 526 | } |
| 527 | } |