Skip to main content

capsule_library/import/
scanner.rs

1use std::collections::HashMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use capsule_core::domain::{DetectionMethod, MemberRole, StackType};
6use capsule_core::import::group::{group_by_stem, is_video};
7use capsule_core::import::scan::{ImportCandidate, ScanResult};
8use capsule_core::import::special::SpecialDirectoryStatus;
9use capsule_core::metadata::AssetType;
10use walkdir::WalkDir;
11
12/// Phase 1 — scan source directories and build a list of `ImportCandidate`s.
13///
14/// **Every regular file is a candidate, whatever its extension** (SSoT: thumbnails § Media Is
15/// Rawshift's — "every file is kept"). Codec coverage and extension recognition decide grouping
16/// and derivatives, never admission: a video, a HEIC, a zero-byte file or a file with an
17/// unrecognised or missing extension is backed up byte for byte like a JPEG. The only files
18/// left out are the operating system's own folder metadata (`is_os_folder_metadata`) and the
19/// contents of special directories (`.git`, DaVinci Resolve), none of which is a user original.
20///
21/// An entry the walk cannot read (a permission-denied directory, a vanished file, a missing
22/// source root) is never dropped silently: it becomes a standalone candidate the planner then
23/// reports as a `SkipError` naming the path, so a run that could not see part of its source
24/// says so.
25///
26/// Responsibilities:
27/// - Recursive walkdir traversal, skipping special directories (`.git`, DaVinci).
28/// - Live Photo pairing: HEIC with `content_identifier` XMP field + matching `.mov`.
29/// - Filename-stem grouping for RAW/JPEG pairs (delegated to `group_by_stem`).
30/// - Standalone files for everything else.
31pub fn scan(
32    source_paths: &[PathBuf],
33) -> Result<ScanResult, Box<dyn std::error::Error + Send + Sync>> {
34    let mut all_files: Vec<PathBuf> = Vec::new();
35    // content_identifier → heic_path (for Live Photo detection)
36    let mut content_id_map: HashMap<String, PathBuf> = HashMap::new();
37    // content_identifier → mov_path
38    let mut mov_ci_map: HashMap<String, PathBuf> = HashMap::new();
39
40    for source in source_paths {
41        collect_files(source, &mut all_files, &mut content_id_map, &mut mov_ci_map);
42    }
43
44    // Match Live Photo pairs: HEIC (with CI) + MOV (with same CI)
45    let mut live_photo_heics: Vec<PathBuf> = Vec::new();
46    let mut live_photo_movs: Vec<PathBuf> = Vec::new();
47    let mut live_photo_pairs: Vec<ImportCandidate> = Vec::new();
48
49    for (ci, heic) in &content_id_map {
50        if let Some(mov) = mov_ci_map.get(ci) {
51            live_photo_heics.push(heic.clone());
52            live_photo_movs.push(mov.clone());
53            live_photo_pairs.push(ImportCandidate {
54                source_paths: vec![heic.clone(), mov.clone()],
55                detected_type: AssetType::Photo,
56                stack_type: Some(StackType::LivePhoto),
57                detection_method: Some(DetectionMethod::ContentIdentifier),
58                detection_key: Some(ci.clone()),
59                members: vec![
60                    (heic.clone(), MemberRole::Primary),
61                    (mov.clone(), MemberRole::Video),
62                ],
63            });
64        }
65    }
66
67    // Remove paired files from the flat list before stem grouping
68    let paired: Vec<PathBuf> = live_photo_heics
69        .iter()
70        .chain(live_photo_movs.iter())
71        .cloned()
72        .collect();
73    let remaining: Vec<PathBuf> = all_files
74        .into_iter()
75        .filter(|p| !paired.contains(p))
76        .collect();
77
78    // Group remaining files by stem (RAW+JPEG detection, etc.)
79    let mut stem_candidates = group_by_stem(&remaining);
80
81    // Combine all candidates
82    let mut candidates = live_photo_pairs;
83    candidates.append(&mut stem_candidates);
84
85    Ok(ScanResult { candidates })
86}
87
88fn collect_files(
89    root: &Path,
90    files: &mut Vec<PathBuf>,
91    content_id_map: &mut HashMap<String, PathBuf>,
92    mov_ci_map: &mut HashMap<String, PathBuf>,
93) {
94    for entry in WalkDir::new(root).into_iter().filter_entry(|e| {
95        // Skip special directories
96        if e.file_type().is_dir()
97            && let Some(status) = SpecialDirectoryStatus::from_path(e.path())
98        {
99            match status {
100                SpecialDirectoryStatus::Git | SpecialDirectoryStatus::DavinciResolve => {
101                    return false;
102                }
103            }
104        }
105        true
106    }) {
107        let entry = match entry {
108            Ok(entry) => entry,
109            Err(error) => {
110                // Kept as a candidate so the planner reports it: a subtree the walk could not
111                // read is part of the source the user asked for, not something to skip.
112                tracing::warn!(
113                    path = ?error.path(),
114                    %error,
115                    "import scan: an entry could not be read; reporting it as an error"
116                );
117                if let Some(path) = error.path() {
118                    files.push(path.to_path_buf());
119                }
120                continue;
121            }
122        };
123        let path = entry.path().to_path_buf();
124        if !path.is_file() {
125            continue;
126        }
127        if is_os_folder_metadata(&path) {
128            tracing::trace!(path = %path.display(), "import scan: OS folder metadata left out");
129            continue;
130        }
131
132        let ext = path
133            .extension()
134            .unwrap_or_default()
135            .to_string_lossy()
136            .to_lowercase();
137
138        // For HEIC files: try to extract Apple content_identifier for Live Photo pairing
139        if (ext == "heic" || ext == "heif")
140            && let Some(ci) = extract_content_identifier(&path)
141        {
142            content_id_map.insert(ci, path.clone());
143            // Don't add to regular files yet — handle in Live Photo logic
144            files.push(path);
145            continue;
146        }
147
148        // For MOV files: try to extract content_identifier for Live Photo pairing
149        if is_video(&ext)
150            && (ext == "mov" || ext == "mp4")
151            && let Some(ci) = extract_content_identifier(&path)
152        {
153            mov_ci_map.insert(ci, path.clone());
154            files.push(path);
155            continue;
156        }
157
158        files.push(path);
159    }
160}
161
162/// Whether `path` is folder metadata an operating system writes beside a user's files, rather
163/// than a file the user put there: macOS Finder's `.DS_Store` and its AppleDouble `._*`
164/// companions, and Windows Explorer's `Thumbs.db` and `desktop.ini`. They are regenerated by
165/// the OS on demand, so leaving them out of a backup loses nothing.
166pub(crate) fn is_os_folder_metadata(path: &Path) -> bool {
167    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
168        return false;
169    };
170    name == ".DS_Store"
171        || name.starts_with("._")
172        || name.eq_ignore_ascii_case("thumbs.db")
173        || name.eq_ignore_ascii_case("desktop.ini")
174}
175
176/// Naive byte-scan for the Apple QuickTime content identifier.
177///
178/// Searches for the ASCII string `com.apple.quicktime.content.identifier`
179/// followed by a null-terminated or length-prefixed ASCII value in the file.
180/// Returns `None` if not found or unreadable.
181fn extract_content_identifier(path: &Path) -> Option<String> {
182    let bytes = fs::read(path).ok()?;
183    let marker = b"com.apple.quicktime.content.identifier";
184
185    let pos = bytes.windows(marker.len()).position(|w| w == marker)?;
186
187    // Skip past the marker and a few bytes of framing (null + length byte etc.)
188    let after = &bytes[pos + marker.len()..];
189    // Skip up to 32 bytes of framing, looking for a printable ASCII identifier
190    for start in 0..32.min(after.len()) {
191        let ch = after[start];
192        // Identifiers are typically UUID strings (hex + hyphens, 36 bytes)
193        if ch.is_ascii_alphanumeric() || ch == b'-' {
194            let end = after[start..]
195                .iter()
196                .position(|&b| !b.is_ascii_alphanumeric() && b != b'-')
197                .unwrap_or(after.len() - start)
198                + start;
199            let candidate = std::str::from_utf8(&after[start..end]).ok()?;
200            if candidate.len() >= 8 {
201                return Some(candidate.to_string());
202            }
203        }
204    }
205
206    None
207}
208
209// ── Tests ────────────────────────────────────────────────────────────────────
210
211#[cfg(test)]
212mod tests;