expand.rs
| 1 | //! Recurrence expansion: DTSTART + RRULE + RDATE - EXRULE - EXDATE, with |
| 2 | //! RECURRENCE-ID overrides applied. |
| 3 | |
| 4 | use std::collections::{BTreeMap, HashMap, HashSet}; |
| 5 | use std::ops::Range; |
| 6 | |
| 7 | use calcard::common::{CalendarScale, PartialDateTime}; |
| 8 | use calcard::icalendar::{ |
| 9 | ICalendar, ICalendarComponent, ICalendarComponentType, ICalendarDuration, ICalendarFrequency, |
| 10 | ICalendarParameterName, ICalendarPeriod, ICalendarProperty, ICalendarRecurrenceRule, |
| 11 | ICalendarSkip, ICalendarValue, |
| 12 | }; |
| 13 | use chrono::{DateTime, NaiveDateTime, NaiveTime, TimeDelta, TimeZone, Timelike, Utc, Weekday}; |
| 14 | |
| 15 | use crate::zone::{Zone, Zones, add, add_local}; |
| 16 | |
| 17 | /// Occurrences the rules of one series may generate together before |
| 18 | /// expansion gives up. |
| 19 | // ponytail: COUNT, MONTHLY and YEARLY rules iterate from DTSTART, so a long |
| 20 | // running one can hit this. Skip ahead for them if that matters. |
| 21 | const MAX_OCCURRENCES: usize = 1_000_000; |
| 22 | |
| 23 | #[derive(Debug, Clone, PartialEq)] |
| 24 | pub struct Instance { |
| 25 | pub start: DateTime<Utc>, |
| 26 | pub end: DateTime<Utc>, |
| 27 | /// The original start. `None` if the component does not recur. |
| 28 | pub recurrence_id: Option<DateTime<Utc>>, |
| 29 | /// Index into `ICalendar::components` of the master or override that |
| 30 | /// describes this instance. |
| 31 | pub component: usize, |
| 32 | } |
| 33 | |
| 34 | #[derive(Debug, Default)] |
| 35 | pub struct Expansion { |
| 36 | /// Sorted by start. |
| 37 | pub instances: Vec<Instance>, |
| 38 | /// A series reached `MAX_OCCURRENCES`, so later instances are missing. |
| 39 | pub truncated: bool, |
| 40 | } |
| 41 | |
| 42 | /// The instances of all VEVENT, VTODO and VJOURNAL components that overlap |
| 43 | /// `window`. A zero-length instance overlaps if it starts inside. |
| 44 | /// |
| 45 | /// Components are grouped by type and UID into one master and its overrides. |
| 46 | /// Components without DTSTART are skipped. `floating` interprets values |
| 47 | /// without a zone. |
| 48 | pub fn expand(cal: &ICalendar, window: Range<DateTime<Utc>>, floating: Zone) -> Expansion { |
| 49 | let zones = Zones::new(cal, floating); |
| 50 | let mut out = Expansion::default(); |
| 51 | let mut groups: HashMap<(&ICalendarComponentType, &str), Vec<usize>> = HashMap::new(); |
| 52 | for (i, c) in cal.components.iter().enumerate() { |
| 53 | if !matches!( |
| 54 | c.component_type, |
| 55 | ICalendarComponentType::VEvent |
| 56 | | ICalendarComponentType::VTodo |
| 57 | | ICalendarComponentType::VJournal |
| 58 | ) { |
| 59 | continue; |
| 60 | } |
| 61 | match c.uid() { |
| 62 | Some(uid) => groups.entry((&c.component_type, uid)).or_default().push(i), |
| 63 | None => expand_group(cal, &zones, &[i], &window, &mut out), |
| 64 | } |
| 65 | } |
| 66 | for group in groups.values() { |
| 67 | expand_group(cal, &zones, group, &window, &mut out); |
| 68 | } |
| 69 | out.instances.sort_by_key(|i| (i.start, i.component)); |
| 70 | out |
| 71 | } |
| 72 | |
| 73 | /// A date or date-time value and the zone it is in. |
| 74 | #[derive(Debug, Clone)] |
| 75 | pub(crate) struct Stamp { |
| 76 | pub(crate) local: NaiveDateTime, |
| 77 | zone: Zone, |
| 78 | pub(crate) date: bool, |
| 79 | /// A date-time without TZID or UTC offset. |
| 80 | floating: bool, |
| 81 | } |
| 82 | |
| 83 | impl Stamp { |
| 84 | pub(crate) fn utc(&self) -> DateTime<Utc> { |
| 85 | self.zone.to_utc(self.local) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | #[derive(Debug, Clone)] |
| 90 | enum Length { |
| 91 | Exact(TimeDelta), |
| 92 | /// Whole days count in wall-clock time, so a day can last 23 or 25 hours. |
| 93 | Nominal { |
| 94 | days: i64, |
| 95 | exact: TimeDelta, |
| 96 | }, |
| 97 | } |
| 98 | |
| 99 | impl Length { |
| 100 | fn end(&self, zone: &Zone, local: NaiveDateTime, utc: DateTime<Utc>) -> DateTime<Utc> { |
| 101 | match self { |
| 102 | Length::Exact(d) => add(utc, *d), |
| 103 | Length::Nominal { days, exact } => add( |
| 104 | zone.to_utc(add_local(local, TimeDelta::days(*days))), |
| 105 | *exact, |
| 106 | ), |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// An upper bound, for widening the generation window. |
| 111 | fn max(&self) -> TimeDelta { |
| 112 | match self { |
| 113 | Length::Exact(d) => *d, |
| 114 | Length::Nominal { days, exact } => TimeDelta::days(days + 1) + *exact, |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// DTSTART and length of one component. |
| 120 | #[derive(Debug, Clone)] |
| 121 | struct Timing { |
| 122 | start: Stamp, |
| 123 | length: Length, |
| 124 | component: usize, |
| 125 | } |
| 126 | |
| 127 | impl Timing { |
| 128 | fn of(cal: &ICalendar, zones: &Zones, component: usize) -> Option<Self> { |
| 129 | let c = &cal.components[component]; |
| 130 | let start = prop_stamp(zones, c, &ICalendarProperty::Dtstart)?; |
| 131 | let end = match c.component_type { |
| 132 | ICalendarComponentType::VTodo => ICalendarProperty::Due, |
| 133 | _ => ICalendarProperty::Dtend, |
| 134 | }; |
| 135 | let zero = TimeDelta::zero(); |
| 136 | let length = if let Some(end) = prop_stamp(zones, c, &end) { |
| 137 | if start.date && end.date { |
| 138 | Length::Nominal { |
| 139 | days: (end.local - start.local).num_days().max(0), |
| 140 | exact: zero, |
| 141 | } |
| 142 | } else { |
| 143 | Length::Exact((end.utc() - start.utc()).max(zero)) |
| 144 | } |
| 145 | } else if let Some(ICalendarValue::Duration(d)) = c |
| 146 | .property(&ICalendarProperty::Duration) |
| 147 | .and_then(|e| e.values.first()) |
| 148 | { |
| 149 | nominal(d) |
| 150 | } else if start.date { |
| 151 | Length::Nominal { |
| 152 | days: 1, |
| 153 | exact: zero, |
| 154 | } |
| 155 | } else { |
| 156 | Length::Exact(zero) |
| 157 | }; |
| 158 | Some(Timing { |
| 159 | start, |
| 160 | length, |
| 161 | component, |
| 162 | }) |
| 163 | } |
| 164 | |
| 165 | fn end_at(&self, local: NaiveDateTime, utc: DateTime<Utc>) -> DateTime<Utc> { |
| 166 | self.length.end(&self.start.zone, local, utc) |
| 167 | } |
| 168 | |
| 169 | /// A RECURRENCE-ID, RDATE or EXDATE value. Dates and floating times are |
| 170 | /// read in the zone of the series: clients write them that way. |
| 171 | fn utc_of(&self, s: &Stamp) -> DateTime<Utc> { |
| 172 | if s.date || s.floating { |
| 173 | self.start.zone.to_utc(s.local) |
| 174 | } else { |
| 175 | s.utc() |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// The identity of a recurrence instance. An all-day series matches by |
| 180 | /// date alone, whatever zone the other value names. |
| 181 | fn key(&self, s: &Stamp) -> i64 { |
| 182 | if self.start.date { |
| 183 | day_key(s.local) |
| 184 | } else { |
| 185 | self.utc_of(s).timestamp() |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | fn member_key(&self, local: NaiveDateTime, utc: DateTime<Utc>) -> i64 { |
| 190 | if self.start.date { |
| 191 | day_key(local) |
| 192 | } else { |
| 193 | utc.timestamp() |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | struct Member { |
| 199 | local: NaiveDateTime, |
| 200 | utc: DateTime<Utc>, |
| 201 | /// From an RDATE period. |
| 202 | length: Option<Length>, |
| 203 | } |
| 204 | |
| 205 | struct Override { |
| 206 | sequence: i64, |
| 207 | recurrence_id: DateTime<Utc>, |
| 208 | timing: Timing, |
| 209 | } |
| 210 | |
| 211 | fn expand_group( |
| 212 | cal: &ICalendar, |
| 213 | zones: &Zones, |
| 214 | group: &[usize], |
| 215 | window: &Range<DateTime<Utc>>, |
| 216 | out: &mut Expansion, |
| 217 | ) { |
| 218 | let comp = |i: usize| &cal.components[i]; |
| 219 | let sequence = |i: usize| { |
| 220 | comp(i) |
| 221 | .property(&ICalendarProperty::Sequence) |
| 222 | .and_then(|e| e.values.first()?.as_integer()) |
| 223 | .unwrap_or(0) |
| 224 | }; |
| 225 | let (overrides, masters): (Vec<usize>, Vec<usize>) = group |
| 226 | .iter() |
| 227 | .partition(|&&i| comp(i).has_property(&ICalendarProperty::RecurrenceId)); |
| 228 | // Several masters for one UID are invalid. Take the latest revision, |
| 229 | // or the first one on a tie. |
| 230 | let master = masters |
| 231 | .into_iter() |
| 232 | .rev() |
| 233 | .max_by_key(|&i| sequence(i)) |
| 234 | .and_then(|i| Timing::of(cal, zones, i)); |
| 235 | |
| 236 | // Matched by RECURRENCE-ID only. SEQUENCE picks between two overrides of |
| 237 | // one instance and never decides whether an override applies. |
| 238 | let mut exact: HashMap<i64, Override> = HashMap::new(); |
| 239 | let mut future: Vec<(i64, DateTime<Utc>, Timing)> = Vec::new(); |
| 240 | for i in overrides { |
| 241 | let Some(e) = comp(i).property(&ICalendarProperty::RecurrenceId) else { |
| 242 | continue; |
| 243 | }; |
| 244 | let (Some(timing), Some(rid)) = ( |
| 245 | Timing::of(cal, zones, i), |
| 246 | e.values |
| 247 | .first() |
| 248 | .and_then(|v| stamp(zones, v.as_partial_date_time()?, e.tz_id())), |
| 249 | ) else { |
| 250 | continue; |
| 251 | }; |
| 252 | let (key, rid_utc) = match &master { |
| 253 | Some(m) => (m.key(&rid), m.utc_of(&rid)), |
| 254 | None => (rid.utc().timestamp(), rid.utc()), |
| 255 | }; |
| 256 | if e.parameter(&ICalendarParameterName::Range).is_some() { |
| 257 | future.push((key, rid_utc, timing.clone())); |
| 258 | } |
| 259 | if exact.get(&key).is_none_or(|old| sequence(i) > old.sequence) { |
| 260 | let sequence = sequence(i); |
| 261 | exact.insert( |
| 262 | key, |
| 263 | Override { |
| 264 | sequence, |
| 265 | recurrence_id: rid_utc, |
| 266 | timing, |
| 267 | }, |
| 268 | ); |
| 269 | } |
| 270 | } |
| 271 | future.sort_by_key(|f| f.0); |
| 272 | |
| 273 | let Some(m) = master else { |
| 274 | push_overrides(out, window, exact.values()); |
| 275 | return; |
| 276 | }; |
| 277 | let mc = comp(m.component); |
| 278 | let mz = &m.start.zone; |
| 279 | |
| 280 | let rules: Vec<_> = mc |
| 281 | .properties(&ICalendarProperty::Rrule) |
| 282 | .filter_map(|e| rule(e.values.first()?)) |
| 283 | .collect(); |
| 284 | let mut set: BTreeMap<i64, Member> = BTreeMap::new(); |
| 285 | let mut slack = m.length.max(); |
| 286 | // DTSTART is an instance even when it does not match the RRULE, unless |
| 287 | // the series ended before it. |
| 288 | let ended = !rules.is_empty() |
| 289 | && rules.iter().all(|r| { |
| 290 | r.until |
| 291 | .as_ref() |
| 292 | .and_then(|u| until_local(u, &m.start)) |
| 293 | .is_some_and(|u| u < m.start.local) |
| 294 | }); |
| 295 | if !ended { |
| 296 | let utc = m.start.utc(); |
| 297 | set.insert( |
| 298 | m.member_key(m.start.local, utc), |
| 299 | Member { |
| 300 | local: m.start.local, |
| 301 | utc, |
| 302 | length: None, |
| 303 | }, |
| 304 | ); |
| 305 | } |
| 306 | for e in mc.properties(&ICalendarProperty::Rdate) { |
| 307 | for v in &e.values { |
| 308 | let (s, length) = match v { |
| 309 | ICalendarValue::PartialDateTime(p) => { |
| 310 | let Some(s) = stamp(zones, p, e.tz_id()) else { |
| 311 | continue; |
| 312 | }; |
| 313 | (s, None) |
| 314 | } |
| 315 | ICalendarValue::Period(ICalendarPeriod::Range { start, end }) => { |
| 316 | let (Some(s), Some(end)) = |
| 317 | (stamp(zones, start, e.tz_id()), stamp(zones, end, e.tz_id())) |
| 318 | else { |
| 319 | continue; |
| 320 | }; |
| 321 | let d = (end.utc() - s.utc()).max(TimeDelta::zero()); |
| 322 | (s, Some(Length::Exact(d))) |
| 323 | } |
| 324 | ICalendarValue::Period(ICalendarPeriod::Duration { start, duration }) => { |
| 325 | let Some(s) = stamp(zones, start, e.tz_id()) else { |
| 326 | continue; |
| 327 | }; |
| 328 | (s, Some(nominal(duration))) |
| 329 | } |
| 330 | _ => continue, |
| 331 | }; |
| 332 | let utc = m.utc_of(&s); |
| 333 | let local = mz.to_local(utc); |
| 334 | if let Some(l) = &length { |
| 335 | slack = slack.max(l.max()); |
| 336 | } |
| 337 | // A period on DTSTART or a rule instance still sets its length. |
| 338 | let member = set.entry(m.key(&s)).or_insert(Member { |
| 339 | local, |
| 340 | utc, |
| 341 | length: None, |
| 342 | }); |
| 343 | member.length = length.or(member.length.take()); |
| 344 | } |
| 345 | } |
| 346 | for (_, rid, t) in &future { |
| 347 | slack = slack.max((t.start.utc() - *rid).abs() + t.length.max()); |
| 348 | } |
| 349 | let slack = slack + TimeDelta::days(1); |
| 350 | let (from, to) = (add(window.start, -slack), add(window.end, slack)); |
| 351 | let (from_local, to_local) = (mz.to_local(from), mz.to_local(to)); |
| 352 | |
| 353 | let mut budget = MAX_OCCURRENCES; |
| 354 | let mut excluded = HashSet::new(); |
| 355 | for e in mc.properties(&ICalendarProperty::Exrule) { |
| 356 | let Some(rule) = e.values.first().and_then(rule) else { |
| 357 | continue; |
| 358 | }; |
| 359 | for local in occurrences_capped(rule, &m, from_local, to_local, &mut budget, out) { |
| 360 | excluded.insert(m.member_key(local, mz.to_utc(local))); |
| 361 | } |
| 362 | } |
| 363 | // ponytail: sub-daily rules iterate in wall time. A DST fall-back skips the |
| 364 | // repeated hour, and a spring-forward collapses a shifted instance into the |
| 365 | // next (COUNT=5 gives 4). Iterate in elapsed time, BYHOUR in local, to fix. |
| 366 | for rule in rules { |
| 367 | for local in occurrences_capped(rule, &m, from_local, to_local, &mut budget, out) { |
| 368 | let utc = mz.to_utc(local); |
| 369 | if utc >= from { |
| 370 | set.entry(m.member_key(local, utc)).or_insert(Member { |
| 371 | local, |
| 372 | utc, |
| 373 | length: None, |
| 374 | }); |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | // A DATE EXDATE on a DATE-TIME series removes every instance on that day. |
| 380 | let mut excluded_days = HashSet::new(); |
| 381 | for e in mc.properties(&ICalendarProperty::Exdate) { |
| 382 | for s in e |
| 383 | .values |
| 384 | .iter() |
| 385 | .filter_map(|v| stamp(zones, v.as_partial_date_time()?, e.tz_id())) |
| 386 | { |
| 387 | if s.date && !m.start.date { |
| 388 | excluded_days.insert(s.local.date()); |
| 389 | } else { |
| 390 | excluded.insert(m.key(&s)); |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | // An EXDATE removes an override of that instance too. An override whose |
| 396 | // RECURRENCE-ID matches no instance still shows, as in clients. |
| 397 | push_overrides( |
| 398 | out, |
| 399 | window, |
| 400 | exact.iter().filter_map(|(key, o)| { |
| 401 | let day = mz.to_local(o.recurrence_id).date(); |
| 402 | (!excluded.contains(key) && !excluded_days.contains(&day)).then_some(o) |
| 403 | }), |
| 404 | ); |
| 405 | |
| 406 | let recurs = |
| 407 | mc.has_property(&ICalendarProperty::Rrule) || mc.has_property(&ICalendarProperty::Rdate); |
| 408 | for (key, member) in &set { |
| 409 | if member.utc < from |
| 410 | || excluded.contains(key) |
| 411 | || excluded_days.contains(&member.local.date()) |
| 412 | || exact.contains_key(key) |
| 413 | { |
| 414 | continue; |
| 415 | } |
| 416 | let recurrence_id = recurs.then_some(member.utc); |
| 417 | // The latest THISANDFUTURE override before this instance moves it by |
| 418 | // the same offset and gives it the override's length. The offset is |
| 419 | // wall-clock time, so later instances keep their local time across DST. |
| 420 | let latest = future.partition_point(|f| f.0 <= *key).checked_sub(1); |
| 421 | let instance = match latest.map(|i| &future[i]) { |
| 422 | Some((_, rid, t)) => { |
| 423 | let shift = mz.to_local(t.start.utc()) - mz.to_local(*rid); |
| 424 | let start = mz.to_utc(add_local(member.local, shift)); |
| 425 | Instance { |
| 426 | start, |
| 427 | end: t.end_at(t.start.zone.to_local(start), start), |
| 428 | recurrence_id, |
| 429 | component: t.component, |
| 430 | } |
| 431 | } |
| 432 | None => Instance { |
| 433 | start: member.utc, |
| 434 | end: member.length.as_ref().map_or_else( |
| 435 | || m.end_at(member.local, member.utc), |
| 436 | |l| l.end(mz, member.local, member.utc), |
| 437 | ), |
| 438 | recurrence_id, |
| 439 | component: m.component, |
| 440 | }, |
| 441 | }; |
| 442 | push(out, window, instance); |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | fn push_overrides<'a>( |
| 447 | out: &mut Expansion, |
| 448 | window: &Range<DateTime<Utc>>, |
| 449 | overrides: impl Iterator<Item = &'a Override>, |
| 450 | ) { |
| 451 | for o in overrides { |
| 452 | let t = &o.timing; |
| 453 | let start = t.start.utc(); |
| 454 | let end = t.end_at(t.start.local, start); |
| 455 | push( |
| 456 | out, |
| 457 | window, |
| 458 | Instance { |
| 459 | start, |
| 460 | end, |
| 461 | recurrence_id: Some(o.recurrence_id), |
| 462 | component: t.component, |
| 463 | }, |
| 464 | ); |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | fn occurrences_capped( |
| 469 | rule: &ICalendarRecurrenceRule, |
| 470 | m: &Timing, |
| 471 | from_local: NaiveDateTime, |
| 472 | to_local: NaiveDateTime, |
| 473 | budget: &mut usize, |
| 474 | out: &mut Expansion, |
| 475 | ) -> Vec<NaiveDateTime> { |
| 476 | let until = match &rule.until { |
| 477 | Some(u) => match until_local(u, &m.start) { |
| 478 | Some(u) => Some(u), |
| 479 | None => return Vec::new(), |
| 480 | }, |
| 481 | None => None, |
| 482 | }; |
| 483 | // Whole steps keep the period grid, so INTERVAL and BYxxx still line up. |
| 484 | let unit = match rule.freq { |
| 485 | ICalendarFrequency::Weekly => 7 * 86400, |
| 486 | ICalendarFrequency::Daily => 86400, |
| 487 | ICalendarFrequency::Hourly => 3600, |
| 488 | ICalendarFrequency::Minutely => 60, |
| 489 | ICalendarFrequency::Secondly => 1, |
| 490 | _ => 0, |
| 491 | }; |
| 492 | let mut first = m.start.local; |
| 493 | // BYSETPOS picks from a whole period, which a mid-period start would cut. |
| 494 | if unit > 0 && rule.count.is_none() && rule.bysetpos.is_empty() { |
| 495 | let step = unit * i64::from(rule.interval.unwrap_or(1).max(1)); |
| 496 | let behind = (from_local - first).num_seconds(); |
| 497 | if behind > 0 { |
| 498 | first += TimeDelta::seconds(behind / step * step); |
| 499 | } |
| 500 | } |
| 501 | let mut list: Vec<_> = occurrences(rule, first, until, to_local) |
| 502 | .take(*budget + 1) |
| 503 | .collect(); |
| 504 | if list.len() > *budget { |
| 505 | list.pop(); |
| 506 | out.truncated = true; |
| 507 | } |
| 508 | *budget -= list.len(); |
| 509 | // DTSTART is the first of COUNT (RFC 5545, 3.3.10), also when the rule |
| 510 | // skips it. |
| 511 | if let Some(n) = rule.count.filter(|_| until.is_none()).map(|n| n as usize) |
| 512 | && list.first() != Some(&m.start.local) |
| 513 | && list.len() >= n |
| 514 | { |
| 515 | list.truncate(n.saturating_sub(1)); |
| 516 | } |
| 517 | list |
| 518 | } |
| 519 | |
| 520 | fn push(out: &mut Expansion, window: &Range<DateTime<Utc>>, i: Instance) { |
| 521 | let overlaps = if i.start == i.end { |
| 522 | window.contains(&i.start) |
| 523 | } else { |
| 524 | i.start < window.end && i.end > window.start |
| 525 | }; |
| 526 | if overlaps { |
| 527 | out.instances.push(i); |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | /// UNTIL as wall-clock time in the zone of DTSTART. The rule iterates in wall |
| 532 | /// time, so a UTC UNTIL compared as-is cuts the last instance east of UTC. |
| 533 | fn until_local(u: &PartialDateTime, start: &Stamp) -> Option<NaiveDateTime> { |
| 534 | let dt = u.to_date_time()?; |
| 535 | Some(match dt.offset { |
| 536 | Some(o) => { |
| 537 | let utc = dt.date_time - TimeDelta::seconds(o.local_minus_utc().into()); |
| 538 | let local = start.zone.to_local(utc.and_utc()); |
| 539 | match start.date { |
| 540 | // Clients write midnight in UTC or in their own zone. The |
| 541 | // later date is the last day either way. |
| 542 | true => utc.date().max(local.date()).and_hms_opt(23, 59, 59)?, |
| 543 | false => local, |
| 544 | } |
| 545 | } |
| 546 | // A DATE on a DATE-TIME series includes that whole day. |
| 547 | None if u.hour.is_none() && !start.date => dt.date_time.date().and_hms_opt(23, 59, 59)?, |
| 548 | // Floating, or a DATE on an all-day series: already wall time. |
| 549 | None => dt.date_time, |
| 550 | }) |
| 551 | } |
| 552 | |
| 553 | fn day_key(local: NaiveDateTime) -> i64 { |
| 554 | local.date().and_time(NaiveTime::MIN).and_utc().timestamp() |
| 555 | } |
| 556 | |
| 557 | fn nominal(d: &ICalendarDuration) -> Length { |
| 558 | if d.neg { |
| 559 | return Length::Exact(TimeDelta::zero()); |
| 560 | } |
| 561 | Length::Nominal { |
| 562 | days: i64::from(d.weeks) * 7 + i64::from(d.days), |
| 563 | exact: TimeDelta::seconds( |
| 564 | i64::from(d.hours) * 3600 + i64::from(d.minutes) * 60 + i64::from(d.seconds), |
| 565 | ), |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | /// The original start and end of the instance at `rid` of the series in |
| 570 | /// component `master`. |
| 571 | pub(crate) fn original( |
| 572 | cal: &ICalendar, |
| 573 | zones: &Zones, |
| 574 | master: usize, |
| 575 | rid: &Stamp, |
| 576 | ) -> Option<(DateTime<Utc>, DateTime<Utc>)> { |
| 577 | let t = Timing::of(cal, zones, master)?; |
| 578 | let start = t.utc_of(rid); |
| 579 | Some((start, t.end_at(t.start.zone.to_local(start), start))) |
| 580 | } |
| 581 | |
| 582 | pub(crate) fn stamp(zones: &Zones, v: &PartialDateTime, tzid: Option<&str>) -> Option<Stamp> { |
| 583 | let dt = v.to_date_time()?; |
| 584 | let date = v.hour.is_none(); |
| 585 | let zone = match dt.offset { |
| 586 | Some(o) if o.local_minus_utc() == 0 => Zone::Utc, |
| 587 | Some(o) => Zone::Fixed(o.local_minus_utc()), |
| 588 | None if date => zones.floating().clone(), |
| 589 | None => zones.get(tzid), |
| 590 | }; |
| 591 | Some(Stamp { |
| 592 | local: dt.date_time, |
| 593 | zone, |
| 594 | date, |
| 595 | floating: !date && dt.offset.is_none() && tzid.is_none(), |
| 596 | }) |
| 597 | } |
| 598 | |
| 599 | fn prop_stamp(zones: &Zones, c: &ICalendarComponent, prop: &ICalendarProperty) -> Option<Stamp> { |
| 600 | let e = c.property(prop)?; |
| 601 | stamp(zones, e.values.first()?.as_partial_date_time()?, e.tz_id()) |
| 602 | } |
| 603 | |
| 604 | pub(crate) fn rule(v: &ICalendarValue) -> Option<&ICalendarRecurrenceRule> { |
| 605 | match v { |
| 606 | ICalendarValue::RecurrenceRule(r) => Some(r), |
| 607 | _ => None, |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | /// Wall-clock occurrences of `rule` from `start` up to `end`. An invalid or |
| 612 | /// unsupported rule yields none. |
| 613 | pub(crate) fn occurrences( |
| 614 | rule: &ICalendarRecurrenceRule, |
| 615 | start: NaiveDateTime, |
| 616 | until: Option<NaiveDateTime>, |
| 617 | end: NaiveDateTime, |
| 618 | ) -> impl Iterator<Item = NaiveDateTime> { |
| 619 | let wall = |t: NaiveDateTime| rrule::Tz::UTC.from_utc_datetime(&t); |
| 620 | let freq = match rule.freq { |
| 621 | ICalendarFrequency::Yearly => rrule::Frequency::Yearly, |
| 622 | ICalendarFrequency::Monthly => rrule::Frequency::Monthly, |
| 623 | ICalendarFrequency::Weekly => rrule::Frequency::Weekly, |
| 624 | ICalendarFrequency::Daily => rrule::Frequency::Daily, |
| 625 | ICalendarFrequency::Hourly => rrule::Frequency::Hourly, |
| 626 | ICalendarFrequency::Minutely => rrule::Frequency::Minutely, |
| 627 | ICalendarFrequency::Secondly => rrule::Frequency::Secondly, |
| 628 | }; |
| 629 | // Other calendar scales and leap months (RFC 7529) are unsupported. RFC |
| 630 | // 7529 allows treating such a rule as absent. |
| 631 | let months: Option<Vec<chrono::Month>> = rule |
| 632 | .bymonth |
| 633 | .iter() |
| 634 | .map(|m| (!m.is_leap()).then(|| chrono::Month::try_from(m.month()).ok())?) |
| 635 | .collect(); |
| 636 | let valid = months.is_some() |
| 637 | && rule |
| 638 | .rscale |
| 639 | .as_ref() |
| 640 | .is_none_or(|s| *s == CalendarScale::Gregorian) |
| 641 | && rule.skip.is_none_or(|s| s == ICalendarSkip::Omit); |
| 642 | // rrule intersects plain and numbered weekdays, RFC 5545 unites them. |
| 643 | // Numbering every occurrence of the plain ones gives the union. |
| 644 | let mixed = rule.byday.iter().any(|d| d.ordwk.is_some()) |
| 645 | && rule.byday.iter().any(|d| d.ordwk.is_none()); |
| 646 | let max_nth = if rule.freq == ICalendarFrequency::Monthly || !rule.bymonth.is_empty() { |
| 647 | 5 |
| 648 | } else { |
| 649 | 53 |
| 650 | }; |
| 651 | let weekdays = rule |
| 652 | .byday |
| 653 | .iter() |
| 654 | .flat_map(|d| { |
| 655 | let wd = d.weekday.into(); |
| 656 | match d.ordwk { |
| 657 | Some(n) => vec![rrule::NWeekday::Nth(n, wd)], |
| 658 | None if mixed => (1..=max_nth).map(|n| rrule::NWeekday::Nth(n, wd)).collect(), |
| 659 | None => vec![rrule::NWeekday::Every(wd)], |
| 660 | } |
| 661 | }) |
| 662 | .collect(); |
| 663 | let interval = rule.interval.unwrap_or(1).max(1); |
| 664 | // rrule loses the INTERVAL grid when it jumps to the next allowed hour or |
| 665 | // minute and the interval does not divide 60. Filter those limits here. |
| 666 | let (hours, minutes) = match rule.freq { |
| 667 | ICalendarFrequency::Minutely if 60 % interval != 0 => (rule.byhour.clone(), Vec::new()), |
| 668 | ICalendarFrequency::Secondly if 60 % interval != 0 => { |
| 669 | (rule.byhour.clone(), rule.byminute.clone()) |
| 670 | } |
| 671 | _ => (Vec::new(), Vec::new()), |
| 672 | }; |
| 673 | let filtered = !(hours.is_empty() && minutes.is_empty()); |
| 674 | let mut r = rrule::RRule::new(freq) |
| 675 | .interval(interval) |
| 676 | .week_start(rule.wkst.map_or(Weekday::Mon, Into::into)) |
| 677 | .by_set_pos(rule.bysetpos.clone()) |
| 678 | .by_month(&months.unwrap_or_default()) |
| 679 | .by_month_day(rule.bymonthday.clone()) |
| 680 | .by_year_day(rule.byyearday.clone()) |
| 681 | .by_week_no(rule.byweekno.clone()) |
| 682 | .by_weekday(weekdays) |
| 683 | .by_hour(if hours.is_empty() { |
| 684 | rule.byhour.clone() |
| 685 | } else { |
| 686 | Vec::new() |
| 687 | }) |
| 688 | .by_minute(if minutes.is_empty() { |
| 689 | rule.byminute.clone() |
| 690 | } else { |
| 691 | Vec::new() |
| 692 | }) |
| 693 | .by_second(rule.bysecond.clone()); |
| 694 | // COUNT and UNTIL together are invalid. UNTIL is the safer bound. |
| 695 | let count = rule.count.filter(|_| until.is_none()); |
| 696 | if let Some(n) = count.filter(|_| !filtered) { |
| 697 | r = r.count(n); |
| 698 | } |
| 699 | if let Some(u) = until { |
| 700 | r = r.until(wall(u)); |
| 701 | } |
| 702 | r.build(wall(start)) |
| 703 | .ok() |
| 704 | .filter(|_| valid) |
| 705 | // Stops a rule that never matches after 100k periods, not at year 9999. |
| 706 | .map(|set| (&set.limit()).into_iter()) |
| 707 | .into_iter() |
| 708 | .flatten() |
| 709 | .map(|t| t.naive_utc()) |
| 710 | .filter(move |t| { |
| 711 | (hours.is_empty() || hours.contains(&(t.hour() as u8))) |
| 712 | && (minutes.is_empty() || minutes.contains(&(t.minute() as u8))) |
| 713 | }) |
| 714 | .take( |
| 715 | count |
| 716 | .filter(|_| filtered) |
| 717 | .map_or(usize::MAX, |n| n as usize), |
| 718 | ) |
| 719 | .take_while(move |t| *t <= end) |
| 720 | } |
| 721 |