media_analyzer 0.8.0

Extract file-based information from photo and video files.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Core logic for determining the best time representation based on extracted components.

use super::error::TimeError;
use super::extraction::{ExtractedTimeComponents, extract_time_components};
use crate::GpsInfo;
use crate::time::structs::{
    CONFIDENCE_HIGH, CONFIDENCE_LOW, CONFIDENCE_MEDIUM, SourceDetails, TimeInfo, TimeZoneInfo,
};
use chrono::{FixedOffset, LocalResult, Offset, TimeZone, Utc};
use chrono_tz::Tz;
use serde_json::Value;
use std::str::FromStr;
use tzf_rs::DefaultFinder;

// --- Constants specific to the logic ---
const MAX_NAIVE_GPS_DIFF_SECONDS: i64 = 10;
const MAX_SANE_TZ_OFFSET_SECONDS: i32 = 15 * 3600;

// --- Global Timezone Finder ---
static FINDER: std::sync::LazyLock<DefaultFinder> = std::sync::LazyLock::new(DefaultFinder::new);

pub fn get_time_info(exif_info: &Value, gps_info: Option<&GpsInfo>) -> Result<TimeInfo, TimeError> {
    let components = extract_time_components(exif_info);
    let time_result = apply_priority_logic(components, gps_info);
    time_result.ok_or(TimeError::Extraction)
}

