Skip to main content

capsule_library/import/importers/
mod.rs

1//! Third-party **source adapters** (the shared seam every importer implements).
2//!
3//! Migration from another photo service is an import, not a new pipeline: a [`SourceAdapter`]
4//! yields `(bytes-source, extracted-metadata)` entries into the same [Scan & Extract] stage the
5//! filesystem [`scanner`](crate::import::scanner) feeds, and the pure
6//! [`planner`](crate::import::planner) and [`executor`](crate::import::executor) are **unchanged**.
7//!
8//! What an adapter owns is *structure awareness*: metadata the exporting service carries
9//! out-of-band (an accompanying JSON/CSV, an album manifest) is folded into
10//! [`ExtractedMetadata`] **before** planning, under a fixed precedence — embedded EXIF wins over
11//! exporter-side records, **except** for constructs the exporter is authoritative for (album
12//! membership, favorites/rating, and user-typed descriptions the file bytes never carried). The
13//! fold happens at extraction, so the planner's determinism contract holds: a given export yields
14//! the same [`ScanResult`] on every run.
15//!
16//! The folded record is not planner input only. The
17//! [executor](crate::import::execute_with_source_metadata) writes it into the **signed
18//! sidecar** at import through [`enrichment`](crate::import::enrichment) — capture time
19//! and GPS as fallbacks behind the file's own EXIF, and the exporter-authoritative constructs
20//! (description, favorites, album membership) unconditionally — so a migrated library keeps what
21//! the exporting service carried instead of discarding it once the plan is built.
22//!
23//! The committed adapters are [`takeout::TakeoutAdapter`] (Google Takeout) and the
24//! [camera adapter](crate::import::camera::CameraAdapter) (PTP/IP); the iCloud and Immich
25//! adapters are post-v1 and land on this same seam.
26//!
27//! [Scan & Extract]: https://docs/design/import/pipeline/#scan--extract
28
29pub(crate) mod takeout;
30
31use std::path::{Path, PathBuf};
32
33use capsule_core::import::scan::{ImportCandidate, ScanResult};
34use jiff::Timestamp;
35use thiserror::Error;
36
37/// The exporting service an adapter migrates from (for logs / telemetry / user-facing labels).
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum ImportProvider {
40    /// Google Photos via Google Takeout.
41    GoogleTakeout,
42    /// iCloud Photos export (post-v1).
43    ICloud,
44    /// Immich export/API (post-v1).
45    Immich,
46    /// A camera over PTP/IP ([`CameraAdapter`](crate::import::camera::CameraAdapter)).
47    Camera,
48}
49
50/// Errors surfaced while walking an export. Malformed *per-file* exporter metadata is tolerated
51/// (the entry degrades to no exporter record); these errors are reserved for failures that abort
52/// the whole extraction (no parts supplied, an unreadable root).
53#[derive(Debug, Error)]
54pub enum AdapterError {
55    /// No export parts were supplied.
56    #[error("no import parts supplied")]
57    NoParts,
58    /// A supplied export root could not be walked.
59    #[error("io reading export root {root}: {reason}")]
60    Io {
61        /// The offending root path.
62        root: String,
63        /// The underlying error text.
64        reason: String,
65    },
66}
67
68/// Which side a folded field was ultimately taken from, per the precedence rule.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum FoldSource {
71    /// From the file's own embedded metadata (EXIF) — the authoritative source for capture time
72    /// and GPS when present.
73    Embedded,
74    /// From the exporting service's out-of-band record (JSON sidecar, CSV, album manifest).
75    Exporter,
76    /// Neither side carried the field.
77    Absent,
78}
79
80/// A WGS-84 point folded from either embedded EXIF or the exporter's record.
81#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct GeoPoint {
83    /// Latitude (WGS-84).
84    pub lat: f64,
85    /// Longitude (WGS-84).
86    pub lon: f64,
87}
88
89/// The out-of-band metadata an adapter folds for one media entry, with the precedence already
90/// resolved. This is the artifact the [Takeout mapping table] validates, one field per rule, and
91/// what [`sidecar_enrichment`](crate::import::sidecar_enrichment) maps onto the
92/// signed sidecar's fields at import.
93///
94/// [Takeout mapping table]: https://docs/design/import/pipeline/#third-party-importers
95#[derive(Debug, Clone, PartialEq)]
96pub struct ExtractedMetadata {
97    /// Capture time: embedded EXIF `DateTimeOriginal` if present, else the exporter's taken-time.
98    pub taken_time: Option<Timestamp>,
99    /// Which side [`taken_time`](Self::taken_time) came from.
100    pub taken_time_source: FoldSource,
101    /// GPS fix: embedded EXIF GPS if present, else the exporter's coordinates.
102    pub gps: Option<GeoPoint>,
103    /// Which side [`gps`](Self::gps) came from.
104    pub gps_source: FoldSource,
105    /// User-typed description — **exporter-authoritative** (the file bytes never carried it).
106    pub description: Option<String>,
107    /// Favorite/starred flag — **exporter-authoritative**.
108    pub favorite: bool,
109    /// Album memberships this entry belongs to — **exporter-authoritative**. Deterministically
110    /// ordered (sorted, de-duplicated).
111    pub albums: Vec<String>,
112}
113
114impl Default for ExtractedMetadata {
115    fn default() -> Self {
116        Self {
117            taken_time: None,
118            taken_time_source: FoldSource::Absent,
119            gps: None,
120            gps_source: FoldSource::Absent,
121            description: None,
122            favorite: false,
123            albums: Vec::new(),
124        }
125    }
126}
127
128/// One normalized import entry: the [`ImportCandidate`] the pure planner consumes plus the folded
129/// exporter [`ExtractedMetadata`] for its primary media file.
130#[derive(Debug, Clone)]
131pub struct SourceEntry {
132    /// The candidate fed verbatim to [`plan`](crate::import::plan).
133    pub candidate: ImportCandidate,
134    /// The folded out-of-band metadata for this entry's primary media file.
135    pub metadata: ExtractedMetadata,
136}
137
138impl SourceEntry {
139    /// The primary media path of this entry (the key callers look metadata up by).
140    pub fn primary_path(&self) -> &PathBuf {
141        self.candidate.primary_path()
142    }
143}
144
145/// The result of walking an export: normalized entries in a deterministic order.
146#[derive(Debug, Default, Clone)]
147pub struct ExtractedImport {
148    /// Entries, ordered deterministically (sorted by primary path) so a given export yields the
149    /// same [`ScanResult`] on every run.
150    pub entries: Vec<SourceEntry>,
151}
152
153impl ExtractedImport {
154    /// Build the [`ScanResult`] the pure [planner](crate::import::plan) consumes. This is the
155    /// only handoff into the pipeline — the adapter **feeds** the planner and never modifies it.
156    pub fn to_scan_result(&self) -> ScanResult {
157        ScanResult {
158            candidates: self.entries.iter().map(|e| e.candidate.clone()).collect(),
159        }
160    }
161
162    /// The folded exporter metadata for a media file, looked up by its primary path.
163    pub fn metadata_for(&self, primary: &Path) -> Option<&ExtractedMetadata> {
164        self.entries
165            .iter()
166            .find(|e| e.primary_path().as_path() == primary)
167            .map(|e| &e.metadata)
168    }
169}
170
171/// A third-party import source adapter — the seam every provider importer implements.
172///
173/// An implementation normalizes an exporting service's on-disk layout into `(bytes-source,
174/// extracted-metadata)` [entries](SourceEntry), folding out-of-band metadata under the precedence
175/// rule **before** the planner sees it. Implementations MUST be deterministic: the same `parts`
176/// (in any order) yield the same [`ExtractedImport`] every run.
177pub trait SourceAdapter {
178    /// The service this adapter migrates from.
179    fn provider(&self) -> ImportProvider;
180
181    /// Walk the export `parts` (one or more roots — a single export directory, or the several
182    /// extracted parts of a split archive) and produce the normalized entries. Split-archive
183    /// parts are merged: a media file in one part pairs with its exporter sidecar in another.
184    fn extract(&self, parts: &[PathBuf]) -> Result<ExtractedImport, AdapterError>;
185}