| 1 | //! Read-only ICS subscriptions (holidays, Proton share links). |
| 2 | |
| 3 | use std::collections::HashSet; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use chrono::{DateTime, Utc}; |
| 7 | use store::{CalendarAccounts, IcsSubscription}; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | use chatsvc::{CalendarEvent, CalendarSource, expand_events, object_id_for, parse_calendar}; |
| 11 | |
| 12 | const REQUEST_TIMEOUT: Duration = Duration::from_secs(20); |
| 13 | |
| 14 | pub async fn add_ics_subscription( |
| 15 | accounts: &mut CalendarAccounts, |
| 16 | url: &str, |
| 17 | summary: &str, |
| 18 | ) -> Result<String, String> { |
| 19 | let url = normalize_ics_url(url)?; |
| 20 | // Smoke-fetch once so a bad URL fails at connect time. |
| 21 | let _ = fetch_one( |
| 22 | &url, |
| 23 | "tmp", |
| 24 | summary, |
| 25 | Utc::now(), |
| 26 | Utc::now() + chrono::Duration::days(1), |
| 27 | ) |
| 28 | .await?; |
| 29 | let id = Uuid::new_v4().to_string(); |
| 30 | accounts.ics_subscriptions.push(IcsSubscription { |
| 31 | id: id.clone(), |
| 32 | url, |
| 33 | summary: if summary.trim().is_empty() { |
| 34 | "ICS".into() |
| 35 | } else { |
| 36 | summary.to_owned() |
| 37 | }, |
| 38 | selected: true, |
| 39 | }); |
| 40 | Ok(id) |
| 41 | } |
| 42 | |
| 43 | /// Events plus per-subscription failure messages. |
| 44 | pub async fn fetch_ics_events( |
| 45 | accounts: &CalendarAccounts, |
| 46 | start: DateTime<Utc>, |
| 47 | end: DateTime<Utc>, |
| 48 | ) -> Result<(Vec<CalendarEvent>, Vec<String>), String> { |
| 49 | let mut all = Vec::new(); |
| 50 | let mut failures = Vec::new(); |
| 51 | for subscription in accounts |
| 52 | .ics_subscriptions |
| 53 | .iter() |
| 54 | .filter(|subscription| subscription.selected) |
| 55 | { |
| 56 | let url = match normalize_ics_url(&subscription.url) { |
| 57 | Ok(url) => url, |
| 58 | Err(error) => { |
| 59 | failures.push(format!("ICS {}: {error}", subscription.summary)); |
| 60 | continue; |
| 61 | } |
| 62 | }; |
| 63 | match fetch_one(&url, &subscription.id, &subscription.summary, start, end).await { |
| 64 | Ok(events) => all.extend(events), |
| 65 | Err(error) => failures.push(format!("ICS {}: {error}", subscription.summary)), |
| 66 | } |
| 67 | } |
| 68 | Ok((all, failures)) |
| 69 | } |
| 70 | |
| 71 | pub fn normalize_ics_url(url: &str) -> Result<String, String> { |
| 72 | let trimmed = url.trim(); |
| 73 | if trimmed.is_empty() { |
| 74 | return Err("ICS URL is empty".into()); |
| 75 | } |
| 76 | let lowered = trimmed.to_ascii_lowercase(); |
| 77 | let with_scheme = if let Some(rest) = lowered.strip_prefix("webcals://") { |
| 78 | format!("https://{}", &trimmed[trimmed.len() - rest.len()..]) |
| 79 | } else if let Some(rest) = lowered.strip_prefix("webcal://") { |
| 80 | format!("https://{}", &trimmed[trimmed.len() - rest.len()..]) |
| 81 | } else if trimmed.contains("://") { |
| 82 | trimmed.to_owned() |
| 83 | } else { |
| 84 | format!("https://{trimmed}") |
| 85 | }; |
| 86 | let parsed = url::Url::parse(&with_scheme).map_err(|e| e.to_string())?; |
| 87 | if parsed.scheme() != "https" && parsed.scheme() != "http" { |
| 88 | return Err(format!("Unsupported ICS URL scheme: {}", parsed.scheme())); |
| 89 | } |
| 90 | Ok(parsed.to_string()) |
| 91 | } |
| 92 | |
| 93 | async fn fetch_one( |
| 94 | url: &str, |
| 95 | account_id: &str, |
| 96 | calendar_name: &str, |
| 97 | start: DateTime<Utc>, |
| 98 | end: DateTime<Utc>, |
| 99 | ) -> Result<Vec<CalendarEvent>, String> { |
| 100 | let client = reqwest::Client::builder() |
| 101 | .timeout(REQUEST_TIMEOUT) |
| 102 | .build() |
| 103 | .map_err(|e| e.to_string())?; |
| 104 | let response = client.get(url).send().await.map_err(|e| e.to_string())?; |
| 105 | if !response.status().is_success() { |
| 106 | return Err(format!("HTTP {}", response.status())); |
| 107 | } |
| 108 | let body = response.text().await.map_err(|e| e.to_string())?; |
| 109 | let parsed = parse_calendar(&body); |
| 110 | let series_uids: HashSet<String> = parsed |
| 111 | .iter() |
| 112 | .filter(|event| { |
| 113 | event.rrule.is_some() || !event.rdates.is_empty() || event.recurrence_id.is_some() |
| 114 | }) |
| 115 | .map(|event| event.uid.clone()) |
| 116 | .collect(); |
| 117 | let expanded = expand_events(parsed, start, end); |
| 118 | Ok(expanded |
| 119 | .into_iter() |
| 120 | .map(|item| { |
| 121 | let series = series_uids.contains(&item.uid) || item.recurrence_id.is_some(); |
| 122 | let object_id = |
| 123 | object_id_for(&format!("ics:{account_id}"), &item.uid, series, item.start); |
| 124 | CalendarEvent { |
| 125 | object_id, |
| 126 | subject: item.summary, |
| 127 | start: item.start, |
| 128 | end: item.end, |
| 129 | all_day: item.all_day, |
| 130 | cancelled: item.cancelled, |
| 131 | online: item.join_url.is_some(), |
| 132 | join_url: item.join_url, |
| 133 | ical_uid: Some(item.uid), |
| 134 | source: CalendarSource::Ics, |
| 135 | account_id: Some(account_id.to_owned()), |
| 136 | calendar_id: Some(url.to_owned()), |
| 137 | sources: vec![CalendarSource::Ics], |
| 138 | location: item.location, |
| 139 | body_preview: item.description.clone(), |
| 140 | body_html: item.description, |
| 141 | reminders: item.reminders_minutes, |
| 142 | calendar_name: Some(calendar_name.to_owned()), |
| 143 | series, |
| 144 | ..Default::default() |
| 145 | } |
| 146 | }) |
| 147 | .collect()) |
| 148 | } |
| 149 | |
| 150 | #[cfg(test)] |
| 151 | mod tests { |
| 152 | use super::*; |
| 153 | |
| 154 | #[test] |
| 155 | fn webcal_becomes_https() { |
| 156 | assert_eq!( |
| 157 | normalize_ics_url("webcal://calendar.example/feed.ics").unwrap(), |
| 158 | "https://calendar.example/feed.ics" |
| 159 | ); |
| 160 | assert_eq!( |
| 161 | normalize_ics_url("webcals://calendar.example/feed.ics").unwrap(), |
| 162 | "https://calendar.example/feed.ics" |
| 163 | ); |
| 164 | } |
| 165 | } |