| 1 | use crate::core::datetime::datetime_to_ical_format; |
| 2 | use crate::core::utils::collect_with_error; |
| 3 | use crate::parser::{ContentLine, Grammar}; |
| 4 | use crate::{ParseError, RRule, RRuleError, Tz}; |
| 5 | use chrono::DateTime; |
| 6 | #[cfg(feature = "serde")] |
| 7 | use serde_with::{serde_as, DeserializeFromStr, SerializeDisplay}; |
| 8 | use std::fmt::Display; |
| 9 | use std::str::FromStr; |
| 10 | |
| 11 | /// A validated Recurrence Rule that can be used to create an iterator. |
| 12 | #[cfg_attr(feature = "serde", serde_as)] |
| 13 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 14 | #[cfg_attr(feature = "serde", derive(DeserializeFromStr, SerializeDisplay))] |
| 15 | pub struct RRuleSet { |
| 16 | /// List of rrules. |
| 17 | pub(crate) rrule: Vec<RRule>, |
| 18 | /// List of rdates. |
| 19 | pub(crate) rdate: Vec<DateTime<Tz>>, |
| 20 | /// List of exules. |
| 21 | pub(crate) exrule: Vec<RRule>, |
| 22 | /// List of exdates. |
| 23 | pub(crate) exdate: Vec<DateTime<Tz>>, |
| 24 | /// The start datetime of the recurring event. |
| 25 | pub(crate) dt_start: DateTime<Tz>, |
| 26 | /// If set, all returned recurrences must be before this date. |
| 27 | pub(crate) before: Option<DateTime<Tz>>, |
| 28 | /// If set, all returned recurrences must be after this date. |
| 29 | pub(crate) after: Option<DateTime<Tz>>, |
| 30 | /// If validation limits are enabled |
| 31 | pub(crate) limited: bool, |
| 32 | } |
| 33 | |
| 34 | /// The return result of `RRuleSet::all`. |
| 35 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 36 | pub struct RRuleResult { |
| 37 | /// List of recurrences. |
| 38 | pub dates: Vec<DateTime<Tz>>, |
| 39 | /// It is being true if the list of dates is limited. |
| 40 | /// To indicate that it can potentially contain more dates. |
| 41 | pub limited: bool, |
| 42 | } |
| 43 | |
| 44 | impl RRuleSet { |
| 45 | /// Creates an empty [`RRuleSet`], starting from `ds_start`. |
| 46 | #[must_use] |
| 47 | pub fn new(dt_start: DateTime<Tz>) -> Self { |
| 48 | Self { |
| 49 | dt_start, |
| 50 | rrule: vec![], |
| 51 | rdate: vec![], |
| 52 | exrule: vec![], |
| 53 | exdate: vec![], |
| 54 | before: None, |
| 55 | after: None, |
| 56 | limited: false, |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /// Enable validation limits. |
| 61 | /// |
| 62 | /// This is only needed if you are going to use the Iterator api directly. |
| 63 | #[must_use] |
| 64 | pub fn limit(mut self) -> Self { |
| 65 | self.limited = true; |
| 66 | self |
| 67 | } |
| 68 | |
| 69 | /// Only return recurrences that comes before this `DateTime`. |
| 70 | /// |
| 71 | /// This value will not be used if you use the `Iterator` API directly. |
| 72 | #[must_use] |
| 73 | pub fn before(mut self, dt: DateTime<Tz>) -> Self { |
| 74 | self.before = Some(dt); |
| 75 | self |
| 76 | } |
| 77 | |
| 78 | /// Only return recurrences that comes after this `DateTime`. |
| 79 | /// |
| 80 | /// This value will not be used if you use the `Iterator` API directly. |
| 81 | #[must_use] |
| 82 | pub fn after(mut self, dt: DateTime<Tz>) -> Self { |
| 83 | self.after = Some(dt); |
| 84 | self |
| 85 | } |
| 86 | |
| 87 | /// Adds a new rrule to the set. |
| 88 | #[must_use] |
| 89 | pub fn rrule(mut self, rrule: RRule) -> Self { |
| 90 | self.rrule.push(rrule); |
| 91 | self |
| 92 | } |
| 93 | |
| 94 | /// Adds a new exrule to the set. |
| 95 | #[must_use] |
| 96 | #[cfg(feature = "exrule")] |
| 97 | pub fn exrule(mut self, rrule: RRule) -> Self { |
| 98 | self.exrule.push(rrule); |
| 99 | self |
| 100 | } |
| 101 | |
| 102 | /// Adds a new rdate to the set. |
| 103 | #[must_use] |
| 104 | pub fn rdate(mut self, rdate: DateTime<Tz>) -> Self { |
| 105 | self.rdate.push(rdate); |
| 106 | self |
| 107 | } |
| 108 | |
| 109 | /// Adds a new exdate to the set. |
| 110 | #[must_use] |
| 111 | pub fn exdate(mut self, exdate: DateTime<Tz>) -> Self { |
| 112 | self.exdate.push(exdate); |
| 113 | self |
| 114 | } |
| 115 | |
| 116 | /// Sets the rrules of the set. |
| 117 | #[must_use] |
| 118 | pub fn set_rrules(mut self, rrules: Vec<RRule>) -> Self { |
| 119 | self.rrule = rrules; |
| 120 | self |
| 121 | } |
| 122 | |
| 123 | /// Sets the exrules of the set. |
| 124 | #[must_use] |
| 125 | #[cfg(feature = "exrule")] |
| 126 | pub fn set_exrules(mut self, exrules: Vec<RRule>) -> Self { |
| 127 | self.exrule = exrules; |
| 128 | self |
| 129 | } |
| 130 | |
| 131 | /// Sets the rdates of the set. |
| 132 | #[must_use] |
| 133 | pub fn set_rdates(mut self, rdates: Vec<DateTime<Tz>>) -> Self { |
| 134 | self.rdate = rdates; |
| 135 | self |
| 136 | } |
| 137 | |
| 138 | /// Set the exdates of the set. |
| 139 | #[must_use] |
| 140 | pub fn set_exdates(mut self, exdates: Vec<DateTime<Tz>>) -> Self { |
| 141 | self.exdate = exdates; |
| 142 | self |
| 143 | } |
| 144 | |
| 145 | /// Returns the rrules of the set. |
| 146 | #[must_use] |
| 147 | pub fn get_rrule(&self) -> &Vec<RRule> { |
| 148 | &self.rrule |
| 149 | } |
| 150 | |
| 151 | /// Returns the exrules of the set. |
| 152 | #[must_use] |
| 153 | pub fn get_exrule(&self) -> &Vec<RRule> { |
| 154 | &self.exrule |
| 155 | } |
| 156 | |
| 157 | /// Returns the rdates of the set. |
| 158 | #[must_use] |
| 159 | pub fn get_rdate(&self) -> &Vec<DateTime<Tz>> { |
| 160 | &self.rdate |
| 161 | } |
| 162 | |
| 163 | /// Returns the exdates of the set. |
| 164 | #[must_use] |
| 165 | pub fn get_exdate(&self) -> &Vec<DateTime<Tz>> { |
| 166 | &self.exdate |
| 167 | } |
| 168 | |
| 169 | /// Returns the start datetime of the recurring event. |
| 170 | #[must_use] |
| 171 | pub fn get_dt_start(&self) -> &DateTime<Tz> { |
| 172 | &self.dt_start |
| 173 | } |
| 174 | |
| 175 | /// Returns all the recurrences of the rrule. |
| 176 | /// |
| 177 | /// Limit must be set in order to prevent infinite loops. |
| 178 | /// The max limit is `65535`. If you need more please use `into_iter` directly. |
| 179 | /// |
| 180 | /// # Usage |
| 181 | /// |
| 182 | /// ``` |
| 183 | /// use rrule::RRuleSet; |
| 184 | /// |
| 185 | /// let rrule_set: RRuleSet = "DTSTART:20210101T090000Z\nRRULE:FREQ=DAILY".parse().unwrap(); |
| 186 | /// |
| 187 | /// // Limit the results to 2 recurrences |
| 188 | /// let result = rrule_set.all(2); |
| 189 | /// assert_eq!(result.dates.len(), 2); |
| 190 | /// assert_eq!(result.limited, true); |
| 191 | /// ``` |
| 192 | #[must_use] |
| 193 | pub fn all(mut self, limit: u16) -> RRuleResult { |
| 194 | self.limited = true; |
| 195 | collect_with_error( |
| 196 | self.into_iter(), |
| 197 | &self.after, |
| 198 | &self.before, |
| 199 | true, |
| 200 | Some(limit), |
| 201 | ) |
| 202 | } |
| 203 | |
| 204 | /// Returns all the recurrences of the rrule. |
| 205 | /// |
| 206 | /// # Note |
| 207 | /// |
| 208 | /// This method does not enforce any validation limits and might lead to |
| 209 | /// very long iteration times. Please read the `SECURITY.md` for more information. |
| 210 | #[must_use] |
| 211 | pub fn all_unchecked(self) -> Vec<DateTime<Tz>> { |
| 212 | collect_with_error(self.into_iter(), &self.after, &self.before, true, None).dates |
| 213 | } |
| 214 | |
| 215 | fn set_from_content_lines(self, content_lines: Vec<ContentLine>) -> Result<Self, RRuleError> { |
| 216 | let dt_start = self.dt_start; |
| 217 | |
| 218 | content_lines.into_iter().try_fold( |
| 219 | self, |
| 220 | |rrule_set, content_line| match content_line { |
| 221 | ContentLine::RRule(rrule) => rrule |
| 222 | .validate(dt_start) |
| 223 | .map(|rrule| rrule_set.rrule(rrule)), |
| 224 | #[allow(unused_variables)] |
| 225 | ContentLine::ExRule(exrule) => { |
| 226 | #[cfg(feature = "exrule")] |
| 227 | { |
| 228 | exrule |
| 229 | .validate(dt_start) |
| 230 | .map(|exrule| rrule_set.exrule(exrule)) |
| 231 | } |
| 232 | #[cfg(not(feature = "exrule"))] |
| 233 | { |
| 234 | log::warn!("Found EXRULE in input, but it will be ignored since the `exrule` feature is not enabled."); |
| 235 | Ok(rrule_set) |
| 236 | } |
| 237 | } |
| 238 | ContentLine::ExDate(exdates) => { |
| 239 | Ok(exdates.into_iter().fold(rrule_set, Self::exdate)) |
| 240 | } |
| 241 | ContentLine::RDate(rdates) => { |
| 242 | Ok(rdates.into_iter().fold(rrule_set, Self::rdate)) |
| 243 | } |
| 244 | }, |
| 245 | ) |
| 246 | } |
| 247 | |
| 248 | /// Set the [`RRuleSet`] properties from a string. If a DTSTART is found, it will be used as the start datetime. |
| 249 | pub fn set_from_string(mut self, s: &str) -> Result<Self, RRuleError> { |
| 250 | let Grammar { |
| 251 | start, |
| 252 | content_lines, |
| 253 | } = Grammar::from_str(s)?; |
| 254 | |
| 255 | if let Some(dtstart) = start { |
| 256 | self.dt_start = dtstart.datetime; |
| 257 | } |
| 258 | |
| 259 | self.set_from_content_lines(content_lines) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | impl FromStr for RRuleSet { |
| 264 | type Err = RRuleError; |
| 265 | |
| 266 | /// Creates an [`RRuleSet`] from a string if input is valid. |
| 267 | /// |
| 268 | /// # Errors |
| 269 | /// |
| 270 | /// Returns [`RRuleError`], if iCalendar string contains invalid parts. |
| 271 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 272 | let Grammar { |
| 273 | start, |
| 274 | content_lines, |
| 275 | } = Grammar::from_str(s)?; |
| 276 | |
| 277 | let start = start.ok_or(ParseError::MissingStartDate)?; |
| 278 | |
| 279 | Self::new(start.datetime).set_from_content_lines(content_lines) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | impl Display for RRuleSet { |
| 284 | /// Prints a valid set of iCalendar properties which can be used to create a new [`RRuleSet`] later. |
| 285 | /// You may use the generated string to create a new iCalendar component, like VEVENT. |
| 286 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 287 | let start_datetime = format!("DTSTART{}", datetime_to_ical_format(&self.dt_start)); |
| 288 | |
| 289 | let mut rrules = self |
| 290 | .rrule |
| 291 | .iter() |
| 292 | .map(|rrule| format!("RRULE:{rrule}")) |
| 293 | .collect::<Vec<_>>() |
| 294 | .join("\n"); |
| 295 | if !rrules.is_empty() { |
| 296 | rrules = format!("\n{rrules}"); |
| 297 | } |
| 298 | |
| 299 | let mut rdates = self |
| 300 | .rdate |
| 301 | .iter() |
| 302 | .map(|dt| { |
| 303 | let maybe_zulu = if dt.timezone().is_local() { "" } else { "Z" }; |
| 304 | |
| 305 | format!("{}{}", dt.format("%Y%m%dT%H%M%S"), maybe_zulu) |
| 306 | }) |
| 307 | .collect::<Vec<_>>() |
| 308 | .join(","); |
| 309 | if !rdates.is_empty() { |
| 310 | // TODO: check if original VALUE prop was DATE or PERIOD |
| 311 | rdates = format!("\nRDATE;VALUE=DATE-TIME:{rdates}"); |
| 312 | } |
| 313 | |
| 314 | let mut exrules = self |
| 315 | .exrule |
| 316 | .iter() |
| 317 | .map(|exrule| format!("EXRULE:{exrule}")) |
| 318 | .collect::<Vec<_>>() |
| 319 | .join("\n"); |
| 320 | if !exrules.is_empty() { |
| 321 | exrules = format!("\n{exrules}"); |
| 322 | } |
| 323 | |
| 324 | let mut exdates = self |
| 325 | .exdate |
| 326 | .iter() |
| 327 | .map(|dt| { |
| 328 | let maybe_zulu = if dt.timezone().is_local() { "" } else { "Z" }; |
| 329 | |
| 330 | format!("{}{}", dt.format("%Y%m%dT%H%M%S"), maybe_zulu) |
| 331 | }) |
| 332 | .collect::<Vec<_>>() |
| 333 | .join(","); |
| 334 | if !exdates.is_empty() { |
| 335 | // TODO: check if original VALUE prop was DATE or PERIOD |
| 336 | exdates = format!("\nEXDATE;VALUE=DATE-TIME:{exdates}"); |
| 337 | } |
| 338 | |
| 339 | write!(f, "{start_datetime}{rrules}{rdates}{exrules}{exdates}") |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | #[cfg(feature = "exrule")] |
| 344 | #[cfg(test)] |
| 345 | mod tests { |
| 346 | use std::str::FromStr; |
| 347 | |
| 348 | use chrono::{Month, TimeZone}; |
| 349 | |
| 350 | use crate::{Frequency, RRule, RRuleSet, Tz}; |
| 351 | |
| 352 | #[test] |
| 353 | fn rruleset_string_roundtrip() { |
| 354 | let rruleset_str = "DTSTART:20120201T093000Z\nRRULE:FREQ=DAILY;COUNT=3;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nRDATE;VALUE=DATE-TIME:19970101T000000Z,19970120T000000Z\nEXRULE:FREQ=YEARLY;COUNT=8;BYMONTH=6,7;BYMONTHDAY=1;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nEXDATE;VALUE=DATE-TIME:19970121T000000Z"; |
| 355 | let rruleset = RRuleSet::from_str(rruleset_str).unwrap(); |
| 356 | |
| 357 | // Check start date |
| 358 | let dt_start = Tz::UTC.with_ymd_and_hms(2012, 2, 1, 9, 30, 0).unwrap(); |
| 359 | assert_eq!(rruleset.dt_start, dt_start); |
| 360 | |
| 361 | // Check rrule |
| 362 | assert_eq!( |
| 363 | rruleset.rrule, |
| 364 | vec![RRule::new(Frequency::Daily) |
| 365 | .count(3) |
| 366 | .validate(dt_start) |
| 367 | .unwrap()] |
| 368 | ); |
| 369 | |
| 370 | // Check rdate |
| 371 | assert_eq!( |
| 372 | rruleset.rdate, |
| 373 | vec![ |
| 374 | Tz::UTC.with_ymd_and_hms(1997, 1, 1, 0, 0, 0).unwrap(), |
| 375 | Tz::UTC.with_ymd_and_hms(1997, 1, 20, 0, 0, 0).unwrap() |
| 376 | ] |
| 377 | ); |
| 378 | |
| 379 | // Check exrule |
| 380 | assert_eq!( |
| 381 | rruleset.exrule, |
| 382 | vec![RRule::new(Frequency::Yearly) |
| 383 | .count(8) |
| 384 | .by_month(&[Month::June, Month::July]) |
| 385 | .validate(dt_start) |
| 386 | .unwrap()] |
| 387 | ); |
| 388 | |
| 389 | // Check exdate |
| 390 | assert_eq!( |
| 391 | rruleset.exdate, |
| 392 | vec![Tz::UTC.with_ymd_and_hms(1997, 1, 21, 0, 0, 0).unwrap()] |
| 393 | ); |
| 394 | |
| 395 | // Serialize to string again |
| 396 | assert_eq!(rruleset.to_string(), rruleset_str); |
| 397 | } |
| 398 | |
| 399 | #[test] |
| 400 | fn respect_local_timezone_in_exdates_rdates() { |
| 401 | let rruleset_str = "DTSTART:20120201T093000Z\nRRULE:FREQ=DAILY;COUNT=3;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nRDATE;VALUE=DATE-TIME:19970101T000000,19970120T000000\nEXRULE:FREQ=YEARLY;COUNT=8;BYMONTH=6,7;BYMONTHDAY=1;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nEXDATE;VALUE=DATE-TIME:19970121T000000"; |
| 402 | let rruleset = RRuleSet::from_str(rruleset_str).unwrap(); |
| 403 | |
| 404 | // Serialize to string again |
| 405 | assert_eq!(rruleset.to_string(), rruleset_str); |
| 406 | } |
| 407 | |
| 408 | #[test] |
| 409 | fn respect_utc_timezone_in_exdates_rdates() { |
| 410 | let rruleset_str = "DTSTART:20120201T093000Z\nRRULE:FREQ=DAILY;COUNT=3;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nRDATE;VALUE=DATE-TIME:19970101T000000Z,19970120T000000Z\nEXRULE:FREQ=YEARLY;COUNT=8;BYMONTH=6,7;BYMONTHDAY=1;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nEXDATE;VALUE=DATE-TIME:19970121T000000Z"; |
| 411 | let rruleset = RRuleSet::from_str(rruleset_str).unwrap(); |
| 412 | |
| 413 | // Serialize to string again |
| 414 | assert_eq!(rruleset.to_string(), rruleset_str); |
| 415 | } |
| 416 | } |