1#[cfg(test)]
3pub mod test;
4
5#[cfg(test)]
6mod test_find_or_infer;
7
8use std::{borrow::Cow, fmt};
9
10use chrono_tz::Tz;
11use tracing::{debug, instrument};
12
13use crate::{
14 cdr, country, from_warning_all, into_caveat_all,
15 json::{self, FieldsAsExt as _, FromJson as _},
16 warning::{self, GatherWarnings as _},
17 IntoCaveat, ParseError, Verdict, Version, Versioned,
18};
19
20#[derive(Debug)]
22pub enum Warning {
23 CantInferTimezoneFromCountry(&'static str),
25
26 ContainsEscapeCodes,
28
29 Country(country::Warning),
31
32 Decode(json::decode::Warning),
34
35 Deserialize(ParseError),
37
38 InvalidLocationType,
40
41 InvalidTimezone,
45
46 InvalidTimezoneType,
48
49 LocationCountryShouldBeAlpha3,
53
54 NoLocationCountry,
56
57 NoLocation,
59
60 Parser(json::Error),
62
63 ShouldBeAnObject,
65
66 V221CdrHasLocationField,
68}
69
70from_warning_all!(
71 country::Warning => Warning::Country,
72 json::decode::Warning => Warning::Decode
73);
74
75impl fmt::Display for Warning {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 match self {
78 Self::CantInferTimezoneFromCountry(country_code) => write!(f, "Unable to infer timezone from the `location`'s `country`: `{country_code}`"),
79 Self::ContainsEscapeCodes => f.write_str("The CDR location contains needless escape codes."),
80 Self::Country(kind) => fmt::Display::fmt(kind, f),
81 Self::Decode(warning) => fmt::Display::fmt(warning, f),
82 Self::Deserialize(err) => fmt::Display::fmt(err, f),
83 Self::InvalidLocationType => f.write_str("The CDR location is not a String."),
84 Self::InvalidTimezone => f.write_str("The CDR location did not contain a valid IANA time-zone."),
85 Self::InvalidTimezoneType => f.write_str("The CDR timezone is not a String."),
86 Self::LocationCountryShouldBeAlpha3 => f.write_str("The `location.country` field should be an alpha-3 country code."),
87 Self::NoLocationCountry => {
88 f.write_str("The CDR's `location` has no `country` element and so the timezone can't be inferred.")
89 },
90 Self::NoLocation => {
91 f.write_str("The CDR has no `location` element and so the timezone can't be found or inferred.")
92 }
93 Self::Parser(err) => fmt::Display::fmt(err, f),
94 Self::ShouldBeAnObject => f.write_str("The CDR should be a JSON object"),
95 Self::V221CdrHasLocationField => f.write_str("the v2.2.1 CDR contains a `location` field but the v2.2.1 spec defines a `cdr_location` field."),
96
97 }
98 }
99}
100
101impl crate::Warning for Warning {
102 fn id(&self) -> warning::Id {
103 match self {
104 Self::CantInferTimezoneFromCountry(_) => {
105 warning::Id::from_static("cant_infer_timezone_from_country")
106 }
107 Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
108 Self::Decode(warning) => warning.id(),
109 Self::Deserialize(err) => warning::Id::from_string(format!("deserialize.{err}")),
110 Self::Country(warning) => warning.id(),
111 Self::InvalidLocationType => warning::Id::from_static("invalid_location_type"),
112 Self::InvalidTimezone => warning::Id::from_static("invalid_timezone"),
113 Self::InvalidTimezoneType => warning::Id::from_static("invalid_timezone_type"),
114 Self::LocationCountryShouldBeAlpha3 => {
115 warning::Id::from_static("location_country_should_be_alpha3")
116 }
117 Self::NoLocationCountry => warning::Id::from_static("no_location_country"),
118 Self::NoLocation => warning::Id::from_static("no_location"),
119 Self::Parser(_err) => warning::Id::from_static("parser_error"),
120 Self::ShouldBeAnObject => warning::Id::from_static("should_be_an_object"),
121 Self::V221CdrHasLocationField => {
122 warning::Id::from_static("v221_cdr_has_location_field")
123 }
124 }
125 }
126}
127
128#[derive(Copy, Clone, Debug)]
130pub enum Source {
131 Found(Tz),
133
134 Inferred(Tz),
136}
137
138into_caveat_all!(Source, Tz);
139
140impl Source {
141 pub fn into_timezone(self) -> Tz {
143 match self {
144 Source::Found(tz) | Source::Inferred(tz) => tz,
145 }
146 }
147}
148
149pub fn find_or_infer(cdr: &cdr::Versioned<'_>) -> Verdict<Source, Warning> {
163 const LOCATION_FIELD_V211: &str = "location";
164 const LOCATION_FIELD_V221: &str = "cdr_location";
165 const TIMEZONE_FIELD: &str = "time_zone";
166 const COUNTRY_FIELD: &str = "country";
167
168 let mut warnings = warning::Set::new();
169
170 let cdr_root = cdr.as_element();
171 let Some(fields) = cdr_root.as_object_fields() else {
172 return warnings.bail(Warning::ShouldBeAnObject, cdr_root);
173 };
174
175 let cdr_fields = fields.as_raw_map();
176
177 let v211_location = cdr_fields.get(LOCATION_FIELD_V211);
178
179 if cdr.version() == Version::V221 && v211_location.is_some() {
184 warnings.insert(Warning::V221CdrHasLocationField, cdr_root);
185 }
186
187 let Some(location_elem) = v211_location.or_else(|| cdr_fields.get(LOCATION_FIELD_V221)) else {
194 return warnings.bail(Warning::NoLocation, cdr_root);
195 };
196
197 let json::Value::Object(fields) = location_elem.as_value() else {
198 return warnings.bail(Warning::InvalidLocationType, cdr_root);
199 };
200
201 let location_fields = fields.as_raw_map();
202
203 debug!("Searching for time-zone in CDR");
204
205 let tz = location_fields
210 .get(TIMEZONE_FIELD)
211 .map(|elem| try_parse_location_timezone(elem).gather_warnings_into(&mut warnings))
212 .transpose();
213
214 let tz = tz
218 .map_err(|err_set| {
219 warnings.deescalate_error(err_set);
220 })
221 .ok()
222 .flatten();
223
224 if let Some(tz) = tz {
225 return Ok(Source::Found(tz).into_caveat(warnings));
226 }
227
228 debug!("No time-zone found in CDR; trying to infer time-zone from country");
229
230 let Some(country_elem) = location_fields.get(COUNTRY_FIELD) else {
232 return warnings.bail(Warning::NoLocationCountry, location_elem);
237 };
238 let tz =
239 infer_timezone_from_location_country(country_elem).gather_warnings_into(&mut warnings)?;
240
241 Ok(Source::Inferred(tz).into_caveat(warnings))
242}
243
244fn try_parse_location_timezone(tz_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
246 let tz = tz_elem.as_value();
247 debug!(tz = %tz, "Raw time-zone found in CDR");
248
249 let mut warnings = warning::Set::new();
250 let Some(tz) = tz.as_raw_str() else {
251 return warnings.bail(Warning::InvalidTimezoneType, tz_elem);
252 };
253
254 let tz = tz
255 .decode_escapes(tz_elem)
256 .gather_warnings_into(&mut warnings);
257
258 if matches!(tz, Cow::Owned(_)) {
259 warnings.insert(Warning::ContainsEscapeCodes, tz_elem);
260 }
261
262 debug!(%tz, "Escaped time-zone found in CDR");
263
264 let Ok(tz) = tz.parse::<Tz>() else {
265 return warnings.bail(Warning::InvalidTimezone, tz_elem);
266 };
267
268 Ok(tz.into_caveat(warnings))
269}
270
271#[instrument(skip_all)]
273fn infer_timezone_from_location_country(country_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
274 let mut warnings = warning::Set::new();
275 let code_set = country::CodeSet::from_json(country_elem)?.gather_warnings_into(&mut warnings);
276
277 let country_code = match code_set {
281 country::CodeSet::Alpha2(code) => {
282 warnings.insert(Warning::LocationCountryShouldBeAlpha3, country_elem);
283 code
284 }
285 country::CodeSet::Alpha3(code) => code,
286 };
287 let Some(tz) = try_detect_timezone(country_code) else {
288 return warnings.bail(
289 Warning::CantInferTimezoneFromCountry(country_code.into_str()),
290 country_elem,
291 );
292 };
293
294 Ok(tz.into_caveat(warnings))
295}
296
297#[instrument]
305fn try_detect_timezone(country_code: country::Code) -> Option<Tz> {
306 let tz = match country_code {
307 country::Code::Ad => Tz::Europe__Andorra,
308 country::Code::Al => Tz::Europe__Tirane,
309 country::Code::At => Tz::Europe__Vienna,
310 country::Code::Ba => Tz::Europe__Sarajevo,
311 country::Code::Be => Tz::Europe__Brussels,
312 country::Code::Bg => Tz::Europe__Sofia,
313 country::Code::By => Tz::Europe__Minsk,
314 country::Code::Ch => Tz::Europe__Zurich,
315 country::Code::Cy => Tz::Europe__Nicosia,
316 country::Code::Cz => Tz::Europe__Prague,
317 country::Code::De => Tz::Europe__Berlin,
318 country::Code::Dk => Tz::Europe__Copenhagen,
319 country::Code::Ee => Tz::Europe__Tallinn,
320 country::Code::Es => Tz::Europe__Madrid,
321 country::Code::Fi => Tz::Europe__Helsinki,
322 country::Code::Fr => Tz::Europe__Paris,
323 country::Code::Gb => Tz::Europe__London,
324 country::Code::Gr => Tz::Europe__Athens,
325 country::Code::Hr => Tz::Europe__Zagreb,
326 country::Code::Hu => Tz::Europe__Budapest,
327 country::Code::Ie => Tz::Europe__Dublin,
328 country::Code::Is => Tz::Iceland,
329 country::Code::It => Tz::Europe__Rome,
330 country::Code::Li => Tz::Europe__Vaduz,
331 country::Code::Lt => Tz::Europe__Vilnius,
332 country::Code::Lu => Tz::Europe__Luxembourg,
333 country::Code::Lv => Tz::Europe__Riga,
334 country::Code::Mc => Tz::Europe__Monaco,
335 country::Code::Md => Tz::Europe__Chisinau,
336 country::Code::Me => Tz::Europe__Podgorica,
337 country::Code::Mk => Tz::Europe__Skopje,
338 country::Code::Mt => Tz::Europe__Malta,
339 country::Code::Nl => Tz::Europe__Amsterdam,
340 country::Code::No => Tz::Europe__Oslo,
341 country::Code::Pl => Tz::Europe__Warsaw,
342 country::Code::Pt => Tz::Europe__Lisbon,
343 country::Code::Ro => Tz::Europe__Bucharest,
344 country::Code::Rs => Tz::Europe__Belgrade,
345 country::Code::Ru => Tz::Europe__Moscow,
346 country::Code::Se => Tz::Europe__Stockholm,
347 country::Code::Si => Tz::Europe__Ljubljana,
348 country::Code::Sk => Tz::Europe__Bratislava,
349 country::Code::Sm => Tz::Europe__San_Marino,
350 country::Code::Tr => Tz::Turkey,
351 country::Code::Ua => Tz::Europe__Kiev,
352 _ => return None,
353 };
354
355 debug!(%tz, "time-zone detected");
356
357 Some(tz)
358}