Skip to main content

capsule_library/import/importers/
takeout.rs

1//! Google Takeout source adapter.
2//!
3//! Walks a Google Photos [Takeout] export — one directory tree, or the several extracted parts of
4//! a split archive — pairs each media file with its JSON sidecar (photo-taken time, GPS,
5//! description, favorites) and its album folder, and folds the out-of-band exporter metadata into
6//! [`ExtractedMetadata`] under the [precedence rule](super): embedded EXIF wins over the exporter's
7//! records, **except** for album membership, favorites, and user-typed descriptions, which the
8//! exporter is authoritative for.
9//!
10//! **Every file is kept.** JSON is the exporter's sidecar and album-manifest channel; every other
11//! file of an export is a media file whatever its extension (a GIF, a WebP, a 3GP video, a suffix
12//! Capsule has never seen). Only Takeout's own named non-media artefacts (`archive_browser.html`)
13//! and the operating system's folder metadata (`.DS_Store`, `._*`, `Thumbs.db`, `desktop.ini`, the
14//! same rule as the plain scanner) are left out, each with a log line.
15//!
16//! Takeout's structural quirks are handled here so the pure planner never special-cases them:
17//!
18//! - **Truncated filenames.** Takeout truncates long sidecar names; the media file and its JSON can
19//!   share only a prefix. The JSON's `title` carries the true original name, and a prefix fallback
20//!   pairs the two.
21//! - **`(1)` duplicates.** A same-named second file becomes `photo(1).jpg`, but its JSON keeps the
22//!   counter *after* the extension: `photo.jpg(1).json`. Both are normalized to a `(base, ext, dup)`
23//!   key so they pair without cross-matching the un-suffixed original.
24//! - **Edited / original pairs.** `photo.jpg` (original) and `photo-edited.jpg` (Google's edit)
25//!   collapse into one stacked candidate — the edited rendition never becomes a separate asset.
26//! - **Split archives.** A media file and its JSON sidecar can land in different export parts; all
27//!   parts are walked into one pool before pairing, so the pair is reunited.
28//!
29//! [Takeout]: https://docs/design/import/pipeline/#third-party-importers
30
31use std::collections::BTreeMap;
32use std::path::{Path, PathBuf};
33
34use capsule_core::domain::{DetectionMethod, MemberRole, StackType};
35use capsule_core::import::group;
36use capsule_core::import::scan::ImportCandidate;
37use capsule_core::metadata::AssetType;
38use jiff::Timestamp;
39use serde::Deserialize;
40use walkdir::WalkDir;
41
42use crate::exif::{ExifExtract, extract_exif, resolve_timezone};
43use crate::import::importers::{
44    AdapterError, ExtractedImport, ExtractedMetadata, FoldSource, GeoPoint, ImportProvider,
45    SourceAdapter, SourceEntry,
46};
47use crate::import::scanner::is_os_folder_metadata;
48
49/// Minimum shared-prefix length before the truncation fallback will pair a media file with a
50/// truncated JSON sidecar — long enough that unrelated files in the same folder never collide.
51const TRUNCATION_MIN_PREFIX: usize = 16;
52
53/// Google localizes the "-edited" suffix it appends to an edited rendition; a representative set of
54/// the common locales. Matched case-insensitively against the file stem.
55const EDITED_MARKERS: &[&str] = &[
56    "-edited",
57    "-bearbeitet",
58    "-modifié",
59    "-modificato",
60    "-bewerkt",
61    "-editado",
62    "-redigerad",
63    "-muokattu",
64    "-edytowane",
65    "-ha editado",
66];
67
68/// The Google Takeout import [`SourceAdapter`].
69#[derive(Debug, Default, Clone, Copy)]
70pub struct TakeoutAdapter;
71
72impl TakeoutAdapter {
73    /// Construct the adapter.
74    #[must_use]
75    pub fn new() -> Self {
76        Self
77    }
78}
79
80impl SourceAdapter for TakeoutAdapter {
81    fn provider(&self) -> ImportProvider {
82        ImportProvider::GoogleTakeout
83    }
84
85    fn extract(&self, parts: &[PathBuf]) -> Result<ExtractedImport, AdapterError> {
86        if parts.is_empty() {
87            return Err(AdapterError::NoParts);
88        }
89        let mut walk = ExportWalk::default();
90        for root in parts {
91            walk.absorb_root(root)?;
92        }
93        Ok(walk.into_extracted())
94    }
95}
96
97// ── Exporter JSON shapes ─────────────────────────────────────────────────────
98
99/// A Google Photos per-media metadata sidecar (`photo.jpg.json`, `…supplemental-metadata.json`).
100#[derive(Debug, Clone, Default, Deserialize)]
101struct TakeoutSidecar {
102    #[serde(default)]
103    title: Option<String>,
104    #[serde(default)]
105    description: Option<String>,
106    #[serde(default, rename = "photoTakenTime")]
107    photo_taken_time: Option<TakeoutTime>,
108    #[serde(default, rename = "creationTime")]
109    creation_time: Option<TakeoutTime>,
110    #[serde(default, rename = "geoData")]
111    geo_data: Option<GeoData>,
112    #[serde(default, rename = "geoDataExif")]
113    geo_data_exif: Option<GeoData>,
114    #[serde(default)]
115    favorited: bool,
116}
117
118/// A Takeout timestamp record — Unix seconds carried as a string.
119#[derive(Debug, Clone, Default, Deserialize)]
120struct TakeoutTime {
121    #[serde(default)]
122    timestamp: Option<String>,
123}
124
125/// A Takeout `geoData` / `geoDataExif` record. `(0, 0)` is Takeout's "no location" sentinel.
126#[derive(Debug, Clone, Copy, Default, Deserialize)]
127struct GeoData {
128    #[serde(default)]
129    latitude: f64,
130    #[serde(default)]
131    longitude: f64,
132}
133
134/// A Takeout album-folder manifest (`metadata.json`), distinguished from a per-file sidecar by its
135/// fixed filename.
136#[derive(Debug, Clone, Default, Deserialize)]
137struct AlbumMetadata {
138    #[serde(default)]
139    title: Option<String>,
140}
141
142impl TakeoutSidecar {
143    /// The exporter's taken-time (`photoTakenTime`, falling back to `creationTime`).
144    fn taken_time(&self) -> Option<Timestamp> {
145        self.photo_taken_time
146            .as_ref()
147            .or(self.creation_time.as_ref())
148            .and_then(|t| t.timestamp.as_ref())
149            .and_then(|s| s.parse::<i64>().ok())
150            .and_then(|secs| Timestamp::from_second(secs).ok())
151    }
152
153    /// The exporter's GPS fix: the (possibly user-edited) `geoData`, else the `geoDataExif` copy.
154    /// The `(0, 0)` sentinel is treated as absent.
155    fn gps(&self) -> Option<GeoPoint> {
156        let pick = |g: &GeoData| {
157            (g.latitude != 0.0 || g.longitude != 0.0).then_some(GeoPoint {
158                lat: g.latitude,
159                lon: g.longitude,
160            })
161        };
162        self.geo_data
163            .as_ref()
164            .and_then(pick)
165            .or_else(|| self.geo_data_exif.as_ref().and_then(pick))
166    }
167
168    /// The user-typed description, trimmed and empty-normalized to `None`.
169    fn description(&self) -> Option<String> {
170        self.description
171            .as_ref()
172            .map(|d| d.trim().to_string())
173            .filter(|d| !d.is_empty())
174    }
175}
176
177// ── The precedence fold ──────────────────────────────────────────────────────
178
179/// Fold a media file's embedded EXIF and its exporter sidecar into [`ExtractedMetadata`], applying
180/// the precedence rule: embedded EXIF wins for capture time and GPS; the exporter is authoritative
181/// for description, favorites, and album membership.
182fn fold(
183    exif: &ExifExtract,
184    sidecar: Option<&TakeoutSidecar>,
185    mut albums: Vec<String>,
186) -> ExtractedMetadata {
187    // Capture time: EXIF `DateTimeOriginal` (resolved to UTC) wins; else the exporter's taken-time.
188    let exif_time = exif
189        .date_time_original
190        .and_then(|_| resolve_timezone(exif).capture_timestamp)
191        .and_then(|secs| Timestamp::from_second(secs).ok());
192    let (taken_time, taken_time_source) = if let Some(t) = exif_time {
193        (Some(t), FoldSource::Embedded)
194    } else if let Some(t) = sidecar.and_then(TakeoutSidecar::taken_time) {
195        (Some(t), FoldSource::Exporter)
196    } else {
197        (None, FoldSource::Absent)
198    };
199
200    // GPS: embedded EXIF fix wins; else the exporter's coordinates.
201    let (gps, gps_source) = match (exif.gps_lat, exif.gps_lon) {
202        (Some(lat), Some(lon)) => (Some(GeoPoint { lat, lon }), FoldSource::Embedded),
203        _ => match sidecar.and_then(TakeoutSidecar::gps) {
204            Some(p) => (Some(p), FoldSource::Exporter),
205            None => (None, FoldSource::Absent),
206        },
207    };
208
209    albums.sort();
210    albums.dedup();
211
212    ExtractedMetadata {
213        taken_time,
214        taken_time_source,
215        gps,
216        gps_source,
217        // Exporter-authoritative constructs (never carried in the file bytes).
218        description: sidecar.and_then(TakeoutSidecar::description),
219        favorite: sidecar.is_some_and(|s| s.favorited),
220        albums,
221    }
222}
223
224// ── Filename normalization ───────────────────────────────────────────────────
225
226/// A normalized media identity: lowercase stem (dup counter removed), lowercase extension, and the
227/// `(n)` duplicate index. Both a media file and the JSON that targets it reduce to this key, so
228/// `photo(1).jpg` and `photo.jpg(1).json` pair while never matching the un-suffixed original.
229#[derive(Debug, Clone, PartialEq, Eq)]
230struct MediaKey {
231    base: String,
232    ext: String,
233    dup: u32,
234}
235
236/// Split a trailing `(n)` duplicate counter from a stem: `photo(1)` → (`photo`, 1).
237fn split_trailing_dup(stem: &str) -> (String, u32) {
238    if let Some(open) = stem.rfind('(')
239        && stem.ends_with(')')
240    {
241        let inner = &stem[open + 1..stem.len() - 1];
242        if !inner.is_empty()
243            && inner.bytes().all(|b| b.is_ascii_digit())
244            && let Ok(n) = inner.parse::<u32>()
245        {
246            return (stem[..open].to_string(), n);
247        }
248    }
249    (stem.to_string(), 0)
250}
251
252/// Normalize a media filename (e.g. `Photo(1).JPG`) into its [`MediaKey`].
253fn media_key_from_name(name: &str) -> MediaKey {
254    let lower = name.to_lowercase();
255    let (stem, ext) = match lower.rfind('.') {
256        Some(i) => (lower[..i].to_string(), lower[i + 1..].to_string()),
257        None => (lower.clone(), String::new()),
258    };
259    let (base, dup) = split_trailing_dup(&stem);
260    MediaKey { base, ext, dup }
261}
262
263/// Strip a (possibly truncated) `.supplemental-metadata` suffix, matched on its stable stem.
264fn strip_supplemental(s: &str) -> &str {
265    match s.find(".supplemental") {
266        Some(idx) => &s[..idx],
267        None => s,
268    }
269}
270
271/// Reduce a JSON sidecar filename to the media it targets: the normalized [`MediaKey`] plus the raw
272/// target string (for the truncation-prefix fallback). Returns `None` for a non-`.json` name.
273fn parse_sidecar_target(json_name: &str) -> Option<(MediaKey, String)> {
274    let lower = json_name.to_lowercase();
275    let body = lower.strip_suffix(".json")?;
276    // The dup counter, when present, sits after the media extension: `photo.jpg(1)`.
277    let (body, dup) = split_trailing_dup(body);
278    let target_raw = strip_supplemental(&body).to_string();
279    let mut key = media_key_from_name(&target_raw);
280    key.dup = dup;
281    Some((key, target_raw))
282}
283
284/// Strip Google's localized `-edited` suffix from a stem, returning the original base if present.
285fn strip_edited_marker(stem_lower: &str) -> Option<String> {
286    EDITED_MARKERS.iter().find_map(|m| {
287        stem_lower
288            .strip_suffix(m)
289            .filter(|base| !base.is_empty())
290            .map(str::to_string)
291    })
292}
293
294/// Takeout's own non-media artefacts, by lowercase file name: the files the exporter writes beside
295/// a user's originals that are not originals themselves. These are the only non-JSON files of an
296/// export the adapter leaves out (**every file is kept** — thumbnails § Media Is Rawshift's); an
297/// extension Capsule does not recognise is never a reason to leave a file out.
298const TAKEOUT_ARTEFACTS: &[&str] = &["archive_browser.html"];
299
300/// Whether `name_lower` (a lowercase file name) is one of [`TAKEOUT_ARTEFACTS`].
301fn is_takeout_artefact(name_lower: &str) -> bool {
302    TAKEOUT_ARTEFACTS.contains(&name_lower)
303}
304
305fn file_name_lower(path: &Path) -> String {
306    path.file_name()
307        .map(|n| n.to_string_lossy().to_lowercase())
308        .unwrap_or_default()
309}
310
311fn parent_dir_name_lower(path: &Path) -> Option<String> {
312    path.parent()
313        .and_then(Path::file_name)
314        .map(|n| n.to_string_lossy().to_lowercase())
315}
316
317// ── The walk ─────────────────────────────────────────────────────────────────
318
319struct MediaFile {
320    path: PathBuf,
321    parent: PathBuf,
322    file_name: String,
323    ext: String,
324    key: MediaKey,
325}
326
327struct SidecarFile {
328    path: PathBuf,
329    parent: PathBuf,
330    target_key: MediaKey,
331    target_raw: String,
332    title: Option<String>,
333    sidecar: TakeoutSidecar,
334}
335
336/// Accumulated media, per-file sidecars, and album memberships across all export parts.
337#[derive(Default)]
338struct ExportWalk {
339    media: Vec<MediaFile>,
340    sidecars: Vec<SidecarFile>,
341    /// Album folder name (lowercase) → display title.
342    album_titles: BTreeMap<String, String>,
343}
344
345impl ExportWalk {
346    /// Walk one export part. JSON files are the sidecar and album-manifest channel; every other
347    /// file is a media file whatever its extension, except a named [`TAKEOUT_ARTEFACTS`] entry.
348    /// Operating-system folder metadata ([`is_os_folder_metadata`]) is left out before either
349    /// channel, as the plain scanner does. Every file left out is logged.
350    fn absorb_root(&mut self, root: &Path) -> Result<(), AdapterError> {
351        for entry in WalkDir::new(root) {
352            let entry = entry.map_err(|e| AdapterError::Io {
353                root: root.display().to_string(),
354                reason: e.to_string(),
355            })?;
356            if !entry.file_type().is_file() {
357                continue;
358            }
359            let path = entry.into_path();
360            if is_os_folder_metadata(&path) {
361                tracing::debug!(
362                    path = %path.display(),
363                    reason = "os_folder_metadata",
364                    "takeout import: left out OS folder metadata that is not an original"
365                );
366                continue;
367            }
368            let name = file_name_lower(&path);
369            let ext = path
370                .extension()
371                .map(|e| e.to_string_lossy().to_lowercase())
372                .unwrap_or_default();
373
374            if name == "metadata.json" {
375                self.absorb_album_manifest(&path);
376                continue;
377            }
378            if ext == "json" {
379                self.absorb_sidecar(path, &name);
380                continue;
381            }
382            if is_takeout_artefact(&name) {
383                tracing::debug!(
384                    path = %path.display(),
385                    reason = "takeout_artefact",
386                    "takeout import: left out a Takeout artefact that is not an original"
387                );
388                continue;
389            }
390            tracing::trace!(path = %path.display(), ext = %ext, "takeout import: media file");
391            let key = media_key_from_name(&name);
392            let parent = path.parent().map(Path::to_path_buf).unwrap_or_default();
393            self.media.push(MediaFile {
394                path,
395                parent,
396                file_name: name,
397                ext,
398                key,
399            });
400        }
401        Ok(())
402    }
403
404    fn absorb_album_manifest(&mut self, path: &Path) {
405        let Some(folder) = parent_dir_name_lower(path) else {
406            return;
407        };
408        // Year buckets ("Photos from 2021") are not user albums.
409        if folder.starts_with("photos from ") {
410            return;
411        }
412        let title = std::fs::read(path)
413            .ok()
414            .and_then(|b| serde_json::from_slice::<AlbumMetadata>(&b).ok())
415            .and_then(|m| m.title)
416            .filter(|t| !t.trim().is_empty())
417            .unwrap_or_else(|| {
418                path.parent()
419                    .and_then(Path::file_name)
420                    .map(|n| n.to_string_lossy().into_owned())
421                    .unwrap_or_default()
422            });
423        if title.to_lowercase().starts_with("photos from ") {
424            return;
425        }
426        self.album_titles.insert(folder, title);
427    }
428
429    fn absorb_sidecar(&mut self, path: PathBuf, name: &str) {
430        let Some((target_key, target_raw)) = parse_sidecar_target(name) else {
431            return;
432        };
433        // A malformed sidecar degrades to an empty record rather than aborting the import.
434        let sidecar = std::fs::read(&path)
435            .ok()
436            .and_then(|b| serde_json::from_slice::<TakeoutSidecar>(&b).ok())
437            .unwrap_or_default();
438        let title = sidecar.title.as_ref().map(|t| t.to_lowercase());
439        let parent = path.parent().map(Path::to_path_buf).unwrap_or_default();
440        self.sidecars.push(SidecarFile {
441            path,
442            parent,
443            target_key,
444            target_raw,
445            title,
446            sidecar,
447        });
448    }
449
450    fn into_extracted(mut self) -> ExtractedImport {
451        // Deterministic processing order regardless of filesystem walk order.
452        self.media.sort_by(|a, b| a.path.cmp(&b.path));
453
454        let paired = self.pair_sidecars();
455        let mut entries = self.build_entries(&paired);
456        entries.sort_by(|a, b| a.primary_path().cmp(b.primary_path()));
457        ExtractedImport { entries }
458    }
459
460    /// Pair each media file with at most one sidecar, in ordered passes: exact key, `title`, then a
461    /// truncation-prefix fallback. Each sidecar is consumed once. Returns `paired[i]` = the sidecar
462    /// index for `media[i]`.
463    fn pair_sidecars(&self) -> Vec<Option<usize>> {
464        let mut used = vec![false; self.sidecars.len()];
465        let mut paired = vec![None; self.media.len()];
466        for (mi, m) in self.media.iter().enumerate() {
467            let chosen = self
468                .pick(&used, m, |s| s.target_key == m.key)
469                .or_else(|| {
470                    self.pick(&used, m, |s| {
471                        s.title.as_deref() == Some(m.file_name.as_str())
472                    })
473                })
474                .or_else(|| self.pick(&used, m, |s| truncation_match(&s.target_raw, &m.file_name)));
475            if let Some(si) = chosen {
476                used[si] = true;
477                paired[mi] = Some(si);
478            }
479        }
480        paired
481    }
482
483    /// The best unconsumed sidecar matching `pred`: same-directory sidecars win, then lowest path.
484    fn pick(
485        &self,
486        used: &[bool],
487        m: &MediaFile,
488        pred: impl Fn(&SidecarFile) -> bool,
489    ) -> Option<usize> {
490        let mut best: Option<usize> = None;
491        for (i, s) in self.sidecars.iter().enumerate() {
492            if used[i] || !pred(s) {
493                continue;
494            }
495            let better = match best {
496                None => true,
497                Some(b) => {
498                    let cur_same = s.parent == m.parent;
499                    let best_same = self.sidecars[b].parent == m.parent;
500                    match (cur_same, best_same) {
501                        (true, false) => true,
502                        (false, true) => false,
503                        _ => s.path < self.sidecars[b].path,
504                    }
505                }
506            };
507            if better {
508                best = Some(i);
509            }
510        }
511        best
512    }
513
514    /// Group media into candidates (collapsing edited/original pairs) and fold each entry.
515    fn build_entries(&self, paired: &[Option<usize>]) -> Vec<SourceEntry> {
516        // Group by (parent, original-stem, ext, dup): an edited rendition shares its original's key.
517        type GroupKey = (PathBuf, String, String, u32);
518        let mut groups: BTreeMap<GroupKey, Vec<usize>> = BTreeMap::new();
519        for (mi, m) in self.media.iter().enumerate() {
520            let base = strip_edited_marker(&m.key.base).unwrap_or_else(|| m.key.base.clone());
521            groups
522                .entry((m.parent.clone(), base, m.key.ext.clone(), m.key.dup))
523                .or_default()
524                .push(mi);
525        }
526
527        let mut entries = Vec::new();
528        for indices in groups.values() {
529            let originals: Vec<usize> = indices
530                .iter()
531                .copied()
532                .filter(|&i| strip_edited_marker(&self.media[i].key.base).is_none())
533                .collect();
534            let editeds: Vec<usize> = indices
535                .iter()
536                .copied()
537                .filter(|&i| strip_edited_marker(&self.media[i].key.base).is_some())
538                .collect();
539
540            if originals.len() == 1 && !editeds.is_empty() {
541                // One stacked candidate: original is primary, each edited rendition an alternate.
542                entries.push(self.entry_for(originals[0], &editeds, paired));
543            } else {
544                for &i in indices {
545                    entries.push(self.entry_for(i, &[], paired));
546                }
547            }
548        }
549        entries
550    }
551
552    /// Build a [`SourceEntry`] for the primary media `pi`, stacking `extras` as alternates and
553    /// folding the primary's exporter sidecar + album membership.
554    fn entry_for(&self, pi: usize, extras: &[usize], paired: &[Option<usize>]) -> SourceEntry {
555        let primary = &self.media[pi];
556        let sidecar = paired[pi].map(|si| &self.sidecars[si].sidecar);
557        let exif = extract_exif(&primary.path).unwrap_or_default();
558        let albums: Vec<String> = parent_dir_name_lower(&primary.path)
559            .and_then(|folder| self.album_titles.get(&folder).cloned())
560            .into_iter()
561            .collect();
562        let metadata = fold(&exif, sidecar, albums);
563
564        let detected_type = if group::is_video(&primary.ext) {
565            AssetType::Video
566        } else {
567            AssetType::Photo
568        };
569
570        if extras.is_empty() {
571            let members = vec![(primary.path.clone(), MemberRole::Primary)];
572            SourceEntry {
573                candidate: ImportCandidate {
574                    source_paths: vec![primary.path.clone()],
575                    detected_type,
576                    stack_type: None,
577                    detection_method: None,
578                    detection_key: None,
579                    members,
580                },
581                metadata,
582            }
583        } else {
584            let mut members = vec![(primary.path.clone(), MemberRole::Primary)];
585            let mut source_paths = vec![primary.path.clone()];
586            for &ei in extras {
587                members.push((self.media[ei].path.clone(), MemberRole::Alternate));
588                source_paths.push(self.media[ei].path.clone());
589            }
590            SourceEntry {
591                candidate: ImportCandidate {
592                    source_paths,
593                    detected_type,
594                    stack_type: Some(StackType::Custom),
595                    detection_method: Some(DetectionMethod::FilenameStem),
596                    detection_key: Some(
597                        strip_edited_marker(&primary.key.base)
598                            .unwrap_or_else(|| primary.key.base.clone()),
599                    ),
600                    members,
601                },
602                metadata,
603            }
604        }
605    }
606}
607
608/// A media file and a truncated sidecar target share a long-enough prefix (either direction).
609fn truncation_match(target_raw: &str, media_name: &str) -> bool {
610    let shared = if media_name.starts_with(target_raw) {
611        target_raw.len()
612    } else if target_raw.starts_with(media_name) {
613        media_name.len()
614    } else {
615        return false;
616    };
617    shared >= TRUNCATION_MIN_PREFIX
618}
619
620// ── Tests ────────────────────────────────────────────────────────────────────
621
622#[cfg(test)]
623mod tests;