1use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::Arc;
10use std::time::Instant;
11
12use async_channel::{bounded, Receiver, Sender};
13use sha2::{Digest, Sha256};
14use walkdir::{DirEntry, WalkDir};
15
16use crate::db::photo_repo::{PhotoInsert, PhotoRepo};
17use crate::db::Database;
18use crate::models::MediaType;
19use crate::services::exclusions::ExclusionMatcher;
20
21pub(crate) const SUPPORTED_EXTENSIONS: &[&str] = &[
31 "jpg", "jpeg", "png", "heic", "heif", "webp", "tif", "tiff", "bmp", "gif",
34 "nef", "cr2", "cr3", "arw", "dng", "orf", "rw2", "pef", "rwl", "srw", "raf",
36 "mp4", "m4v", "mov", "webm", "mkv", "avi", "3gp", "3g2", "mts", "m2ts",
38];
39
40pub(crate) const SKIP_DIRECTORIES: &[&str] = &[
42 ".photovault",
43 ".Trash",
44 "$RECYCLE.BIN",
45 "System Volume Information",
46 ".DS_Store",
47 "Thumbs.db",
48 ".thumbnails",
49 "@eaDir", ];
51
52const MIN_FILE_SIZE: u64 = 1024;
56
57const DB_BATCH_SIZE: usize = 100;
59
60const MAX_ERROR_DETAILS: usize = 1000;
67
68const WALKER_CHANNEL_DEPTH: usize = 1000;
71
72const FAST_HASH_PREFIX_BYTES: usize = 64 * 1024;
76
77const STUB_PROGRESS_EVERY: u64 = 200;
79
80#[derive(Debug, Clone)]
82pub struct ScanProgress {
83 pub files_found: u64,
84 pub files_processed: u64,
85 pub bytes_processed: u64,
86 pub current_directory: String,
87 pub current_file: String,
88 pub errors: Vec<String>,
89 pub error_count: u64,
90 pub is_complete: bool,
91 pub elapsed_seconds: f64,
92}
93
94impl Default for ScanProgress {
95 fn default() -> Self {
96 Self {
97 files_found: 0,
98 files_processed: 0,
99 bytes_processed: 0,
100 current_directory: String::new(),
101 current_file: "Preparing...".to_string(),
102 errors: Vec::new(),
103 error_count: 0,
104 is_complete: false,
105 elapsed_seconds: 0.0,
106 }
107 }
108}
109
110#[derive(Debug, Clone)]
111pub struct ScanReport {
112 pub files_inserted: u64,
113 pub errors: Vec<String>,
114 pub error_count: u64,
115 pub elapsed_seconds: f64,
116}
117
118struct FileCandidate {
120 path: PathBuf,
121 relative_path: String,
122 file_name: String,
123 file_size: i64,
124 mtime: Option<i64>,
125 media_type: MediaType,
126}
127
128pub fn start_scan(
135 root_path: PathBuf,
136 db: Arc<tokio::sync::Mutex<Database>>,
137 cancel: Arc<AtomicBool>,
138 scan_hidden_folders: bool,
139) -> (Receiver<ScanProgress>, tokio::task::JoinHandle<ScanReport>) {
140 let (progress_tx, progress_rx) = bounded::<ScanProgress>(64);
141 let handle = tokio::task::spawn(async move {
142 let result =
143 run_scan_streaming(root_path, db, cancel, scan_hidden_folders, progress_tx).await;
144 result.unwrap_or_else(|e| ScanReport {
145 files_inserted: 0,
146 errors: vec![format!("scan failed: {e}")],
147 error_count: 1,
148 elapsed_seconds: 0.0,
149 })
150 });
151 (progress_rx, handle)
152}
153
154pub(crate) fn calculate_fast_hash<P: AsRef<Path>>(
173 path: P,
174 file_size: u64,
175 mtime: Option<i64>,
176) -> std::io::Result<String> {
177 use std::io::Read;
178
179 let mut file = std::fs::File::open(&path)?;
180 let mut buf = vec![0u8; FAST_HASH_PREFIX_BYTES];
181 let mut n = 0usize;
184 while n < buf.len() {
185 match file.read(&mut buf[n..])? {
186 0 => break,
187 read => n += read,
188 }
189 }
190
191 let mut hasher = Sha256::new();
192 hasher.update(file_size.to_le_bytes());
193 hasher.update(mtime.unwrap_or(0).to_le_bytes());
194 hasher.update(&buf[..n]);
195 Ok(format!("{:x}", hasher.finalize()))
196}
197
198async fn run_scan_streaming(
199 root_path: PathBuf,
200 db: Arc<tokio::sync::Mutex<Database>>,
201 cancel: Arc<AtomicBool>,
202 scan_hidden_folders: bool,
203 progress_tx: Sender<ScanProgress>,
204) -> Result<ScanReport, String> {
205 let start = Instant::now();
206 let (paths_tx, paths_rx) = bounded::<FileCandidate>(WALKER_CHANNEL_DEPTH);
207 let (exclusions, known_paths) = {
208 let guard = db.lock().await;
209 let exclusions = ExclusionMatcher::from_db(&guard.conn)
210 .map_err(|e| format!("failed to load folder exclusions; scan aborted: {e}"))?;
211 let known_paths = PhotoRepo::new(&guard.conn)
215 .all_file_paths()
216 .map_err(|e| format!("failed to load indexed paths; scan aborted: {e}"))?;
217 (exclusions, known_paths)
218 };
219
220 let walker_cancel = cancel.clone();
222 let walker_root = root_path.clone();
223 let walker = tokio::task::spawn_blocking(move || -> (u64, Vec<String>, u64) {
224 let mut count: u64 = 0;
225 let mut errors = Vec::new();
226 let mut error_count = 0;
227 let walker = WalkDir::new(&walker_root)
228 .follow_links(false)
229 .into_iter()
230 .filter_entry(|e| !should_skip(e, &walker_root, scan_hidden_folders, &exclusions));
231
232 for entry in walker {
233 if walker_cancel.load(Ordering::Relaxed) {
234 tracing::info!("Scan cancelled during walk");
235 break;
236 }
237 let entry = match entry {
238 Ok(entry) => entry,
239 Err(error) => {
240 error_count += 1;
241 if errors.len() < MAX_ERROR_DETAILS {
242 errors.push(format!("walk {}: {error}", walker_root.display()));
243 }
244 continue;
245 }
246 };
247 if !entry.file_type().is_file() {
248 continue;
249 }
250 if !is_supported_file(&entry) {
251 continue;
252 }
253 let relative_path = entry
254 .path()
255 .strip_prefix(&walker_root)
256 .map(crate::services::path_util::relative_path_for_storage)
257 .unwrap_or_else(|_| {
258 crate::services::path_util::relative_path_for_storage(entry.path())
259 });
260 if known_paths.contains(&relative_path) {
261 continue;
262 }
263 let media_type = media_type_for_path(entry.path()).unwrap_or_default();
264 let metadata = match entry.metadata() {
265 Ok(metadata) => metadata,
266 Err(error) => {
267 error_count += 1;
268 if errors.len() < MAX_ERROR_DETAILS {
269 errors.push(format!("metadata {}: {error}", entry.path().display()));
270 }
271 continue;
272 }
273 };
274 if metadata.len() < MIN_FILE_SIZE {
275 continue;
276 }
277
278 let mtime = metadata
279 .modified()
280 .ok()
281 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
282 .map(|d| d.as_secs() as i64);
283
284 let candidate = FileCandidate {
285 path: entry.path().to_path_buf(),
286 relative_path,
287 file_name: entry.file_name().to_string_lossy().to_string(),
288 file_size: metadata.len() as i64,
289 mtime,
290 media_type,
291 };
292
293 if paths_tx.send_blocking(candidate).is_err() {
295 break; }
297 count += 1;
298 }
299 drop(paths_tx);
300 (count, errors, error_count)
301 });
302
303 let writer_cancel = cancel.clone();
305 let writer_db = db.clone();
306 let writer_progress = progress_tx.clone();
307 let writer = tokio::task::spawn(async move {
308 let mut errors: Vec<String> = Vec::new();
309 let mut error_count: u64 = 0;
310 let mut buf: Vec<PhotoInsert> = Vec::with_capacity(DB_BATCH_SIZE);
311 let mut files_inserted: u64 = 0;
312
313 loop {
317 if writer_cancel.load(Ordering::Relaxed) {
318 break;
319 }
320
321 let Ok(candidate) = paths_rx.recv().await else {
322 break;
323 };
324
325 let hash_path = candidate.path.clone();
329 let hash_size = candidate.file_size as u64;
330 let hash_mtime = candidate.mtime;
331 let hash_result = tokio::task::spawn_blocking(move || {
332 calculate_fast_hash(&hash_path, hash_size, hash_mtime)
333 })
334 .await;
335 let hash = match hash_result {
336 Ok(Ok(h)) => h,
337 Ok(Err(e)) => {
338 error_count += 1;
339 if errors.len() < MAX_ERROR_DETAILS {
340 errors.push(format!("fast-hash {}: {e}", candidate.path.display()));
341 }
342 continue;
343 }
344 Err(e) => {
345 error_count += 1;
346 if errors.len() < MAX_ERROR_DETAILS {
347 errors.push(format!("hash worker {}: {e}", candidate.path.display()));
348 }
349 continue;
350 }
351 };
352
353 buf.push(PhotoInsert {
354 relative_path: candidate.relative_path,
355 file_name: candidate.file_name,
356 file_hash: hash,
357 file_size: candidate.file_size,
358 file_mtime: candidate.mtime,
359 date_taken: None,
361 date_taken_source: None,
362 gps_latitude: None,
363 gps_longitude: None,
364 location_city: None,
365 location_country: None,
366 camera_make: None,
367 camera_model: None,
368 iso: None,
369 aperture: None,
370 shutter_speed: None,
371 focal_length: None,
372 lens_model: None,
373 flash: None,
374 gps_altitude: None,
375 width: None,
376 height: None,
377 orientation: 1,
378 media_type: candidate.media_type,
379 duration_ms: None,
380 video_codec: None,
381 audio_codec: None,
382 frame_rate: None,
383 bitrate: None,
384 has_audio: false,
385 });
386
387 if buf.len() >= DB_BATCH_SIZE {
388 let (inserted, encountered) =
389 flush_stub_batch(&writer_db, &mut buf, &mut errors).await;
390 files_inserted += inserted;
391 error_count += encountered;
392
393 if files_inserted.is_multiple_of(STUB_PROGRESS_EVERY) {
394 let _ = writer_progress.try_send(ScanProgress {
395 files_found: files_inserted,
396 files_processed: files_inserted,
397 bytes_processed: 0,
398 current_directory: String::new(),
399 current_file: format!("Indexed {files_inserted} files…"),
400 errors: errors.clone(),
401 error_count,
402 is_complete: false,
403 elapsed_seconds: start.elapsed().as_secs_f64(),
404 });
405 }
406 }
407 }
408
409 if !buf.is_empty() {
411 let (inserted, encountered) = flush_stub_batch(&writer_db, &mut buf, &mut errors).await;
412 files_inserted += inserted;
413 error_count += encountered;
414 }
415 (files_inserted, errors, error_count)
416 });
417
418 let (total_walked, walker_errors, walker_error_count) =
419 walker.await.map_err(|e| format!("walker join: {e}"))?;
420 let (files_inserted, mut errors, writer_error_count) =
421 writer.await.map_err(|e| format!("writer join: {e}"))?;
422 errors.extend(walker_errors);
423 let error_count = walker_error_count + writer_error_count;
424 tracing::info!("Phase 1 done: walked {total_walked}, inserted {files_inserted}");
425
426 let report = ScanReport {
427 files_inserted,
428 errors,
429 error_count,
430 elapsed_seconds: start.elapsed().as_secs_f64(),
431 };
432
433 let _ = progress_tx
435 .send(ScanProgress {
436 files_found: report.files_inserted,
437 files_processed: report.files_inserted,
438 bytes_processed: 0,
439 current_directory: String::new(),
440 current_file: format!("Indexed {} files", report.files_inserted),
441 errors: report.errors.clone(),
442 error_count: report.error_count,
443 is_complete: true,
444 elapsed_seconds: report.elapsed_seconds,
445 })
446 .await;
447
448 Ok(report)
449}
450
451async fn flush_stub_batch(
460 db: &Arc<tokio::sync::Mutex<Database>>,
461 buf: &mut Vec<PhotoInsert>,
462 errors: &mut Vec<String>,
463) -> (u64, u64) {
464 let guard = db.lock().await;
465 let repo = PhotoRepo::new(&guard.conn);
466 let mut encountered = 0u64;
467 let inserted = match repo.insert_batch_stub(buf) {
468 Ok(n) => n as u64,
469 Err(e) => {
470 encountered = 1;
471 if errors.len() < MAX_ERROR_DETAILS {
472 errors.push(format!("stub batch insert: {e}"));
473 }
474 0
475 }
476 };
477 buf.clear();
478 (inserted, encountered)
479}
480
481fn should_skip(
483 entry: &DirEntry,
484 root: &Path,
485 scan_hidden_folders: bool,
486 exclusions: &ExclusionMatcher,
487) -> bool {
488 if entry.path() == root {
492 return false;
493 }
494 let file_name = entry.file_name().to_string_lossy();
495
496 if !scan_hidden_folders && file_name.starts_with('.') {
497 return true;
498 }
499
500 for skip in SKIP_DIRECTORIES {
501 if file_name == *skip {
502 return true;
503 }
504 }
505
506 exclusions.should_skip_path(root, entry.path())
507}
508
509fn is_supported_file(entry: &DirEntry) -> bool {
511 media_type_for_path(entry.path()).is_some()
512}
513
514pub fn media_type_for_path(path: &Path) -> Option<MediaType> {
515 let lower = path.extension()?.to_str()?.to_lowercase();
516 if !SUPPORTED_EXTENSIONS.contains(&lower.as_str()) {
517 return None;
518 }
519 match lower.as_str() {
520 "mp4" | "m4v" | "mov" | "webm" | "mkv" | "avi" | "3gp" | "3g2" | "mts" | "m2ts" => {
521 Some(MediaType::Video)
522 }
523 _ => Some(MediaType::Photo),
524 }
525}
526
527pub fn calculate_hash<P: AsRef<Path>>(path: P) -> std::io::Result<String> {
529 calculate_hash_cancellable(path, None)
530}
531
532pub fn calculate_hash_cancellable<P: AsRef<Path>>(
533 path: P,
534 cancel: Option<&AtomicBool>,
535) -> std::io::Result<String> {
536 use std::io::Read;
537
538 let mut file = std::fs::File::open(path)?;
539 let mut hasher = Sha256::new();
540 let mut buffer = [0u8; 65536]; loop {
543 if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
544 return Err(std::io::Error::new(
545 std::io::ErrorKind::Interrupted,
546 "hashing cancelled",
547 ));
548 }
549 let bytes_read = file.read(&mut buffer)?;
550 if bytes_read == 0 {
551 break;
552 }
553 hasher.update(&buffer[..bytes_read]);
554 }
555
556 let result = hasher.finalize();
557 Ok(format!("{:x}", result))
558}
559
560#[cfg(test)]
561mod tests {
562 use super::*;
563 use std::fs::File;
564 use std::io::Write;
565 use tempfile::tempdir;
566
567 #[test]
568 fn full_hash_honors_cancellation() {
569 let dir = tempdir().unwrap();
570 let path = dir.path().join("photo");
571 std::fs::write(&path, [7u8; 65537]).unwrap();
572 let cancel = AtomicBool::new(true);
573 assert_eq!(
574 calculate_hash_cancellable(&path, Some(&cancel))
575 .unwrap_err()
576 .kind(),
577 std::io::ErrorKind::Interrupted
578 );
579 cancel.store(false, Ordering::Relaxed);
580 assert_eq!(
581 calculate_hash_cancellable(&path, Some(&cancel)).unwrap(),
582 calculate_hash(&path).unwrap()
583 );
584 }
585
586 #[test]
587 fn test_should_skip_hidden() {
588 let temp = tempdir().unwrap();
589 let hidden = temp.path().join(".hidden");
590 std::fs::create_dir(&hidden).unwrap();
591 let exclusions = ExclusionMatcher::empty();
592
593 let walker = WalkDir::new(temp.path()).into_iter();
594 for entry in walker {
595 let entry = entry.unwrap();
596 if entry.file_name().to_string_lossy() == ".hidden" {
597 assert!(should_skip(&entry, temp.path(), false, &exclusions));
598 assert!(!should_skip(&entry, temp.path(), true, &exclusions));
599 }
600 }
601 }
602
603 #[test]
604 fn test_should_skip_excluded_folder_descendants() {
605 let temp = tempdir().unwrap();
606 let excluded = temp.path().join("Trips").join("Goa");
607 let similar = temp.path().join("Trips").join("Goa2");
608 std::fs::create_dir_all(&excluded).unwrap();
609 std::fs::create_dir_all(&similar).unwrap();
610 let exclusions = ExclusionMatcher::new(vec!["Trips/Goa".into()]);
611
612 let mut saw_excluded = false;
613 let mut saw_similar = false;
614 for entry in WalkDir::new(temp.path()).into_iter().filter_map(Result::ok) {
615 let name = entry.path();
616 if name == excluded {
617 saw_excluded = true;
618 assert!(should_skip(&entry, temp.path(), false, &exclusions));
619 }
620 if name == similar {
621 saw_similar = true;
622 assert!(!should_skip(&entry, temp.path(), false, &exclusions));
623 }
624 }
625 assert!(saw_excluded);
626 assert!(saw_similar);
627 }
628
629 #[test]
630 fn test_is_supported_file() {
631 let temp = tempdir().unwrap();
632
633 let jpg = temp.path().join("test.jpg");
634 File::create(&jpg).unwrap();
635
636 let txt = temp.path().join("test.txt");
637 File::create(&txt).unwrap();
638
639 let png = temp.path().join("test.PNG");
640 File::create(&png).unwrap();
641
642 let mp4 = temp.path().join("clip.MP4");
643 File::create(&mp4).unwrap();
644
645 let walker = WalkDir::new(temp.path()).into_iter();
646 for entry in walker {
647 let entry = entry.unwrap();
648 if !entry.file_type().is_file() {
649 continue;
650 }
651 let name = entry.file_name().to_string_lossy().to_string();
652 match name.as_str() {
653 "test.jpg" => assert!(is_supported_file(&entry)),
654 "test.txt" => assert!(!is_supported_file(&entry)),
655 "test.PNG" => assert!(is_supported_file(&entry)),
656 "clip.MP4" => {
657 assert!(is_supported_file(&entry));
658 assert_eq!(media_type_for_path(entry.path()), Some(MediaType::Video));
659 }
660 _ => {}
661 }
662 }
663 }
664
665 #[test]
666 fn test_calculate_hash() {
667 let temp = tempdir().unwrap();
668 let file_path = temp.path().join("test.bin");
669 let mut f = File::create(&file_path).unwrap();
670 f.write_all(b"hello world").unwrap();
671
672 let hash = calculate_hash(&file_path).unwrap();
673 assert_eq!(
674 hash,
675 "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
676 );
677 }
678
679 #[test]
680 fn test_min_file_size_filter() {
681 const _: () = assert!(MIN_FILE_SIZE == 1024);
682 }
683
684 #[test]
685 fn test_fast_hash_changes_with_mtime() {
686 let temp = tempdir().unwrap();
687 let file_path = temp.path().join("test_mtime.bin");
688 std::fs::write(&file_path, b"some content here").unwrap();
689
690 let hash1 = calculate_fast_hash(&file_path, 100, Some(1700000000)).unwrap();
691 let hash2 = calculate_fast_hash(&file_path, 100, Some(1700000001)).unwrap();
692 assert_ne!(hash1, hash2, "fast hash must change when mtime changes");
693 }
694
695 #[test]
696 fn test_fast_hash_changes_with_size() {
697 let temp = tempdir().unwrap();
698 let file_path = temp.path().join("test_size.bin");
699 std::fs::write(&file_path, b"same prefix data").unwrap();
700
701 let hash1 = calculate_fast_hash(&file_path, 100, Some(1700000000)).unwrap();
702 let hash2 = calculate_fast_hash(&file_path, 200, Some(1700000000)).unwrap();
703 assert_ne!(hash1, hash2, "fast hash must change when file size changes");
704 }
705
706 #[test]
707 fn test_fast_hash_stable_on_repeat() {
708 let temp = tempdir().unwrap();
709 let file_path = temp.path().join("test_stable.bin");
710 std::fs::write(&file_path, b"repeatable content").unwrap();
711
712 let hash1 = calculate_fast_hash(&file_path, 500, Some(1700000000)).unwrap();
713 let hash2 = calculate_fast_hash(&file_path, 500, Some(1700000000)).unwrap();
714 assert_eq!(hash1, hash2, "fast hash must be stable on repeat calls");
715 }
716
717 #[test]
718 fn test_fast_hash_is_plain_hex_digest() {
719 let temp = tempdir().unwrap();
724 let file_path = temp.path().join("test_prefix.bin");
725 std::fs::write(&file_path, b"check prefix").unwrap();
726
727 let hash = calculate_fast_hash(&file_path, 12, None).unwrap();
728 assert_eq!(hash.len(), 64, "SHA-256 hex digest is 64 chars");
729 assert!(
730 hash.chars().all(|c| c.is_ascii_hexdigit()),
731 "hash must be pure ASCII hex"
732 );
733 }
734}