/// Applies the priority logic to extracted components and constructs the final `TimeInfo`.
fn apply_priority_logic(
    components: ExtractedTimeComponents,
    gps_info: Option<&GpsInfo>,
) -> Option<TimeInfo> {
    let ExtractedTimeComponents {
        best_local,
        potential_utc,
        potential_explicit_offset,
        potential_file_dt,
        is_video,
    } = components;

    // --- Priority 1: Confirmed UTC (Highest confidence) ---
    if let (Some((local_dt, naive_source)), Some((gps_utc_dt, utc_source)), Some(gps)) =
        (&best_local, &potential_utc, gps_info)
        && let Ok(tz) = Tz::from_str(FINDER.get_tz_name(gps.longitude, gps.latitude))
        && let LocalResult::Single(zoned_dt) | LocalResult::Ambiguous(zoned_dt, _) =
            tz.from_local_datetime(local_dt)
    {
        let calculated_utc_from_naive = zoned_dt.with_timezone(&Utc);
        let diff = gps_utc_dt.signed_duration_since(calculated_utc_from_naive);

        // Video has difficult local dt extraction, so the `diff` can be wrong.
        // The UTC is more trustable for video so we ignore the `diff` possibly being high in this case
        if is_video || diff.num_seconds().abs() <= MAX_NAIVE_GPS_DIFF_SECONDS {
            let offset_secs = zoned_dt.offset().fix().local_minus_utc();
            let tz_info = TimeZoneInfo {
                name: tz.name().to_string(),
                offset_seconds: offset_secs,
                source: format!("{utc_source} confirmed by {naive_source} @ GPS location"),
            };
            // Discard `local_dt` if it comes from video
            let datetime_local = if is_video {
                gps_utc_dt.with_timezone(&tz).naive_local()
            } else {
                *local_dt
            };
            return Some(TimeInfo {
                datetime_utc: Some(*gps_utc_dt),
                datetime_local,
                timezone: Some(tz_info),
                source_details: SourceDetails {
                    time_source: naive_source.clone(),
                    confidence: CONFIDENCE_HIGH.to_string(),
                },
            });
        }
    }

    if let Some((local_dt, naive_source)) = best_local {
        // --- Priority 2: Zoned Time (Naive + GPS Location) ---
        if let Some(gps) = gps_info
            && let Ok(tz) = Tz::from_str(FINDER.get_tz_name(gps.longitude, gps.latitude))
            && let LocalResult::Single(zoned_dt) | LocalResult::Ambiguous(zoned_dt, _) =
                tz.from_local_datetime(&local_dt)
        {
            return Some(TimeInfo {
                datetime_utc: Some(zoned_dt.with_timezone(&Utc)),
                datetime_local: local_dt,
                timezone: Some(TimeZoneInfo {
                    name: tz.name().to_string(),
                    offset_seconds: zoned_dt.offset().fix().local_minus_utc(),
                    source: "IANA from GPS".to_string(),
                }),
                source_details: SourceDetails {
                    time_source: naive_source,
                    confidence: CONFIDENCE_HIGH.to_string(),
                },
            });
        }

        // --- Priority 3: Fixed Offset Time (Naive + Explicit Offset Tag) ---
        if let Some((offset_secs, offset_str, offset_source)) = potential_explicit_offset
            && let Some(offset) = FixedOffset::east_opt(offset_secs)
            && let LocalResult::Single(dt_with_offset) | LocalResult::Ambiguous(dt_with_offset, _) =
                offset.from_local_datetime(&local_dt)
        {
            return Some(TimeInfo {
                datetime_utc: Some(dt_with_offset.with_timezone(&Utc)),
                datetime_local: local_dt,
                timezone: Some(TimeZoneInfo {
                    name: offset_str,
                    offset_seconds: offset_secs,
                    source: offset_source,
                }),
                source_details: SourceDetails {
                    time_source: naive_source,
                    confidence: CONFIDENCE_HIGH.to_string(),
                },
            });
        }

        // --- Priority 4: Hybrid (Local Time + Unconfirmed UTC Time) ---
        if let Some((utc_dt, utc_source)) = potential_utc {
            // Calculate offset in seconds between local and UTC datetimes
            let offset_seconds = (local_dt - utc_dt.naive_utc()).num_seconds() as i32;

            // Format offset as ±HH:MM
            let sign = if offset_seconds >= 0 { '+' } else { '-' };
            let abs_offset = offset_seconds.abs();

            if abs_offset <= MAX_SANE_TZ_OFFSET_SECONDS {
                let hours = abs_offset / 3600;
                let minutes = (abs_offset % 3600) / 60;
                let tz_name = format!("{sign}{hours:02}:{minutes:02}");

                return Some(TimeInfo {
                    datetime_utc: Some(utc_dt),
                    datetime_local: local_dt,
                    timezone: Some(TimeZoneInfo {
                        name: tz_name,
                        offset_seconds,
                        source: utc_source.clone(),
                    }),
                    source_details: SourceDetails {
                        time_source: format!("{naive_source} + {utc_source}"),
                        confidence: CONFIDENCE_MEDIUM.to_string(),
                    },
                });
            }
        }

        // --- Priority 5: Naive With Guessed Offset ---
        if let Some((file_dt, file_source)) = potential_file_dt {
            let guessed_offset = file_dt.offset().fix();
            let iso_utc = guessed_offset
                .from_local_datetime(&local_dt)
                .single()
                .map(|dt| dt.with_timezone(&Utc));

            return Some(TimeInfo {
                datetime_utc: iso_utc,
                datetime_local: local_dt,
                timezone: Some(TimeZoneInfo {
                    name: guessed_offset.to_string(),
                    offset_seconds: guessed_offset.local_minus_utc(),
                    source: format!("Guessed from {file_source}"),
                }),
                source_details: SourceDetails {
                    time_source: naive_source,
                    confidence: CONFIDENCE_MEDIUM.to_string(),
                },
            });
        }

        // we are left with just the naive time.
        return Some(TimeInfo {
            datetime_utc: None,
            datetime_local: local_dt,
            timezone: None,
            source_details: SourceDetails {
                time_source: naive_source,
                confidence: CONFIDENCE_LOW.to_string(),
            },
        });
    }

    // --- Fallback Path: No authoritative naive time was found anywhere. ---

    // --- Priority 7: Accurate UTC Only, no naive time available somehow. ---
    if let Some((utc_dt, utc_source)) = potential_utc {
        // No tz available
        return Some(TimeInfo {
            datetime_utc: Some(utc_dt),
            datetime_local: utc_dt.naive_utc(),
            timezone: None,
            source_details: SourceDetails {
                time_source: utc_source,
                confidence: CONFIDENCE_HIGH.to_string(),
            },
        });
    }

    // --- Priority 8: File Metadata Time Only ---
    if let Some((file_dt, file_source)) = potential_file_dt {
        let offset = file_dt.offset().fix();
        return Some(TimeInfo {
            datetime_utc: Some(file_dt.with_timezone(&Utc)),
            datetime_local: file_dt.naive_local(),
            timezone: Some(TimeZoneInfo {
                name: offset.to_string(),
                offset_seconds: offset.local_minus_utc(),
                source: file_source.clone(),
            }),
            source_details: SourceDetails {
                time_source: file_source,
                confidence: CONFIDENCE_LOW.to_string(),
            },
        });
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::features::gps::get_gps_info;
    use crate::{LocationName, MediaAnalyzerError};
    use chrono::NaiveDate;
    use exiftool::ExifTool;
    use reverse_geocoder::ReverseGeocoder;
    use serde_json::from_str;
    use std::path::Path;

    // Mock GpsInfo struct as it's defined in another part of the crate.
    #[derive(Debug, Clone, Copy)]
    pub struct MockGpsInfo {
        pub latitude: f64,
        pub longitude: f64,
    }
    // Allow tests to use the mock struct where the real GpsInfo is expected.
    impl From<MockGpsInfo> for GpsInfo {
        fn from(val: MockGpsInfo) -> Self {
            Self {
                latitude: val.latitude,
                longitude: val.longitude,
                altitude: None,
                image_direction: None,
                image_direction_ref: None,
                location: LocationName {
                    latitude: 0.0,
                    name: String::new(),
                    admin1: String::new(),
                    admin2: String::new(),
                    country_code: String::new(),
                    longitude: 0.,
                    country_name: None,
                },
            }
        }
    }

    fn get_full_exif() -> Value {
        from_str(r#"{
            "Time": {
                "FileModifyDate": "2025:02:26 19:14:06+01:00",
                "ModifyDate": "2017:11:06 11:03:20",
                "GPSDateStamp": "2017:11:06",
                "GPSTimeStamp": "10:03:19",
                "CreateDate": "2017:11:06 11:03:20",
                "SubSecTimeOriginal": 123953,
                "DateTimeOriginal": "2017:11:06 11:03:20",
                "SubSecDateTimeOriginal": "2017:11:06 11:03:20.123953",
                "GPSDateTime": "2017:11:06 10:03:19Z"
            },
            "Location": { "GPSLatitude": "53 deg 12' 45.68\" N", "GPSLongitude": "6 deg 33' 46.93\" E" }
            }"#).unwrap()
    }

    fn get_basic_exif() -> Value {
        from_str(
            r#"{
        "Time": {
        "FileModifyDate": "2011:01:01 15:26:40+01:00",
        "ModifyDate": "2011:01:01 16:26:30",
        "DateTimeOriginal": "                    ",
        "CreateDate": "                    "
        }
        }"#,
        )
        .unwrap()
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_difficult_tz_offset() -> Result<(), MediaAnalyzerError> {
        // Arrange
        let image = Path::new("assets/tz-offset-bug/IMG_20170904_101507.jpg");
        let et = ExifTool::new()?;
        let exif = et.json(image, &["-g2"])?;
        let geocoder = ReverseGeocoder::new();
        let numeric_exif = et.json(image, &["-n"])?;
        let gps_info = get_gps_info(&geocoder, &numeric_exif);

        // Act
        let time_info = get_time_info(&exif, gps_info.as_ref())?;

        // Assert
        println!("{time_info:?}");

        Ok(())
    }

    #[test]
    fn test_priority1_confirmed_utc_from_cluster_jpg() {
        let exif = get_full_exif();
        // GPS Coordinates for Groningen, NL
        let gps = MockGpsInfo {
            latitude: 53.212_688,
            longitude: 6.563_036,
        };

        let info = get_time_info(&exif, Some(&gps.into())).unwrap();

        // UTC time should come directly from GPSDateTime because it's confirmed.
        assert_eq!(
            info.datetime_utc.unwrap().to_rfc3339(),
            "2017-11-06T10:03:19+00:00"
        );
        // Local time is the high-precision naive time from SubSecDateTimeOriginal.
        assert_eq!(
            info.datetime_local,
            NaiveDate::from_ymd_opt(2017, 11, 6)
                .unwrap()
                .and_hms_micro_opt(11, 3, 20, 123_953)
                .unwrap()
        );
        // Timezone should be identified from GPS and used for confirmation.
        assert_eq!(info.timezone.as_ref().unwrap().name, "Europe/Amsterdam");
        assert_eq!(info.timezone.as_ref().unwrap().offset_seconds, 3600);
        // Confidence should be high.
        assert_eq!(info.source_details.confidence, CONFIDENCE_HIGH);
        assert!(info.timezone.unwrap().source.contains("confirmed by"));
    }

    #[test]
    fn test_priority5_guessed_offset_from_pict0017() {
        let exif = get_basic_exif();
        // No GPS, no fallback timezone.
        let info = get_time_info(&exif, None).unwrap();

        // `best_local` comes from `ModifyDate` since `DateTimeOriginal` is blank.
        assert_eq!(
            info.datetime_local,
            NaiveDate::from_ymd_opt(2011, 1, 1)
                .unwrap()
                .and_hms_opt(16, 26, 30)
                .unwrap()
        );
        // The offset is "guessed" from the `FileModifyDate`.
        assert_eq!(info.timezone.as_ref().unwrap().name, "+01:00");
        assert_eq!(info.timezone.as_ref().unwrap().offset_seconds, 3600);
        assert_eq!(info.timezone.unwrap().source, "Guessed from FileModifyDate");
        // The UTC time is calculated from the local time + guessed offset.
        assert_eq!(
            info.datetime_utc.unwrap().to_rfc3339(),
            "2011-01-01T15:26:30+00:00"
        );
        // Confidence is Medium because the offset is a guess.
        assert_eq!(info.source_details.confidence, CONFIDENCE_MEDIUM);
    }

    #[test]
    fn test_priority6_naive_with_fallback_timezone() {
        let exif = get_basic_exif();
        let info = get_time_info(&exif, None).unwrap();

        assert_eq!(
            info.datetime_local,
            NaiveDate::from_ymd_opt(2011, 1, 1)
                .unwrap()
                .and_hms_opt(16, 26, 30)
                .unwrap()
        );
        // The timezone is now the provided fallback.
        assert_eq!(info.timezone.as_ref().unwrap().name, "+01:00");
        assert_eq!(info.timezone.unwrap().source, "Guessed from FileModifyDate");
        // UTC time calculated from local time + Paris offset in winter (+1).
        assert_eq!(
            info.datetime_utc.unwrap().to_rfc3339(),
            "2011-01-01T15:26:30+00:00"
        );
        // Confidence is "Fallback".
        assert_eq!(info.source_details.confidence, CONFIDENCE_MEDIUM);
    }

    #[test]
    fn test_priority6_naive_only_low_confidence() {
        let exif =
            from_str(r#"{ "Time": { "DateTimeOriginal": "2023-05-10 10:00:00" } }"#).unwrap();
        let info = get_time_info(&exif, None).unwrap();

        assert_eq!(
            info.datetime_local,
            NaiveDate::from_ymd_opt(2023, 5, 10)
                .unwrap()
                .and_hms_opt(10, 0, 0)
                .unwrap()
        );
        // With no other information, UTC and timezone must be None.
        assert!(info.datetime_utc.is_none());
        assert!(info.timezone.is_none());
        // Confidence is Low.
        assert_eq!(info.source_details.confidence, CONFIDENCE_LOW);
    }

    #[test]
    fn test_priority7_utc_only_with_fallback_timezone() {
        let exif = from_str(r#"{ "Time": { "GPSDateTime": "2022-08-15T18:00:00Z" } }"#).unwrap();
        let info = get_time_info(&exif, None).unwrap();

        // UTC time is known and accurate.
        assert_eq!(
            info.datetime_utc.unwrap().to_rfc3339(),
            "2022-08-15T18:00:00+00:00"
        );
        // The local time should be the UTC time, since no naive time is provided at all.
        assert_eq!(
            info.datetime_local,
            NaiveDate::from_ymd_opt(2022, 8, 15)
                .unwrap()
                .and_hms_opt(18, 0, 0)
                .unwrap()
        );
    }
}