Skip to main content

smriti/services/
metadata_processor.rs

1//! Background EXIF + geocoding pass.
2//!
3//! Reads photos with `metadata_extracted = 0`, runs `ExifExtractor::extract`
4//! on each (header read only, ~10 KB per file), reverse-geocodes any GPS
5//! coordinates, and updates the row in place. Idempotent and resumable.
6
7use std::io::{Read, Seek, SeekFrom};
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::Arc;
11use std::time::Instant;
12
13use async_channel::{bounded, Receiver, Sender};
14use rayon::prelude::*;
15use regex::Regex;
16use rusqlite::params;
17
18use crate::db::Database;
19use crate::models::MediaType;
20use crate::services::exif_extractor::ExifExtractor;
21use crate::services::scanner::media_type_for_path;
22use crate::services::GeocodingService;
23
24const METADATA_CHUNK_SIZE: usize = 50;
25
26#[derive(Debug, Clone)]
27pub struct MetadataProgress {
28    pub total: u64,
29    pub done: u64,
30    pub is_complete: bool,
31    pub elapsed_seconds: f64,
32    pub stage: Option<String>,
33    pub message: Option<String>,
34}
35
36pub fn start_metadata_job(
37    drive_root: PathBuf,
38    db: Arc<tokio::sync::Mutex<Database>>,
39    cancel: Arc<AtomicBool>,
40) -> (Receiver<MetadataProgress>, tokio::task::JoinHandle<()>) {
41    let (progress_tx, progress_rx) = bounded::<MetadataProgress>(32);
42    let handle = tokio::spawn(async move {
43        run_metadata_job(drive_root, db, cancel, progress_tx).await;
44    });
45    (progress_rx, handle)
46}
47
48async fn run_metadata_job(
49    drive_root: PathBuf,
50    db: Arc<tokio::sync::Mutex<Database>>,
51    cancel: Arc<AtomicBool>,
52    progress_tx: Sender<MetadataProgress>,
53) {
54    let start = Instant::now();
55
56    let total: u64 = {
57        let guard = db.lock().await;
58        // Per-run failure exclusion lives in a temp table so the chunk
59        // query plan stays constant no matter how many files failed
60        // (an ever-growing `NOT IN (…)` list degraded quadratically).
61        if let Err(e) = guard.conn.execute_batch(
62            "CREATE TEMP TABLE IF NOT EXISTS meta_failed_ids (id INTEGER PRIMARY KEY);
63             DELETE FROM meta_failed_ids;",
64        ) {
65            tracing::warn!("metadata failed-id table unavailable: {e}");
66        }
67        guard
68            .conn
69            .query_row(
70                "SELECT COUNT(*) FROM photos WHERE metadata_extracted = FALSE AND is_trashed = FALSE",
71                [],
72                |row| row.get::<_, i64>(0),
73            )
74            .unwrap_or(0)
75            .max(0) as u64
76    };
77    let total = total as u64;
78    let mut done = 0u64;
79    let mut hard_error: Option<String> = None;
80
81    let geonames_path = crate::db::geonames::geonames_db_path();
82    let geocoder = if geonames_path.exists() {
83        GeocodingService::new(&geonames_path).ok()
84    } else {
85        None
86    };
87
88    loop {
89        if cancel.load(Ordering::Relaxed) {
90            break;
91        }
92
93        let chunk: Vec<(i64, String, String)> = {
94            let guard = db.lock().await;
95            match load_metadata_chunk(&guard.conn, METADATA_CHUNK_SIZE) {
96                Ok(rows) => rows,
97                Err(e) => {
98                    hard_error = Some(format!("metadata query failed: {e}"));
99                    Vec::new()
100                }
101            }
102        };
103
104        if hard_error.is_some() || chunk.is_empty() {
105            break;
106        }
107
108        let root = drive_root.clone();
109        let extracted =
110            tokio::task::spawn_blocking(move || -> Vec<(i64, String, ExtractedMetadata)> {
111                chunk
112                    .par_iter()
113                    .map(|(id, rel_path, file_hash)| {
114                        let abs =
115                            match crate::services::path_util::safe_join_relative(&root, rel_path) {
116                                Ok(abs) => abs,
117                                Err(e) => {
118                                    tracing::debug!(
119                                        "metadata skipped unsafe path for photo_id={id}: {e}"
120                                    );
121                                    return (*id, file_hash.clone(), ExtractedMetadata::Skipped);
122                                }
123                            };
124                        // A parser panic on one malformed file skips that
125                        // file instead of failing the whole metadata pass.
126                        let meta = std::panic::catch_unwind(|| {
127                            match media_type_for_path(&abs).unwrap_or_default() {
128                                MediaType::Video => {
129                                    ExtractedMetadata::Video(VideoMetadata::from_path(&abs))
130                                }
131                                MediaType::Photo => {
132                                    ExtractedMetadata::Photo(Box::new(ExifExtractor::extract(&abs)))
133                                }
134                            }
135                        })
136                        .unwrap_or_else(|_| {
137                            tracing::warn!("metadata extraction crashed on {}", abs.display());
138                            ExtractedMetadata::Skipped
139                        });
140                        (*id, file_hash.clone(), meta)
141                    })
142                    .collect()
143            })
144            .await;
145        let extracted = match extracted {
146            Ok(extracted) => extracted,
147            Err(error) => {
148                hard_error = Some(format!("metadata worker failed: {error}"));
149                break;
150            }
151        };
152
153        // Geocoding can query another database; do it before taking the writer lock.
154        let locations: Vec<_> = extracted
155            .iter()
156            .map(
157                |(_, _, meta)| match (meta.gps_latitude(), meta.gps_longitude(), &geocoder) {
158                    (Some(lat), Some(lon), Some(g)) => g
159                        .reverse_geocode(lat, lon)
160                        .map(|r| (Some(r.city), Some(r.country)))
161                        .unwrap_or((None, None)),
162                    _ => (None, None),
163                },
164            )
165            .collect();
166
167        let mut errors_this_chunk = 0usize;
168        {
169            let mut guard = db.lock().await;
170            let tx = match guard.conn.transaction() {
171                Ok(t) => t,
172                Err(e) => {
173                    tracing::error!("metadata tx start: {e}");
174                    hard_error = Some(format!("metadata database transaction failed: {e}"));
175                    break;
176                }
177            };
178
179            for ((id, file_hash, meta), (city, country)) in extracted.iter().zip(&locations) {
180                if matches!(meta, ExtractedMetadata::Skipped) {
181                    errors_this_chunk += 1;
182                    let _ = tx.execute(
183                        "INSERT OR IGNORE INTO meta_failed_ids(id) VALUES (?1)",
184                        [*id],
185                    );
186                    continue;
187                }
188                let gps_latitude = meta.gps_latitude();
189                let gps_longitude = meta.gps_longitude();
190
191                let res = tx.execute(
192                    "UPDATE photos SET
193                        date_taken = ?,
194                        date_taken_source = ?,
195                        gps_latitude = ?,
196                        gps_longitude = ?,
197                        location_city = ?,
198                        location_country = ?,
199                        camera_make = ?,
200                        camera_model = ?,
201                        iso = ?,
202                        aperture = ?,
203                        shutter_speed = ?,
204                        focal_length = ?,
205                        lens_model = ?,
206                        flash = ?,
207                        gps_altitude = ?,
208                        width = ?,
209                        height = ?,
210                        orientation = ?,
211                        media_type = ?,
212                        duration_ms = ?,
213                        video_codec = ?,
214                        audio_codec = ?,
215                        frame_rate = ?,
216                        bitrate = ?,
217                        has_audio = ?,
218                        metadata_extracted = TRUE
219                     WHERE id = ? AND file_hash = ?",
220                    params![
221                        meta.date_taken()
222                            .map(|d: chrono::DateTime<chrono::Utc>| d.to_rfc3339()),
223                        meta.date_taken_source(),
224                        gps_latitude,
225                        gps_longitude,
226                        city,
227                        country,
228                        meta.camera_make(),
229                        meta.camera_model(),
230                        meta.iso(),
231                        meta.aperture(),
232                        meta.shutter_speed(),
233                        meta.focal_length(),
234                        meta.lens_model(),
235                        meta.flash(),
236                        meta.gps_altitude(),
237                        meta.width().map(|v| v as i64),
238                        meta.height().map(|v| v as i64),
239                        meta.orientation() as i64,
240                        meta.media_type().as_str(),
241                        meta.duration_ms(),
242                        meta.video_codec(),
243                        meta.audio_codec(),
244                        meta.frame_rate(),
245                        meta.bitrate(),
246                        meta.has_audio(),
247                        id,
248                        file_hash,
249                    ],
250                );
251                match res {
252                    Ok(0) => {
253                        errors_this_chunk += 1;
254                        let _ = tx.execute(
255                            "INSERT OR IGNORE INTO meta_failed_ids(id) VALUES (?1)",
256                            [*id],
257                        );
258                    }
259                    Ok(_) => {}
260                    Err(_) => {
261                        errors_this_chunk += 1;
262                        let _ = tx.execute(
263                            "INSERT OR IGNORE INTO meta_failed_ids(id) VALUES (?1)",
264                            [*id],
265                        );
266                    }
267                }
268            }
269            if let Err(e) = tx.commit() {
270                tracing::error!("metadata tx commit: {e}");
271                hard_error = Some(format!("metadata database commit failed: {e}"));
272                break;
273            }
274        }
275
276        done += (extracted.len() - errors_this_chunk) as u64;
277        let _ = progress_tx.try_send(MetadataProgress {
278            total,
279            done,
280            is_complete: false,
281            elapsed_seconds: start.elapsed().as_secs_f64(),
282            stage: Some("extract".to_string()),
283            message: None,
284        });
285    }
286
287    {
288        let guard = db.lock().await;
289        let _ = guard
290            .conn
291            .execute("DROP TABLE IF EXISTS temp.meta_failed_ids", []);
292    }
293
294    let _ = progress_tx
295        .send(MetadataProgress {
296            total,
297            done,
298            is_complete: hard_error.is_none(),
299            elapsed_seconds: start.elapsed().as_secs_f64(),
300            stage: hard_error
301                .as_ref()
302                .map(|_| "error".to_string())
303                .or_else(|| Some("complete".to_string())),
304            message: hard_error,
305        })
306        .await;
307}
308
309enum ExtractedMetadata {
310    Photo(Box<crate::services::exif_extractor::ImageMetadata>),
311    Video(VideoMetadata),
312    Skipped,
313}
314
315fn load_metadata_chunk(
316    conn: &rusqlite::Connection,
317    limit: usize,
318) -> rusqlite::Result<Vec<(i64, String, String)>> {
319    conn.execute_batch("CREATE TEMP TABLE IF NOT EXISTS meta_failed_ids (id INTEGER PRIMARY KEY)")?;
320    let sql = "SELECT id, file_path, file_hash FROM photos \
321         WHERE metadata_extracted = FALSE AND is_trashed = FALSE \
322         AND NOT EXISTS (SELECT 1 FROM meta_failed_ids f WHERE f.id = photos.id) \
323         ORDER BY id ASC LIMIT ?";
324    let mut stmt = conn.prepare(sql)?;
325    let rows = stmt.query_map([limit as i64], |row| {
326        Ok((row.get(0)?, row.get(1)?, row.get(2)?))
327    })?;
328    rows.collect()
329}
330
331#[derive(Debug, Clone, Default)]
332struct VideoMetadata {
333    date_taken: Option<chrono::DateTime<chrono::Utc>>,
334    date_taken_source: Option<String>,
335}
336
337impl VideoMetadata {
338    fn from_path(path: &Path) -> Self {
339        if let Some(date) = video_capture_date(path) {
340            return Self {
341                date_taken: Some(date),
342                date_taken_source: Some("video_metadata".into()),
343            };
344        }
345        if let Some(date) = ExifExtractor::parse_date_from_filename(path) {
346            return Self {
347                date_taken: Some(date),
348                date_taken_source: Some("filename".into()),
349            };
350        }
351        Self {
352            date_taken: file_mtime(path),
353            date_taken_source: Some("mtime".into()),
354        }
355    }
356}
357
358fn video_capture_date(path: &Path) -> Option<chrono::DateTime<chrono::Utc>> {
359    let bytes = read_video_probe_bytes(path).ok()?;
360    embedded_video_date_string(&bytes).or_else(|| quicktime_epoch_date(&bytes))
361}
362
363fn read_video_probe_bytes(path: &Path) -> std::io::Result<Vec<u8>> {
364    const PROBE_CHUNK: usize = 8 * 1024 * 1024;
365    let mut file = std::fs::File::open(path)?;
366    let len = file.metadata()?.len();
367    if len <= (PROBE_CHUNK * 2) as u64 {
368        let mut bytes = Vec::with_capacity(len as usize);
369        file.read_to_end(&mut bytes)?;
370        return Ok(bytes);
371    }
372
373    let mut bytes = vec![0u8; PROBE_CHUNK];
374    file.read_exact(&mut bytes)?;
375    file.seek(SeekFrom::End(-(PROBE_CHUNK as i64)))?;
376    let mut tail = vec![0u8; PROBE_CHUNK];
377    file.read_exact(&mut tail)?;
378    bytes.extend_from_slice(&tail);
379    Ok(bytes)
380}
381
382fn quicktime_epoch_date(bytes: &[u8]) -> Option<chrono::DateTime<chrono::Utc>> {
383    find_quicktime_atom_date(bytes, b"mvhd").or_else(|| find_quicktime_atom_date(bytes, b"mdhd"))
384}
385
386fn find_quicktime_atom_date(bytes: &[u8], atom: &[u8; 4]) -> Option<chrono::DateTime<chrono::Utc>> {
387    const QT_TO_UNIX_SECONDS: i64 = 2_082_844_800;
388    for i in 0..bytes.len().saturating_sub(16) {
389        if &bytes[i..i + 4] != atom {
390            continue;
391        }
392        let version = bytes.get(i + 4).copied()?;
393        let seconds = match version {
394            0 => {
395                let raw = u32::from_be_bytes(bytes.get(i + 8..i + 12)?.try_into().ok()?);
396                i64::from(raw)
397            }
398            1 => {
399                let raw = u64::from_be_bytes(bytes.get(i + 8..i + 16)?.try_into().ok()?);
400                i64::try_from(raw).ok()?
401            }
402            _ => continue,
403        };
404        if seconds <= QT_TO_UNIX_SECONDS {
405            continue;
406        }
407        let unix = seconds - QT_TO_UNIX_SECONDS;
408        let dt = chrono::DateTime::from_timestamp(unix, 0)?;
409        ExifExtractor::plausible_datetime(dt.naive_utc())?;
410        return Some(dt);
411    }
412    None
413}
414
415fn embedded_video_date_string(bytes: &[u8]) -> Option<chrono::DateTime<chrono::Utc>> {
416    lazy_static::lazy_static! {
417        static ref VIDEO_DATE: Regex = Regex::new(
418            r"(?x)
419            (\d{4}[:-]\d{2}[:-]\d{2}
420            [ T]
421            \d{2}:\d{2}(?::\d{2}(?:\.\d+)? )?
422            (?:Z|[+-]\d{2}:?\d{2})?)
423            "
424        ).unwrap();
425    }
426    let text = String::from_utf8_lossy(bytes);
427    for caps in VIDEO_DATE.captures_iter(&text) {
428        let candidate = caps.get(1)?.as_str();
429        if let Some(dt) = ExifExtractor::parse_exif_date(candidate) {
430            return Some(dt);
431        }
432    }
433    None
434}
435
436fn file_mtime(path: &Path) -> Option<chrono::DateTime<chrono::Utc>> {
437    let metadata = std::fs::metadata(path).ok()?;
438    let mtime = metadata.modified().ok()?;
439    let duration = mtime.duration_since(std::time::UNIX_EPOCH).ok()?;
440    chrono::DateTime::from_timestamp(duration.as_secs() as i64, 0)
441}
442
443impl ExtractedMetadata {
444    fn media_type(&self) -> MediaType {
445        match self {
446            Self::Photo(_) => MediaType::Photo,
447            Self::Video(_) => MediaType::Video,
448            Self::Skipped => MediaType::Photo,
449        }
450    }
451
452    fn date_taken(&self) -> Option<chrono::DateTime<chrono::Utc>> {
453        match self {
454            Self::Photo(m) => m.date_taken,
455            Self::Video(m) => m.date_taken,
456            Self::Skipped => None,
457        }
458    }
459
460    fn date_taken_source(&self) -> Option<String> {
461        match self {
462            Self::Photo(m) => m.date_taken_source.clone(),
463            Self::Video(m) => m.date_taken_source.clone(),
464            Self::Skipped => None,
465        }
466    }
467
468    fn gps_latitude(&self) -> Option<f64> {
469        match self {
470            Self::Photo(m) => m.gps_latitude,
471            Self::Video(_) => None,
472            Self::Skipped => None,
473        }
474    }
475
476    fn gps_longitude(&self) -> Option<f64> {
477        match self {
478            Self::Photo(m) => m.gps_longitude,
479            Self::Video(_) => None,
480            Self::Skipped => None,
481        }
482    }
483
484    fn camera_make(&self) -> Option<String> {
485        match self {
486            Self::Photo(m) => m.camera_make.clone(),
487            Self::Video(_) => None,
488            Self::Skipped => None,
489        }
490    }
491
492    fn camera_model(&self) -> Option<String> {
493        match self {
494            Self::Photo(m) => m.camera_model.clone(),
495            Self::Video(_) => None,
496            Self::Skipped => None,
497        }
498    }
499
500    fn iso(&self) -> Option<i32> {
501        match self {
502            Self::Photo(m) => m.iso,
503            Self::Video(_) => None,
504            Self::Skipped => None,
505        }
506    }
507
508    fn aperture(&self) -> Option<String> {
509        match self {
510            Self::Photo(m) => m.aperture.clone(),
511            Self::Video(_) => None,
512            Self::Skipped => None,
513        }
514    }
515
516    fn shutter_speed(&self) -> Option<String> {
517        match self {
518            Self::Photo(m) => m.shutter_speed.clone(),
519            Self::Video(_) => None,
520            Self::Skipped => None,
521        }
522    }
523
524    fn focal_length(&self) -> Option<String> {
525        match self {
526            Self::Photo(m) => m.focal_length.clone(),
527            Self::Video(_) => None,
528            Self::Skipped => None,
529        }
530    }
531
532    fn lens_model(&self) -> Option<String> {
533        match self {
534            Self::Photo(m) => m.lens_model.clone(),
535            Self::Video(_) => None,
536            Self::Skipped => None,
537        }
538    }
539
540    fn flash(&self) -> Option<String> {
541        match self {
542            Self::Photo(m) => m.flash.clone(),
543            Self::Video(_) => None,
544            Self::Skipped => None,
545        }
546    }
547
548    fn gps_altitude(&self) -> Option<f64> {
549        match self {
550            Self::Photo(m) => m.gps_altitude,
551            Self::Video(_) => None,
552            Self::Skipped => None,
553        }
554    }
555
556    fn width(&self) -> Option<u32> {
557        match self {
558            Self::Photo(m) => m.width,
559            Self::Video(_) => None,
560            Self::Skipped => None,
561        }
562    }
563
564    fn height(&self) -> Option<u32> {
565        match self {
566            Self::Photo(m) => m.height,
567            Self::Video(_) => None,
568            Self::Skipped => None,
569        }
570    }
571
572    fn orientation(&self) -> u16 {
573        match self {
574            Self::Photo(m) => m.orientation.unwrap_or(1),
575            Self::Video(_) => 1,
576            Self::Skipped => 1,
577        }
578    }
579
580    fn duration_ms(&self) -> Option<i64> {
581        match self {
582            Self::Photo(_) => None,
583            Self::Video(_) => None,
584            Self::Skipped => None,
585        }
586    }
587
588    fn video_codec(&self) -> Option<String> {
589        match self {
590            Self::Photo(_) => None,
591            Self::Video(_) => None,
592            Self::Skipped => None,
593        }
594    }
595
596    fn audio_codec(&self) -> Option<String> {
597        match self {
598            Self::Photo(_) => None,
599            Self::Video(_) => None,
600            Self::Skipped => None,
601        }
602    }
603
604    fn frame_rate(&self) -> Option<f32> {
605        match self {
606            Self::Photo(_) => None,
607            Self::Video(_) => None,
608            Self::Skipped => None,
609        }
610    }
611
612    fn bitrate(&self) -> Option<i64> {
613        match self {
614            Self::Photo(_) => None,
615            Self::Video(_) => None,
616            Self::Skipped => None,
617        }
618    }
619
620    fn has_audio(&self) -> bool {
621        match self {
622            Self::Photo(_) => false,
623            Self::Video(_) => false,
624            Self::Skipped => false,
625        }
626    }
627}
628
629#[cfg(test)]
630mod tests {
631    use super::*;
632    use chrono::{Datelike, TimeZone, Timelike, Utc};
633
634    #[test]
635    fn quicktime_epoch_date_reads_mvhd_creation_time() {
636        const QT_TO_UNIX_SECONDS: i64 = 2_082_844_800;
637        let unix = Utc
638            .with_ymd_and_hms(2024, 1, 15, 10, 16, 0)
639            .single()
640            .unwrap()
641            .timestamp();
642        let qt_seconds = (unix + QT_TO_UNIX_SECONDS) as u32;
643        let mut bytes = Vec::new();
644        bytes.extend_from_slice(&108u32.to_be_bytes());
645        bytes.extend_from_slice(b"mvhd");
646        bytes.push(0);
647        bytes.extend_from_slice(&[0, 0, 0]);
648        bytes.extend_from_slice(&qt_seconds.to_be_bytes());
649        bytes.resize(108, 0);
650
651        let dt = quicktime_epoch_date(&bytes).unwrap();
652        assert_eq!(dt.year(), 2024);
653        assert_eq!(dt.hour(), 10);
654        assert_eq!(dt.minute(), 16);
655    }
656
657    #[test]
658    fn embedded_video_date_string_reads_quicktime_creationdate() {
659        let bytes = b"com.apple.quicktime.creationdate\0\x002024-01-15T10:16:00+05:30";
660        let dt = embedded_video_date_string(bytes).unwrap();
661        assert_eq!(dt.year(), 2024);
662        assert_eq!(dt.hour(), 10);
663        assert_eq!(dt.minute(), 16);
664    }
665
666    #[test]
667    fn metadata_chunk_skips_current_run_failures_without_hiding_pending_rows() {
668        let conn = rusqlite::Connection::open_in_memory().unwrap();
669        conn.execute_batch(
670            r#"
671            CREATE TABLE photos (
672                id INTEGER PRIMARY KEY,
673                file_path TEXT NOT NULL,
674                file_hash TEXT NOT NULL,
675                metadata_extracted BOOLEAN NOT NULL DEFAULT FALSE,
676                is_trashed BOOLEAN NOT NULL DEFAULT FALSE
677            );
678            INSERT INTO photos (id, file_path, file_hash, metadata_extracted, is_trashed)
679            VALUES
680                (1, 'bad.jpg', 'aa111', FALSE, FALSE),
681                (2, 'good.jpg', 'bb222', FALSE, FALSE),
682                (3, 'done.jpg', 'cc333', TRUE, FALSE),
683                (4, 'trashed.jpg', 'dd444', FALSE, TRUE);
684            "#,
685        )
686        .unwrap();
687        conn.execute_batch(
688            "CREATE TEMP TABLE meta_failed_ids (id INTEGER PRIMARY KEY);
689             INSERT INTO meta_failed_ids(id) VALUES (1);",
690        )
691        .unwrap();
692
693        let rows = load_metadata_chunk(&conn, 20).unwrap();
694
695        assert_eq!(rows, vec![(2, "good.jpg".into(), "bb222".into())]);
696    }
697}