capsule_core/exif/
timezone.rs1use jiff::tz::{Offset, TimeZone};
2
3use crate::domain::CaptureTzSource;
4use crate::exif::ExifExtract;
5
6#[derive(Debug, Clone, PartialEq)]
7pub struct TimezoneResolution {
8 pub capture_timestamp: Option<i64>, pub capture_utc: Option<i64>, pub capture_tz: Option<String>, pub capture_tz_source: Option<CaptureTzSource>,
12 pub tz_db_version: Option<String>,
13}
14
15pub fn resolve_timezone(extract: &ExifExtract) -> TimezoneResolution {
16 let capture_timestamp = extract
17 .date_time_original
18 .and_then(|dt| dt.to_zoned_datetime(TimeZone::UTC).ok())
19 .map(|z| z.timestamp().as_second());
20
21 if let (Some(dt), Some(offset_str)) =
23 (extract.date_time_original, &extract.offset_time_original)
24 && let Some(offset) = parse_offset(offset_str)
25 {
26 let local = dt.to_zoned_datetime(TimeZone::fixed(offset)).ok();
29 let capture_utc = local.map(|t| t.timestamp().as_second());
30 return TimezoneResolution {
31 capture_timestamp,
32 capture_utc,
33 capture_tz: Some(offset_str.clone()),
34 capture_tz_source: Some(CaptureTzSource::OffsetExif),
35 tz_db_version: None,
36 };
37 }
38
39 if let (Some(lat), Some(lon)) = (extract.gps_lat, extract.gps_lon)
41 && let Some((tz_name, tz_db_ver)) = lookup_timezone(lat, lon)
42 {
43 return TimezoneResolution {
44 capture_timestamp,
45 capture_utc: None, capture_tz: Some(tz_name),
47 capture_tz_source: Some(CaptureTzSource::GpsLookup),
48 tz_db_version: Some(tz_db_ver),
49 };
50 }
51
52 TimezoneResolution {
54 capture_timestamp,
55 capture_utc: None,
56 capture_tz: None,
57 capture_tz_source: Some(CaptureTzSource::Floating),
58 tz_db_version: None,
59 }
60}
61
62fn parse_offset(s: &str) -> Option<Offset> {
63 let s = s.trim();
65 if s.len() < 6 {
66 return None;
67 }
68 let sign: i32 = if s.starts_with('-') { -1 } else { 1 };
69 let parts: Vec<&str> = s[1..].split(':').collect();
70 if parts.len() != 2 {
71 return None;
72 }
73 let hours: i32 = parts[0].parse().ok()?;
74 let minutes: i32 = parts[1].parse().ok()?;
75 let total_secs = sign * (hours * 3600 + minutes * 60);
76 Offset::from_seconds(total_secs).ok()
77}
78
79fn lookup_timezone(lat: f64, lon: f64) -> Option<(String, String)> {
80 use tzf_rs::DefaultFinder;
81 let finder = DefaultFinder::new();
82 let tz_name = finder.get_tz_name(lon, lat); if tz_name.is_empty() {
84 return None;
85 }
86 let tz_db_version = finder.data_version().to_string();
87 Some((tz_name.to_string(), tz_db_version))
88}
89
90#[cfg(test)]
91mod tests;