Skip to main content

smriti/services/
takeout_import.rs

1//! Google Photos Takeout ZIP importer.
2//!
3//! The importer treats every selected ZIP as one logical export, so sidecars
4//! and repeated album copies can be reconciled across split Takeout parts.
5//! Media is streamed through a temporary file, hashed, and atomically moved
6//! into the library. The database ledger makes reruns idempotent and retains
7//! Google-only metadata for future refreshes.
8
9use std::collections::{BTreeSet, HashMap, HashSet};
10use std::fs::{self, File};
11use std::io::{BufReader, BufWriter, Read, Write};
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::time::Instant;
15
16use chrono::{DateTime, TimeZone, Utc};
17use rusqlite::{params, Connection, OptionalExtension};
18use serde::{Deserialize, Serialize};
19use sha2::{Digest, Sha256};
20use zip::read::ZipArchive;
21
22use crate::db::{AlbumRepo, TakeoutImportRepo, TakeoutLedgerItem};
23use crate::services::scanner::{calculate_hash, media_type_for_path};
24
25const IMPORT_DIR: &str = "Imported from Google Photos";
26const STAGING_DIR: &str = "takeout-import";
27const MAX_JSON_BYTES: u64 = 8 * 1024 * 1024;
28const MAX_ARCHIVE_ENTRIES: usize = 2_000_000;
29const MIN_MEDIA_BYTES: u64 = 10 * 1024;
30const SPACE_MARGIN_BYTES: u64 = 256 * 1024 * 1024;
31
32#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
33pub struct TakeoutMetadata {
34    pub title: Option<String>,
35    pub description: Option<String>,
36    pub taken_at_unix: Option<i64>,
37    pub latitude: Option<f64>,
38    pub longitude: Option<f64>,
39    pub altitude: Option<f64>,
40    pub favorited: bool,
41}
42
43impl TakeoutMetadata {
44    fn merge_from(&mut self, other: &Self) {
45        if self.title.is_none() {
46            self.title.clone_from(&other.title);
47        }
48        if self.description.is_none() {
49            self.description.clone_from(&other.description);
50        }
51        if self.taken_at_unix.is_none() {
52            self.taken_at_unix = other.taken_at_unix;
53        }
54        if self.latitude.is_none() {
55            self.latitude = other.latitude;
56        }
57        if self.longitude.is_none() {
58            self.longitude = other.longitude;
59        }
60        if self.altitude.is_none() {
61            self.altitude = other.altitude;
62        }
63        self.favorited |= other.favorited;
64    }
65
66    pub fn taken_at_rfc3339(&self) -> Option<String> {
67        self.taken_at_unix
68            .and_then(|ts| Utc.timestamp_opt(ts, 0).single())
69            .map(|dt| dt.to_rfc3339())
70    }
71}
72
73#[derive(Debug, Clone, Serialize)]
74pub struct TakeoutProgress {
75    pub stage: &'static str,
76    pub processed: u64,
77    pub total: u64,
78    pub message: String,
79    pub elapsed_seconds: f64,
80}
81
82#[derive(Debug, Clone, Serialize, Default)]
83pub struct TakeoutImportReport {
84    pub archives: u64,
85    pub media_found: u64,
86    pub imported: u64,
87    pub reused_existing: u64,
88    pub duplicates_collapsed: u64,
89    pub unsupported_or_small: u64,
90    pub unmatched_sidecars: u64,
91    pub albums_restored: u64,
92    pub metadata_restored: u64,
93    pub errors: Vec<String>,
94    pub cancelled: bool,
95}
96
97#[derive(Debug, Clone)]
98struct MediaEntry {
99    archive_index: usize,
100    entry_index: usize,
101    logical_path: String,
102    size: u64,
103    sidecar_key: String,
104    folder_key: String,
105    file_name: String,
106}
107
108#[derive(Debug, Default)]
109struct ImportPlan {
110    archives: Vec<PathBuf>,
111    media: Vec<MediaEntry>,
112    sidecars: HashMap<String, TakeoutMetadata>,
113    album_dirs: HashMap<String, String>,
114    json_count: u64,
115    ignored_count: u64,
116    estimated_unique_bytes: u64,
117}
118
119#[derive(Debug)]
120struct ImportedAggregate {
121    relative_path: String,
122    metadata: TakeoutMetadata,
123    albums: BTreeSet<String>,
124}
125
126#[derive(Debug, Deserialize)]
127struct RawTime {
128    timestamp: Option<String>,
129}
130
131#[derive(Debug, Deserialize, Default)]
132#[serde(rename_all = "camelCase")]
133struct RawGeo {
134    latitude: Option<f64>,
135    longitude: Option<f64>,
136    altitude: Option<f64>,
137}
138
139#[derive(Debug, Deserialize, Default)]
140#[serde(rename_all = "camelCase")]
141struct RawSidecar {
142    title: Option<String>,
143    description: Option<String>,
144    photo_taken_time: Option<RawTime>,
145    creation_time: Option<RawTime>,
146    geo_data_exif: Option<RawGeo>,
147    geo_data: Option<RawGeo>,
148    favorited: Option<bool>,
149}
150
151pub fn import_google_takeout(
152    archive_paths: &[PathBuf],
153    library_root: &Path,
154    conn: &Connection,
155    cancel: &AtomicBool,
156    mut progress: impl FnMut(TakeoutProgress),
157) -> Result<TakeoutImportReport, String> {
158    let started = Instant::now();
159    validate_library_root(library_root)?;
160    let mut report = TakeoutImportReport {
161        archives: archive_paths.len() as u64,
162        ..Default::default()
163    };
164    progress(TakeoutProgress {
165        stage: "inspect",
166        processed: 0,
167        total: archive_paths.len() as u64,
168        message: "Checking Takeout archives".into(),
169        elapsed_seconds: 0.0,
170    });
171    let plan = inspect_archives(archive_paths, cancel, |processed, total, message| {
172        progress(TakeoutProgress {
173            stage: "inspect",
174            processed,
175            total,
176            message,
177            elapsed_seconds: started.elapsed().as_secs_f64(),
178        });
179    })?;
180    report.media_found = plan.media.len() as u64;
181    report.unsupported_or_small = plan.ignored_count;
182    if cancel.load(Ordering::Relaxed) {
183        report.cancelled = true;
184        return Ok(report);
185    }
186    if plan.media.is_empty() {
187        return Err("No supported Google Photos media was found in the selected ZIP files".into());
188    }
189    check_available_space(library_root, plan.estimated_unique_bytes)?;
190
191    let candidate_sizes: HashSet<i64> = plan
192        .media
193        .iter()
194        .filter_map(|m| i64::try_from(m.size).ok())
195        .collect();
196    let existing_hashes = hash_existing_candidates(conn, library_root, &candidate_sizes, cancel);
197    let import_root = library_root.join(IMPORT_DIR);
198    fs::create_dir_all(&import_root)
199        .map_err(|e| format!("Could not create {}: {e}", import_root.display()))?;
200    let staging = crate::db::connection::library_metadata_dir(library_root).join(STAGING_DIR);
201    prepare_staging(&staging)?;
202
203    let mut aggregates: HashMap<String, ImportedAggregate> = HashMap::new();
204    let mut used_sidecars: HashSet<String> = HashSet::new();
205    let mut current_archive_index = usize::MAX;
206    let mut current_archive: Option<ZipArchive<BufReader<File>>> = None;
207    let repo = TakeoutImportRepo::new(conn);
208
209    for (ordinal, media) in plan.media.iter().enumerate() {
210        if cancel.load(Ordering::Relaxed) {
211            report.cancelled = true;
212            break;
213        }
214        if current_archive_index != media.archive_index {
215            let file = File::open(&plan.archives[media.archive_index]).map_err(|e| {
216                format!(
217                    "Could not reopen {}: {e}",
218                    plan.archives[media.archive_index].display()
219                )
220            })?;
221            current_archive = Some(
222                ZipArchive::new(BufReader::new(file))
223                    .map_err(|e| format!("Invalid ZIP during import: {e}"))?,
224            );
225            current_archive_index = media.archive_index;
226        }
227
228        let temp_path = staging.join(format!("{}.partial", ordinal));
229        if temp_path.exists() {
230            let _ = fs::remove_file(&temp_path);
231        }
232        let archive = current_archive.as_mut().expect("archive opened above");
233        let mut entry = match archive.by_index(media.entry_index) {
234            Ok(entry) => entry,
235            Err(error) => {
236                report
237                    .errors
238                    .push(format!("Could not read {}: {error}", media.logical_path));
239                continue;
240            }
241        };
242        let content_hash = match stream_entry_to_temp(&mut entry, &temp_path) {
243            Ok(hash) => hash,
244            Err(error) => {
245                let _ = fs::remove_file(&temp_path);
246                report
247                    .errors
248                    .push(format!("Could not import {}: {error}", media.logical_path));
249                continue;
250            }
251        };
252
253        let metadata = plan
254            .sidecars
255            .get(&media.sidecar_key)
256            .cloned()
257            .unwrap_or_default();
258        if plan.sidecars.contains_key(&media.sidecar_key) {
259            used_sidecars.insert(media.sidecar_key.clone());
260        }
261        let mut albums = BTreeSet::new();
262        if let Some(album) = plan.album_dirs.get(&media.folder_key) {
263            albums.insert(album.clone());
264        }
265
266        if let Some(existing) = aggregates.get_mut(&content_hash) {
267            existing.metadata.merge_from(&metadata);
268            existing.albums.extend(albums);
269            report.duplicates_collapsed += 1;
270            let _ = fs::remove_file(&temp_path);
271        } else {
272            let prior_takeout = repo
273                .path_for_hash(&content_hash)
274                .map_err(|e| e.to_string())?;
275            let existing_path = prior_takeout
276                .filter(|path| library_root.join(path).is_file())
277                .or_else(|| existing_hashes.get(&content_hash).cloned());
278            let relative_path = if let Some(path) = existing_path {
279                report.reused_existing += 1;
280                let _ = fs::remove_file(&temp_path);
281                path
282            } else {
283                let destination = destination_for(&import_root, media, &metadata, &content_hash)?;
284                if destination.is_file()
285                    && calculate_hash(&destination).ok().as_deref() == Some(&content_hash)
286                {
287                    let _ = fs::remove_file(&temp_path);
288                    report.reused_existing += 1;
289                } else {
290                    atomic_move(&temp_path, &destination)?;
291                    report.imported += 1;
292                }
293                crate::services::path_util::relative_path_for_storage(
294                    destination
295                        .strip_prefix(library_root)
296                        .map_err(|_| "Import destination escaped the library root".to_string())?,
297                )
298            };
299            aggregates.insert(
300                content_hash,
301                ImportedAggregate {
302                    relative_path,
303                    metadata,
304                    albums,
305                },
306            );
307        }
308
309        progress(TakeoutProgress {
310            stage: "extract",
311            processed: (ordinal + 1) as u64,
312            total: plan.media.len() as u64,
313            message: media.file_name.clone(),
314            elapsed_seconds: started.elapsed().as_secs_f64(),
315        });
316    }
317
318    let ledger_items: Vec<TakeoutLedgerItem> = aggregates
319        .iter()
320        .map(|(hash, aggregate)| TakeoutLedgerItem {
321            content_hash: hash.clone(),
322            file_path: aggregate.relative_path.clone(),
323            metadata_json: (aggregate.metadata != TakeoutMetadata::default())
324                .then(|| serde_json::to_string(&aggregate.metadata).ok())
325                .flatten(),
326            albums: aggregate.albums.clone(),
327        })
328        .collect();
329    repo.upsert_items(&ledger_items)
330        .map_err(|e| format!("Could not save Takeout import state: {e}"))?;
331    report.unmatched_sidecars = plan
332        .sidecars
333        .keys()
334        .filter(|key| !used_sidecars.contains(*key))
335        .count() as u64;
336    let _ = fs::remove_dir_all(&staging);
337    Ok(report)
338}
339
340pub fn apply_takeout_metadata_and_albums(conn: &Connection) -> Result<(u64, u64), String> {
341    let geocoder =
342        crate::services::geocoding::GeocodingService::new(crate::db::geonames::geonames_db_path())
343            .ok();
344    let mut stmt = conn
345        .prepare(
346            r#"
347            SELECT i.content_hash, i.metadata_json, p.id
348              FROM google_takeout_items i
349              JOIN photos p ON p.file_path = i.file_path
350             WHERE p.is_trashed = FALSE
351            "#,
352        )
353        .map_err(|e| e.to_string())?;
354    let rows: Vec<(String, Option<String>, i64)> = stmt
355        .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
356        .map_err(|e| e.to_string())?
357        .collect::<Result<_, _>>()
358        .map_err(|e| e.to_string())?;
359    drop(stmt);
360
361    let mut parsed_rows = Vec::with_capacity(rows.len());
362    let mut album_photos: HashMap<String, Vec<i64>> = HashMap::new();
363    for (hash, metadata_json, photo_id) in rows {
364        let metadata = metadata_json
365            .as_deref()
366            .and_then(|json| serde_json::from_str::<TakeoutMetadata>(json).ok());
367        parsed_rows.push((photo_id, metadata));
368        let mut album_stmt = conn
369            .prepare("SELECT album_name FROM google_takeout_albums WHERE content_hash = ?1")
370            .map_err(|e| e.to_string())?;
371        let albums: Vec<String> = album_stmt
372            .query_map(params![hash], |r| r.get(0))
373            .map_err(|e| e.to_string())?
374            .collect::<Result<_, _>>()
375            .map_err(|e| e.to_string())?;
376        for album in albums {
377            album_photos.entry(album).or_default().push(photo_id);
378        }
379    }
380
381    let tx = conn.unchecked_transaction().map_err(|e| e.to_string())?;
382    let mut metadata_restored = 0u64;
383    for (photo_id, metadata) in parsed_rows {
384        if let Some(metadata) = metadata {
385            let taken = metadata.taken_at_rfc3339();
386            let (city, country) = match (metadata.latitude, metadata.longitude, geocoder.as_ref()) {
387                (Some(lat), Some(lon), Some(g)) => g
388                    .reverse_geocode(lat, lon)
389                    .map(|place| (Some(place.city), Some(place.country)))
390                    .unwrap_or((None, None)),
391                _ => (None, None),
392            };
393            tx.execute(
394                    r#"
395                    UPDATE photos SET
396                        date_taken = COALESCE(?1, date_taken),
397                        date_taken_source = CASE WHEN ?1 IS NOT NULL THEN 'google_takeout' ELSE date_taken_source END,
398                        gps_latitude = COALESCE(?2, gps_latitude),
399                        gps_longitude = COALESCE(?3, gps_longitude),
400                        gps_altitude = COALESCE(?4, gps_altitude),
401                        location_city = COALESCE(?5, location_city),
402                        location_country = COALESCE(?6, location_country),
403                        is_favorite = CASE WHEN ?7 THEN TRUE ELSE is_favorite END,
404                        updated_at = CURRENT_TIMESTAMP
405                    WHERE id = ?8
406                    "#,
407                    params![
408                        taken,
409                        metadata.latitude,
410                        metadata.longitude,
411                        metadata.altitude,
412                        city,
413                        country,
414                        metadata.favorited,
415                        photo_id
416                    ],
417                )
418                .map_err(|e| e.to_string())?;
419            metadata_restored += 1;
420        }
421    }
422    tx.commit().map_err(|e| e.to_string())?;
423
424    let mut album_ids = HashSet::new();
425    for (album_name, photo_ids) in album_photos {
426        let existing: Option<i64> = conn
427            .query_row(
428                "SELECT id FROM albums WHERE name = ?1 ORDER BY id LIMIT 1",
429                params![album_name],
430                |r| r.get(0),
431            )
432            .optional()
433            .map_err(|e| e.to_string())?;
434        let album_id = match existing {
435            Some(id) => id,
436            None => AlbumRepo::new(conn)
437                .create(&album_name)
438                .map_err(|e| e.to_string())?,
439        };
440        AlbumRepo::new(conn)
441            .add_photos(album_id, &photo_ids)
442            .map_err(|e| e.to_string())?;
443        album_ids.insert(album_id);
444    }
445    Ok((metadata_restored, album_ids.len() as u64))
446}
447
448fn inspect_archives(
449    archive_paths: &[PathBuf],
450    cancel: &AtomicBool,
451    mut progress: impl FnMut(u64, u64, String),
452) -> Result<ImportPlan, String> {
453    if archive_paths.is_empty() {
454        return Err("Select at least one Google Takeout ZIP file".into());
455    }
456    let mut plan = ImportPlan {
457        archives: archive_paths.to_vec(),
458        ..Default::default()
459    };
460    let mut unique_size_crc = HashSet::new();
461    for (archive_index, path) in archive_paths.iter().enumerate() {
462        if cancel.load(Ordering::Relaxed) {
463            break;
464        }
465        if path
466            .extension()
467            .and_then(|s| s.to_str())
468            .map(str::to_ascii_lowercase)
469            .as_deref()
470            != Some("zip")
471        {
472            return Err(format!("{} is not a ZIP file", path.display()));
473        }
474        let file =
475            File::open(path).map_err(|e| format!("Could not open {}: {e}", path.display()))?;
476        let mut archive = ZipArchive::new(BufReader::new(file))
477            .map_err(|e| format!("Invalid ZIP {}: {e}", path.display()))?;
478        if archive.len() > MAX_ARCHIVE_ENTRIES {
479            return Err(format!(
480                "{} contains too many entries ({})",
481                path.display(),
482                archive.len()
483            ));
484        }
485        for entry_index in 0..archive.len() {
486            let mut entry = archive.by_index(entry_index).map_err(|e| {
487                format!(
488                    "Could not inspect {} entry {entry_index}: {e}",
489                    path.display()
490                )
491            })?;
492            if entry.is_dir() {
493                continue;
494            }
495            let enclosed = entry.enclosed_name().ok_or_else(|| {
496                format!(
497                    "Unsafe path in {}: {}",
498                    path.display(),
499                    String::from_utf8_lossy(entry.name_raw())
500                )
501            })?;
502            let logical_path = normalize_zip_path(&enclosed);
503            let Some(relative_google_path) = google_photos_relative(&logical_path) else {
504                continue;
505            };
506            let lower = relative_google_path.to_ascii_lowercase();
507            if lower.ends_with(".json") {
508                if entry.size() > MAX_JSON_BYTES {
509                    plan.ignored_count += 1;
510                    continue;
511                }
512                let mut json = String::new();
513                entry
514                    .read_to_string(&mut json)
515                    .map_err(|e| format!("Could not read sidecar {logical_path}: {e}"))?;
516                if file_name_of(&relative_google_path).eq_ignore_ascii_case("metadata.json") {
517                    if let Ok(value) = serde_json::from_str::<serde_json::Value>(&json) {
518                        if let Some(title) = value.get("title").and_then(|v| v.as_str()) {
519                            let folder = folder_of(&relative_google_path);
520                            if !is_year_bucket(&folder) && !title.trim().is_empty() {
521                                plan.album_dirs.insert(folder, title.trim().to_string());
522                            }
523                        }
524                    }
525                } else {
526                    match parse_sidecar(&relative_google_path, &json) {
527                        Some((key, metadata)) => {
528                            plan.sidecars
529                                .entry(key)
530                                .and_modify(|m| m.merge_from(&metadata))
531                                .or_insert(metadata);
532                            plan.json_count += 1;
533                        }
534                        None => plan.ignored_count += 1,
535                    }
536                }
537                continue;
538            }
539            if media_type_for_path(Path::new(&relative_google_path)).is_none()
540                || entry.size() < MIN_MEDIA_BYTES
541            {
542                plan.ignored_count += 1;
543                continue;
544            }
545            let file_name = file_name_of(&relative_google_path).to_string();
546            let folder_key = folder_of(&relative_google_path);
547            let sidecar_key = sidecar_key(&folder_key, &file_name);
548            let size_crc = (entry.size(), entry.crc32());
549            if unique_size_crc.insert(size_crc) {
550                plan.estimated_unique_bytes =
551                    plan.estimated_unique_bytes.saturating_add(entry.size());
552            }
553            plan.media.push(MediaEntry {
554                archive_index,
555                entry_index,
556                logical_path,
557                size: entry.size(),
558                sidecar_key,
559                folder_key,
560                file_name,
561            });
562        }
563        progress(
564            (archive_index + 1) as u64,
565            archive_paths.len() as u64,
566            path.file_name()
567                .and_then(|s| s.to_str())
568                .unwrap_or("Takeout archive")
569                .to_string(),
570        );
571    }
572
573    Ok(plan)
574}
575
576fn parse_sidecar(relative_path: &str, json: &str) -> Option<(String, TakeoutMetadata)> {
577    let raw: RawSidecar = serde_json::from_str(json).ok()?;
578    let folder = folder_of(relative_path);
579    let fallback = sidecar_media_name(file_name_of(relative_path));
580    let title = raw
581        .title
582        .as_deref()
583        .filter(|s| !s.trim().is_empty())
584        .unwrap_or(&fallback)
585        .to_string();
586    if title.is_empty() {
587        return None;
588    }
589    let taken_at_unix = raw
590        .photo_taken_time
591        .or(raw.creation_time)
592        .and_then(|t| t.timestamp)
593        .and_then(|s| s.parse::<i64>().ok());
594    let geo = valid_geo(raw.geo_data_exif).or_else(|| valid_geo(raw.geo_data));
595    let metadata = TakeoutMetadata {
596        title: Some(title.clone()),
597        description: raw.description.filter(|s| !s.is_empty()),
598        taken_at_unix,
599        latitude: geo.as_ref().and_then(|g| g.latitude),
600        longitude: geo.as_ref().and_then(|g| g.longitude),
601        altitude: geo.and_then(|g| g.altitude),
602        favorited: raw.favorited.unwrap_or(false),
603    };
604    Some((sidecar_key(&folder, &title), metadata))
605}
606
607fn valid_geo(geo: Option<RawGeo>) -> Option<RawGeo> {
608    let geo = geo?;
609    let lat = geo.latitude?;
610    let lon = geo.longitude?;
611    if !(-90.0..=90.0).contains(&lat)
612        || !(-180.0..=180.0).contains(&lon)
613        || (lat == 0.0 && lon == 0.0)
614    {
615        return None;
616    }
617    Some(geo)
618}
619
620fn hash_existing_candidates(
621    conn: &Connection,
622    library_root: &Path,
623    sizes: &HashSet<i64>,
624    cancel: &AtomicBool,
625) -> HashMap<String, String> {
626    let repo = TakeoutImportRepo::new(conn);
627    let mut result = HashMap::new();
628    let candidates = repo.candidate_existing_files(sizes).unwrap_or_default();
629    for (relative, _) in candidates {
630        if cancel.load(Ordering::Relaxed) {
631            break;
632        }
633        let Ok(path) = crate::services::path_util::safe_join_relative(library_root, &relative)
634        else {
635            continue;
636        };
637        if let Ok(hash) = calculate_hash(path) {
638            result.entry(hash).or_insert(relative);
639        }
640    }
641    result
642}
643
644fn stream_entry_to_temp<R: Read>(reader: &mut R, temp_path: &Path) -> Result<String, String> {
645    let file = File::create(temp_path)
646        .map_err(|e| format!("Could not create temporary import file: {e}"))?;
647    let mut writer = BufWriter::new(file);
648    let mut hasher = Sha256::new();
649    let mut buffer = vec![0u8; 1024 * 1024];
650    loop {
651        let count = reader
652            .read(&mut buffer)
653            .map_err(|e| format!("Could not decompress Takeout media: {e}"))?;
654        if count == 0 {
655            break;
656        }
657        writer
658            .write_all(&buffer[..count])
659            .map_err(|e| format!("Could not write imported media: {e}"))?;
660        hasher.update(&buffer[..count]);
661    }
662    writer
663        .flush()
664        .map_err(|e| format!("Could not finish imported media: {e}"))?;
665    Ok(format!("{:x}", hasher.finalize()))
666}
667
668fn destination_for(
669    import_root: &Path,
670    media: &MediaEntry,
671    metadata: &TakeoutMetadata,
672    hash: &str,
673) -> Result<PathBuf, String> {
674    let year = metadata
675        .taken_at_unix
676        .and_then(|ts| Utc.timestamp_opt(ts, 0).single())
677        .map(|d: DateTime<Utc>| d.format("%Y").to_string())
678        .unwrap_or_else(|| "Undated".to_string());
679    let dir = import_root.join(year);
680    fs::create_dir_all(&dir).map_err(|e| format!("Could not create {}: {e}", dir.display()))?;
681    let safe_name = sanitize_file_name(&media.file_name);
682    let preferred = dir.join(&safe_name);
683    if !preferred.exists() {
684        return Ok(preferred);
685    }
686    if calculate_hash(&preferred).ok().as_deref() == Some(hash) {
687        return Ok(preferred);
688    }
689    let source = Path::new(&safe_name);
690    let stem = source
691        .file_stem()
692        .and_then(|s| s.to_str())
693        .unwrap_or("photo");
694    let ext = source.extension().and_then(|s| s.to_str());
695    let mut candidate = match ext {
696        Some(ext) => dir.join(format!("{stem}_{}.{}", &hash[..10], ext)),
697        None => dir.join(format!("{stem}_{}", &hash[..10])),
698    };
699    let mut suffix = 2u32;
700    while candidate.exists() && calculate_hash(&candidate).ok().as_deref() != Some(hash) {
701        candidate = match ext {
702            Some(ext) => dir.join(format!("{stem}_{}_{}.{}", &hash[..10], suffix, ext)),
703            None => dir.join(format!("{stem}_{}_{}", &hash[..10], suffix)),
704        };
705        suffix += 1;
706    }
707    Ok(candidate)
708}
709
710fn atomic_move(source: &Path, destination: &Path) -> Result<(), String> {
711    if let Some(parent) = destination.parent() {
712        fs::create_dir_all(parent)
713            .map_err(|e| format!("Could not create {}: {e}", parent.display()))?;
714    }
715    let mut staged = tempfile::TempPath::try_from_path(source)
716        .map_err(|e| format!("Could not stage imported file: {e}"))?;
717    staged.disable_cleanup(true);
718    staged.persist_noclobber(destination).map_err(|e| {
719        format!(
720            "Could not place imported file at {}: {e}",
721            destination.display()
722        )
723    })?;
724    Ok(())
725}
726
727fn prepare_staging(staging: &Path) -> Result<(), String> {
728    if staging.exists() {
729        fs::remove_dir_all(staging)
730            .map_err(|e| format!("Could not clear stale Takeout staging data: {e}"))?;
731    }
732    fs::create_dir_all(staging)
733        .map_err(|e| format!("Could not create Takeout staging directory: {e}"))
734}
735
736fn check_available_space(root: &Path, required: u64) -> Result<(), String> {
737    let available = fs2::available_space(root)
738        .map_err(|e| format!("Could not determine available library space: {e}"))?;
739    let needed = required.saturating_add(SPACE_MARGIN_BYTES);
740    if available < needed {
741        return Err(format!(
742            "Not enough free space. The import needs about {}, but only {} is available",
743            human_bytes(needed),
744            human_bytes(available)
745        ));
746    }
747    Ok(())
748}
749
750fn validate_library_root(root: &Path) -> Result<(), String> {
751    if !root.is_dir() {
752        return Err(format!("Library folder does not exist: {}", root.display()));
753    }
754    let metadata = crate::db::connection::library_metadata_dir(root);
755    if !metadata.is_dir() {
756        return Err("Open the destination as a Smriti library before importing".into());
757    }
758    Ok(())
759}
760
761fn google_photos_relative(path: &str) -> Option<String> {
762    let components: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
763    let idx = components
764        .iter()
765        .position(|component| component.eq_ignore_ascii_case("Google Photos"))?;
766    let rest = components.get(idx + 1..)?.join("/");
767    (!rest.is_empty()).then_some(rest)
768}
769
770fn normalize_zip_path(path: &Path) -> String {
771    path.components()
772        .map(|component| component.as_os_str().to_string_lossy())
773        .collect::<Vec<_>>()
774        .join("/")
775}
776
777fn folder_of(path: &str) -> String {
778    path.rsplit_once('/')
779        .map(|(folder, _)| folder.to_string())
780        .unwrap_or_default()
781}
782
783fn file_name_of(path: &str) -> &str {
784    path.rsplit('/').next().unwrap_or(path)
785}
786
787fn last_folder_component(path: &str) -> &str {
788    path.rsplit('/').next().unwrap_or(path)
789}
790
791fn sidecar_key(folder: &str, title: &str) -> String {
792    format!("{}\0{}", folder.to_lowercase(), title.to_lowercase())
793}
794
795fn sidecar_media_name(name: &str) -> String {
796    let lower = name.to_ascii_lowercase();
797    if lower.ends_with(".supplemental-metadata.json") {
798        name[..name.len() - ".supplemental-metadata.json".len()].to_string()
799    } else if lower.ends_with(".json") {
800        name[..name.len() - 5].to_string()
801    } else {
802        name.to_string()
803    }
804}
805
806fn is_year_bucket(folder: &str) -> bool {
807    let name = last_folder_component(folder).trim();
808    let lower = name.to_ascii_lowercase();
809    if let Some(year) = lower.strip_prefix("photos from ") {
810        return year.len() == 4 && year.chars().all(|c| c.is_ascii_digit());
811    }
812    false
813}
814
815fn sanitize_file_name(name: &str) -> String {
816    let mut safe: String = name
817        .chars()
818        .map(|c| {
819            if c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*') {
820                '_'
821            } else {
822                c
823            }
824        })
825        .collect();
826    safe = safe.trim_matches([' ', '.']).to_string();
827    if safe.is_empty() {
828        safe = "photo".into();
829    }
830    let stem = Path::new(&safe)
831        .file_stem()
832        .and_then(|s| s.to_str())
833        .unwrap_or("")
834        .to_ascii_uppercase();
835    const RESERVED: &[&str] = &[
836        "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
837        "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
838    ];
839    if RESERVED.contains(&stem.as_str()) {
840        safe.insert(0, '_');
841    }
842    truncate_file_name(&safe, 180)
843}
844
845fn truncate_file_name(name: &str, max_bytes: usize) -> String {
846    if name.len() <= max_bytes {
847        return name.to_string();
848    }
849    let path = Path::new(name);
850    let extension = path
851        .extension()
852        .and_then(|s| s.to_str())
853        .filter(|ext| ext.len() <= 20)
854        .map(|ext| format!(".{ext}"))
855        .unwrap_or_default();
856    let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("photo");
857    let budget = max_bytes.saturating_sub(extension.len());
858    let mut shortened = String::new();
859    for ch in stem.chars() {
860        if shortened.len() + ch.len_utf8() > budget {
861            break;
862        }
863        shortened.push(ch);
864    }
865    if shortened.is_empty() {
866        shortened.push_str("photo");
867    }
868    shortened.push_str(&extension);
869    shortened
870}
871
872fn human_bytes(bytes: u64) -> String {
873    if bytes >= 1024 * 1024 * 1024 {
874        format!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
875    } else {
876        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
877    }
878}
879
880#[cfg(test)]
881mod tests {
882    use super::*;
883    use std::io::Write;
884    use tempfile::tempdir;
885    use zip::write::SimpleFileOptions;
886
887    fn write_zip(path: &Path, entries: &[(&str, &[u8])]) {
888        let file = File::create(path).unwrap();
889        let mut zip = zip::ZipWriter::new(file);
890        for (name, bytes) in entries {
891            zip.start_file(*name, SimpleFileOptions::default()).unwrap();
892            zip.write_all(bytes).unwrap();
893        }
894        zip.finish().unwrap();
895    }
896
897    fn jpeg_bytes(seed: u8) -> Vec<u8> {
898        let mut bytes = vec![seed; MIN_MEDIA_BYTES as usize + 1];
899        bytes[0..3].copy_from_slice(&[0xff, 0xd8, 0xff]);
900        bytes
901    }
902
903    #[test]
904    fn parses_google_sidecar_with_exif_geo_priority() {
905        let json = r#"{
906          "title":"IMG_0001.JPG",
907          "description":"At the beach",
908          "photoTakenTime":{"timestamp":"1704067200"},
909          "geoData":{"latitude":1.0,"longitude":2.0,"altitude":3.0},
910          "geoDataExif":{"latitude":10.0,"longitude":20.0,"altitude":30.0},
911          "favorited":true
912        }"#;
913        let (_, meta) = parse_sidecar("Photos from 2024/IMG_0001.JPG.json", json).unwrap();
914        assert_eq!(meta.taken_at_unix, Some(1_704_067_200));
915        assert_eq!(meta.latitude, Some(10.0));
916        assert_eq!(meta.longitude, Some(20.0));
917        assert!(meta.favorited);
918    }
919
920    #[test]
921    fn multi_part_import_collapses_album_copy_and_restores_metadata() {
922        let root = tempdir().unwrap();
923        let db = crate::db::Database::open_for_drive(root.path()).unwrap();
924        crate::db::create_schema(&db.conn).unwrap();
925        let first = root.path().join("takeout-001.zip");
926        let second = root.path().join("takeout-002.zip");
927        let photo = jpeg_bytes(7);
928        let sidecar = br#"{
929          "title":"IMG_0001.JPG",
930          "photoTakenTime":{"timestamp":"1704067200"},
931          "geoDataExif":{"latitude":10.0,"longitude":20.0,"altitude":30.0},
932          "favorited":true
933        }"#;
934        write_zip(
935            &first,
936            &[
937                (
938                    "Takeout/Google Photos/Photos from 2024/IMG_0001.JPG",
939                    &photo,
940                ),
941                (
942                    "Takeout/Google Photos/Photos from 2024/IMG_0001.JPG.json",
943                    sidecar,
944                ),
945            ],
946        );
947        write_zip(
948            &second,
949            &[
950                (
951                    "Takeout/Google Photos/Beach/metadata.json",
952                    br#"{"title":"Beach"}"#,
953                ),
954                ("Takeout/Google Photos/Beach/IMG_0001.JPG", &photo),
955            ],
956        );
957
958        let report = import_google_takeout(
959            &[first.clone(), second.clone()],
960            root.path(),
961            &db.conn,
962            &AtomicBool::new(false),
963            |_| {},
964        )
965        .unwrap();
966        assert_eq!(report.imported, 1);
967        assert_eq!(report.duplicates_collapsed, 1);
968
969        let cancel = std::sync::Arc::new(AtomicBool::new(false));
970        let db_arc = std::sync::Arc::new(tokio::sync::Mutex::new(db));
971        let runtime = tokio::runtime::Runtime::new().unwrap();
972        let scan_report = runtime.block_on(async {
973            let (rx, task) = crate::services::scanner::start_scan(
974                root.path().to_path_buf(),
975                db_arc.clone(),
976                cancel,
977                false,
978            );
979            let drain = tokio::spawn(async move { while rx.recv().await.is_ok() {} });
980            let report = task.await.unwrap();
981            drain.await.unwrap();
982            report
983        });
984        assert!(
985            scan_report.errors.is_empty(),
986            "scan errors: {:?}",
987            scan_report.errors
988        );
989        let guard = runtime.block_on(db_arc.lock());
990        let photo_count: i64 = guard
991            .conn
992            .query_row("SELECT COUNT(*) FROM photos", [], |r| r.get(0))
993            .unwrap();
994        let ledger: Vec<(String, Option<String>)> = guard
995            .conn
996            .prepare("SELECT file_path, metadata_json FROM google_takeout_items")
997            .unwrap()
998            .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
999            .unwrap()
1000            .collect::<Result<_, _>>()
1001            .unwrap();
1002        assert_eq!(photo_count, 1, "ledger={ledger:?}");
1003        let (metadata, albums) = apply_takeout_metadata_and_albums(&guard.conn).unwrap();
1004        assert_eq!(metadata, 1);
1005        assert_eq!(albums, 1);
1006        let restored: (String, f64, i64) = guard
1007            .conn
1008            .query_row(
1009                "SELECT date_taken_source, gps_latitude, is_favorite FROM photos",
1010                [],
1011                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
1012            )
1013            .unwrap();
1014        assert_eq!(restored.0, "google_takeout");
1015        assert_eq!(restored.1, 10.0);
1016        assert_eq!(restored.2, 1);
1017        let album_count: i64 = guard
1018            .conn
1019            .query_row("SELECT COUNT(*) FROM album_photos", [], |r| r.get(0))
1020            .unwrap();
1021        assert_eq!(album_count, 1);
1022
1023        let repeated = import_google_takeout(
1024            &[first, second],
1025            root.path(),
1026            &guard.conn,
1027            &AtomicBool::new(false),
1028            |_| {},
1029        )
1030        .unwrap();
1031        assert_eq!(repeated.imported, 0);
1032        assert_eq!(repeated.reused_existing, 1);
1033        assert_eq!(repeated.duplicates_collapsed, 1);
1034    }
1035
1036    #[test]
1037    fn sidecar_can_live_in_a_different_takeout_part() {
1038        let root = tempdir().unwrap();
1039        let first = root.path().join("takeout-001.zip");
1040        let second = root.path().join("takeout-002.zip");
1041        write_zip(
1042            &first,
1043            &[(
1044                "Takeout/Google Photos/Photos from 2020/a.jpg",
1045                &jpeg_bytes(2),
1046            )],
1047        );
1048        write_zip(
1049            &second,
1050            &[(
1051                "Takeout/Google Photos/Photos from 2020/a.jpg.json",
1052                br#"{"title":"a.jpg","photoTakenTime":{"timestamp":"1577836800"}}"#,
1053            )],
1054        );
1055        let plan =
1056            inspect_archives(&[first, second], &AtomicBool::new(false), |_, _, _| {}).unwrap();
1057        assert_eq!(plan.media.len(), 1);
1058        assert_eq!(
1059            plan.sidecars
1060                .get(&plan.media[0].sidecar_key)
1061                .and_then(|metadata| metadata.taken_at_unix),
1062            Some(1_577_836_800)
1063        );
1064    }
1065
1066    #[test]
1067    fn cancellation_before_inspection_is_resumable() {
1068        let root = tempdir().unwrap();
1069        let db = crate::db::Database::open_for_drive(root.path()).unwrap();
1070        crate::db::create_schema(&db.conn).unwrap();
1071        let archive = root.path().join("takeout.zip");
1072        write_zip(
1073            &archive,
1074            &[(
1075                "Takeout/Google Photos/Photos from 2020/a.jpg",
1076                &jpeg_bytes(3),
1077            )],
1078        );
1079        let cancel = AtomicBool::new(true);
1080        let report =
1081            import_google_takeout(&[archive], root.path(), &db.conn, &cancel, |_| {}).unwrap();
1082        assert!(report.cancelled);
1083        assert_eq!(report.imported, 0);
1084    }
1085
1086    #[test]
1087    fn rejects_zip_slip_paths() {
1088        let dir = tempdir().unwrap();
1089        let path = dir.path().join("bad.zip");
1090        write_zip(
1091            &path,
1092            &[("../Google Photos/Photos from 2024/a.jpg", &jpeg_bytes(1))],
1093        );
1094        let err = inspect_archives(&[path], &AtomicBool::new(false), |_, _, _| {}).unwrap_err();
1095        assert!(err.contains("Unsafe path"));
1096    }
1097
1098    #[test]
1099    fn sanitizes_windows_names_and_collisions() {
1100        assert_eq!(sanitize_file_name("CON.jpg"), "_CON.jpg");
1101        assert_eq!(sanitize_file_name("bad:name?.jpg"), "bad_name_.jpg");
1102        assert_eq!(sanitize_file_name("  .  "), "photo");
1103        let long = format!("{}.jpeg", "🙂".repeat(100));
1104        let shortened = sanitize_file_name(&long);
1105        assert!(shortened.len() <= 180);
1106        assert!(shortened.ends_with(".jpeg"));
1107    }
1108    #[test]
1109    fn publishing_import_does_not_overwrite_a_new_destination() {
1110        let dir = tempfile::tempdir().unwrap();
1111        let source = dir.path().join("staged");
1112        let destination = dir.path().join("photo.jpg");
1113        fs::write(&source, b"import").unwrap();
1114        fs::write(&destination, b"existing").unwrap();
1115        assert!(atomic_move(&source, &destination).is_err());
1116        assert_eq!(fs::read(&source).unwrap(), b"import");
1117        assert_eq!(fs::read(&destination).unwrap(), b"existing");
1118    }
1119}