| 1 | use std::str::FromStr; |
| 2 | |
| 3 | use super::{regex::ParsedDateString, ParseError}; |
| 4 | use crate::{core::Tz, NWeekday}; |
| 5 | use chrono::{NaiveDate, TimeZone, Weekday}; |
| 6 | |
| 7 | /// Attempts to convert a `str` to a `chrono_tz::Tz`. |
| 8 | pub(crate) fn parse_timezone(tz: &str) -> Result<Tz, ParseError> { |
| 9 | chrono_tz::Tz::from_str(tz) |
| 10 | .map_err(|_| ParseError::InvalidTimezone(tz.into())) |
| 11 | .map(Tz::Tz) |
| 12 | } |
| 13 | |
| 14 | /// Convert a datetime string and a timezone to a `chrono::DateTime<Tz>`. |
| 15 | /// If the string specifies a zulu timezone with `Z`, then the timezone |
| 16 | /// argument will be ignored. |
| 17 | pub(crate) fn datestring_to_date( |
| 18 | dt: &str, |
| 19 | tz: Option<Tz>, |
| 20 | property: &str, |
| 21 | ) -> Result<chrono::DateTime<Tz>, ParseError> { |
| 22 | let ParsedDateString { |
| 23 | year, |
| 24 | month, |
| 25 | day, |
| 26 | time, |
| 27 | flags, |
| 28 | } = ParsedDateString::from_ical_datetime(dt).map_err(|_| ParseError::InvalidDateTime { |
| 29 | value: dt.into(), |
| 30 | property: property.into(), |
| 31 | })?; |
| 32 | |
| 33 | // Combine parts to create data time. |
| 34 | let date = |
| 35 | NaiveDate::from_ymd_opt(year, month, day).ok_or_else(|| ParseError::InvalidDateTime { |
| 36 | value: dt.into(), |
| 37 | property: property.into(), |
| 38 | })?; |
| 39 | |
| 40 | // Spec defines this is a date-time OR date |
| 41 | // So the time can will be set to 0:0:0 if only a date is given. |
| 42 | // https://icalendar.org/iCalendar-RFC-5545/3-8-2-4-date-time-start.html |
| 43 | let (hour, min, sec) = if let Some(time) = time { |
| 44 | (time.hour, time.min, time.sec) |
| 45 | } else { |
| 46 | (0, 0, 0) |
| 47 | }; |
| 48 | let datetime = date |
| 49 | .and_hms_opt(hour, min, sec) |
| 50 | .ok_or_else(|| ParseError::InvalidDateTime { |
| 51 | value: dt.into(), |
| 52 | property: property.into(), |
| 53 | })?; |
| 54 | |
| 55 | // Apply timezone appended to the datetime before converting to UTC. |
| 56 | // For more info https://icalendar.org/iCalendar-RFC-5545/3-3-5-date-time.html |
| 57 | let datetime: chrono::DateTime<Tz> = if flags.zulu_timezone_set { |
| 58 | // If a `Z` is present, UTC should be used. |
| 59 | chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(datetime, chrono::Utc) |
| 60 | .with_timezone(&Tz::UTC) |
| 61 | } else { |
| 62 | // If no `Z` is present, local time should be used. |
| 63 | use chrono::offset::LocalResult; |
| 64 | // Get datetime in local time or machine local time. |
| 65 | // So this also takes into account daylight or standard time (summer/winter). |
| 66 | if let Some(tz) = tz { |
| 67 | // Use the timezone specified in the `tz` |
| 68 | match tz.from_local_datetime(&datetime) { |
| 69 | LocalResult::None => Err(ParseError::InvalidDateTimeInLocalTimezone { |
| 70 | value: dt.into(), |
| 71 | property: property.into(), |
| 72 | }), |
| 73 | LocalResult::Single(date) => Ok(date), |
| 74 | LocalResult::Ambiguous(date1, date2) => { |
| 75 | Err(ParseError::DateTimeInLocalTimezoneIsAmbiguous { |
| 76 | value: dt.into(), |
| 77 | property: property.into(), |
| 78 | date1: date1.to_rfc3339(), |
| 79 | date2: date2.to_rfc3339(), |
| 80 | }) |
| 81 | } |
| 82 | }? |
| 83 | } else { |
| 84 | // Use current system timezone |
| 85 | // TODO Add option to always use UTC when this is executed on a server. |
| 86 | let local = Tz::LOCAL; |
| 87 | match local.from_local_datetime(&datetime) { |
| 88 | LocalResult::None => { |
| 89 | return Err(ParseError::InvalidDateTimeInLocalTimezone { |
| 90 | value: dt.into(), |
| 91 | property: property.into(), |
| 92 | }) |
| 93 | } |
| 94 | LocalResult::Single(date) => date, |
| 95 | LocalResult::Ambiguous(date1, date2) => { |
| 96 | return Err(ParseError::DateTimeInLocalTimezoneIsAmbiguous { |
| 97 | value: dt.into(), |
| 98 | property: property.into(), |
| 99 | date1: date1.to_rfc3339(), |
| 100 | date2: date2.to_rfc3339(), |
| 101 | }) |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | }; |
| 106 | |
| 107 | Ok(datetime) |
| 108 | } |
| 109 | |
| 110 | /// Attempts to convert a `str` to a `Weekday`. |
| 111 | pub(crate) fn str_to_weekday(d: &str) -> Result<Weekday, ParseError> { |
| 112 | let day = match &d.to_uppercase()[..] { |
| 113 | "MO" => Weekday::Mon, |
| 114 | "TU" => Weekday::Tue, |
| 115 | "WE" => Weekday::Wed, |
| 116 | "TH" => Weekday::Thu, |
| 117 | "FR" => Weekday::Fri, |
| 118 | "SA" => Weekday::Sat, |
| 119 | "SU" => Weekday::Sun, |
| 120 | _ => return Err(ParseError::InvalidWeekday(d.to_string())), |
| 121 | }; |
| 122 | Ok(day) |
| 123 | } |
| 124 | |
| 125 | /// Parse the "BYWEEKDAY" and "BYDAY" values |
| 126 | /// Example: `SU,MO,TU,WE,TH,FR` or `4MO` or `-1WE` |
| 127 | /// > For example, within a MONTHLY rule, +1MO (or simply 1MO) represents the first Monday |
| 128 | /// > within the month, whereas -1MO represents the last Monday of the month. |
| 129 | pub(crate) fn parse_weekdays(val: &str) -> Result<Vec<NWeekday>, ParseError> { |
| 130 | let mut wdays = vec![]; |
| 131 | // Separate all days |
| 132 | for day in val.split(',') { |
| 133 | let wday = day.parse::<NWeekday>()?; |
| 134 | wdays.push(wday); |
| 135 | } |
| 136 | Ok(wdays) |
| 137 | } |
| 138 | |
| 139 | #[cfg(test)] |
| 140 | mod tests { |
| 141 | use super::*; |
| 142 | |
| 143 | const US_PACIFIC: Tz = Tz::US__Pacific; |
| 144 | |
| 145 | #[test] |
| 146 | fn parses_valid_nweekdays() { |
| 147 | let tests = [ |
| 148 | ("SU", vec![NWeekday::Every(Weekday::Sun)]), |
| 149 | ("-12TU", vec![NWeekday::Nth(-12, Weekday::Tue)]), |
| 150 | ( |
| 151 | "MO,WE", |
| 152 | vec![NWeekday::Every(Weekday::Mon), NWeekday::Every(Weekday::Wed)], |
| 153 | ), |
| 154 | ( |
| 155 | "MO,WE,3TU,-4SA", |
| 156 | vec![ |
| 157 | NWeekday::Every(Weekday::Mon), |
| 158 | NWeekday::Every(Weekday::Wed), |
| 159 | NWeekday::Nth(3, Weekday::Tue), |
| 160 | NWeekday::Nth(-4, Weekday::Sat), |
| 161 | ], |
| 162 | ), |
| 163 | ]; |
| 164 | |
| 165 | for (input, expected_output) in tests { |
| 166 | let output = parse_weekdays(input); |
| 167 | assert_eq!(output, Ok(expected_output)); |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | #[test] |
| 172 | fn rejects_invalid_nweekdays() { |
| 173 | let tests = ["", " ", "fjoasfjapsjop", "MONDAY", "MONDAY, TUESDAY"]; |
| 174 | |
| 175 | for input in tests { |
| 176 | let res = parse_weekdays(input); |
| 177 | assert!(res.is_err()); |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | #[test] |
| 182 | fn parses_valid_weekdays() { |
| 183 | let tests = [ |
| 184 | ("MO", Weekday::Mon), |
| 185 | ("TU", Weekday::Tue), |
| 186 | ("WE", Weekday::Wed), |
| 187 | ("TH", Weekday::Thu), |
| 188 | ("FR", Weekday::Fri), |
| 189 | ("SA", Weekday::Sat), |
| 190 | ("SU", Weekday::Sun), |
| 191 | ]; |
| 192 | |
| 193 | for (input, expected_output) in tests { |
| 194 | let output = str_to_weekday(input); |
| 195 | assert_eq!(output, Ok(expected_output)); |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | #[test] |
| 200 | fn rejects_invalid_weekdays() { |
| 201 | let tests = ["", " ", "fjoasfjapsjop", "MONDAY", "MONDAY, TUESDAY"]; |
| 202 | |
| 203 | for input in tests { |
| 204 | let res = str_to_weekday(input); |
| 205 | assert!(res.is_err()); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | fn parses_valid_datestime_str() { |
| 211 | let tests = [ |
| 212 | ( |
| 213 | "19970902T090000Z", |
| 214 | None, |
| 215 | Tz::UTC.with_ymd_and_hms(1997, 9, 2, 9, 0, 0).unwrap(), |
| 216 | ), |
| 217 | ( |
| 218 | "19970902T090000", |
| 219 | Some(Tz::UTC), |
| 220 | Tz::UTC.with_ymd_and_hms(1997, 9, 2, 9, 0, 0).unwrap(), |
| 221 | ), |
| 222 | ( |
| 223 | "19970902T090000", |
| 224 | Some(US_PACIFIC), |
| 225 | US_PACIFIC.with_ymd_and_hms(1997, 9, 2, 9, 0, 0).unwrap(), |
| 226 | ), |
| 227 | ( |
| 228 | "19970902T090000Z", |
| 229 | Some(US_PACIFIC), |
| 230 | // Timezone is overwritten by the zulu specified in the datetime string |
| 231 | Tz::UTC.with_ymd_and_hms(1997, 9, 2, 9, 0, 0).unwrap(), |
| 232 | ), |
| 233 | ]; |
| 234 | |
| 235 | for (datetime_str, timezone, expected_output) in tests { |
| 236 | let output = datestring_to_date(datetime_str, timezone, "DTSTART"); |
| 237 | assert_eq!(output, Ok(expected_output)); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | #[test] |
| 242 | fn rejects_invalid_datetime_str() { |
| 243 | let tests = [ |
| 244 | ("", None), |
| 245 | ("TZID=America/New_York:19970902T090000", None), |
| 246 | ("19970902T09", None), |
| 247 | ("19970902T09", Some(US_PACIFIC)), |
| 248 | ]; |
| 249 | |
| 250 | for (datetime_str, timezone) in tests { |
| 251 | let res = datestring_to_date(datetime_str, timezone, "DTSTART"); |
| 252 | assert!(res.is_err()); |
| 253 | } |
| 254 | } |
| 255 | } |