capsule_library/import/
scanner.rs1use 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
12pub 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 let mut content_id_map: HashMap<String, PathBuf> = HashMap::new();
37 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 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 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 let mut stem_candidates = group_by_stem(&remaining);
80
81 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 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 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 if (ext == "heic" || ext == "heif")
140 && let Some(ci) = extract_content_identifier(&path)
141 {
142 content_id_map.insert(ci, path.clone());
143 files.push(path);
145 continue;
146 }
147
148 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
162pub(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
176fn 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 let after = &bytes[pos + marker.len()..];
189 for start in 0..32.min(after.len()) {
191 let ch = after[start];
192 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#[cfg(test)]
212mod tests;