Skip to main content

smriti/services/
duplicate_detector.rs

1//! Duplicate detection: byte-identical (SHA-256) and near-identical
2//! (perceptual DCT hash). The two passes run in sequence and emit
3//! groups with `duplicate_type = 'exact' | 'perceptual'`.
4
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
7
8use image_hasher::{HashAlg, HasherConfig};
9use rayon::prelude::*;
10use rusqlite::Connection;
11
12use crate::services::path_util::safe_join_relative;
13
14/// Perceptual hashes computed between database writes during backfill.
15const PHASH_WRITE_CHUNK: usize = 256;
16
17/// Result of duplicate detection
18#[derive(Debug, Clone)]
19pub struct DuplicateGroup {
20    /// Unique group identifier (SHA hash for exact, `phash:<hex>` for perceptual).
21    pub hash: String,
22
23    /// Photo IDs in this group
24    pub photo_ids: Vec<i64>,
25
26    /// Suggested photo ID to keep
27    pub suggested_keep_id: Option<i64>,
28
29    /// 'exact' | 'perceptual'.
30    pub duplicate_type: &'static str,
31}
32
33#[derive(Debug, Clone)]
34pub struct DuplicateProgress {
35    pub stage: &'static str,
36    pub processed: u64,
37    pub total: Option<u64>,
38    pub message: String,
39}
40
41type ExactCandidate = (i64, String, Option<String>, i64);
42
43/// Hamming-distance threshold (out of 64 bits) below which two photos
44/// are considered the same image. 4 bits ≈ 94% bit agreement — the
45/// floor for "really actually the same shot, different file":
46/// re-encoded JPEGs, stripped-EXIF copies, scale variants, watermark-
47/// added copies. The previous 6-bit threshold (91%) still flagged too
48/// many compositionally-similar but visually distinct photos as
49/// "duplicates" (same wall + same lighting → near-identical pHash but
50/// different subjects). Tighter is the right error: missing a dup is
51/// fine, false-flagging real photos as dups erodes trust in the
52/// listing. Burst-style near-dupes belong to the burst detector.
53const PHASH_HAMMING_THRESHOLD: u32 = 4;
54
55/// Duplicate detection service
56pub struct DuplicateDetector;
57
58struct PendingHashPhoto {
59    id: i64,
60    file_hash: String,
61    file_path: String,
62    orientation: i32,
63    thumbnail_path: Option<String>,
64}
65
66/// One candidate row for exact-duplicate grouping, straight from the
67/// size-bucket query.
68struct CandidateRow {
69    id: i64,
70    path: String,
71    date_taken: Option<String>,
72    file_size: i64,
73    stored_hash: Option<String>,
74}
75
76fn is_cancelled(cancel: Option<&AtomicBool>) -> bool {
77    cancel
78        .map(|flag| flag.load(Ordering::Relaxed))
79        .unwrap_or(false)
80}
81
82impl DuplicateDetector {
83    pub fn find_duplicates_cancellable(
84        conn: &Connection,
85        drive_root: &Path,
86        cancel: Option<&AtomicBool>,
87    ) -> rusqlite::Result<Vec<DuplicateGroup>> {
88        // Fast scanner hashes include file metadata, so byte-identical
89        // copies with different mtimes may not share photos.file_hash.
90        // Use file_size only to narrow candidates, then group by the true
91        // full-file SHA-256. That hash is computed once per file and cached
92        // in photos.content_hash, so repeat passes never re-read files.
93        let mut stmt = conn.prepare(
94            r#"
95            SELECT file_size, COUNT(*) as count
96            FROM photos
97            WHERE is_trashed = FALSE
98            GROUP BY file_size
99            HAVING count > 1
100            ORDER BY count DESC
101            "#,
102        )?;
103
104        let sizes: Vec<i64> = stmt
105            .query_map([], |row| row.get(0))?
106            .collect::<rusqlite::Result<Vec<_>>>()?;
107
108        let mut groups = Vec::new();
109        let mut newly_hashed: Vec<(i64, String)> = Vec::new();
110
111        for size in sizes {
112            if is_cancelled(cancel) {
113                return Ok(Vec::new());
114            }
115            let mut photo_stmt = conn.prepare(
116                r#"
117                SELECT id, file_path, date_taken, file_size, content_hash
118                FROM photos
119                WHERE file_size = ?1 AND is_trashed = FALSE
120                ORDER BY date_taken ASC, file_path ASC
121                "#,
122            )?;
123
124            let photos: Vec<CandidateRow> = photo_stmt
125                .query_map([size], |row| {
126                    Ok(CandidateRow {
127                        id: row.get(0)?,
128                        path: row.get(1)?,
129                        date_taken: row.get(2)?,
130                        file_size: row.get(3)?,
131                        stored_hash: row.get(4)?,
132                    })
133                })?
134                .collect::<rusqlite::Result<Vec<_>>>()?;
135
136            if photos.len() < 2 {
137                continue;
138            }
139
140            let mut by_full_hash: std::collections::HashMap<String, Vec<ExactCandidate>> =
141                std::collections::HashMap::new();
142            for CandidateRow {
143                id,
144                path,
145                date_taken,
146                file_size,
147                stored_hash,
148            } in photos
149            {
150                let full_hash = if let Some(hash) = stored_hash {
151                    hash
152                } else {
153                    let Ok(abs) = safe_join_relative(drive_root, &path) else {
154                        continue;
155                    };
156                    let Ok(full_hash) =
157                        crate::services::scanner::calculate_hash_cancellable(&abs, cancel)
158                    else {
159                        continue;
160                    };
161                    newly_hashed.push((id, full_hash.clone()));
162                    full_hash
163                };
164                by_full_hash
165                    .entry(full_hash)
166                    .or_default()
167                    .push((id, path, date_taken, file_size));
168            }
169
170            for (hash, photos) in by_full_hash {
171                if photos.len() < 2 {
172                    continue;
173                }
174                let photo_ids: Vec<i64> = photos.iter().map(|(id, _, _, _)| *id).collect();
175                let suggested_keep_id = Self::suggest_keep(&photos);
176
177                groups.push(DuplicateGroup {
178                    hash,
179                    photo_ids,
180                    suggested_keep_id,
181                    duplicate_type: "exact",
182                });
183            }
184        }
185
186        // Persist freshly computed hashes so future passes skip the reads.
187        if !newly_hashed.is_empty() && !is_cancelled(cancel) {
188            let tx = conn.unchecked_transaction()?;
189            {
190                let mut update = tx.prepare(
191                    "UPDATE photos SET content_hash = ?2 WHERE id = ?1 AND content_hash IS NULL",
192                )?;
193                for (id, hash) in &newly_hashed {
194                    update.execute(rusqlite::params![id, hash])?;
195                }
196            }
197            tx.commit()?;
198        }
199
200        if is_cancelled(cancel) {
201            return Ok(Vec::new());
202        }
203        groups.sort_by_key(|g| std::cmp::Reverse(g.photo_ids.len()));
204        Ok(groups)
205    }
206
207    /// Find perceptually-similar duplicate groups (re-edits, re-saves,
208    /// quality-adjusted exports). Computes phash on demand for any
209    /// photo where it's NULL and persists into `photos.phash`, then
210    /// groups by Hamming distance ≤ 10 across the 64-bit hashes.
211    ///
212    /// Excludes photos already grouped as exact duplicates so the UI
213    /// doesn't show the same pair twice.
214    pub fn find_perceptual_duplicates(
215        conn: &Connection,
216        drive_root: &Path,
217        exclude_ids: &std::collections::HashSet<i64>,
218    ) -> rusqlite::Result<Vec<DuplicateGroup>> {
219        Self::find_perceptual_duplicates_with_progress(conn, drive_root, exclude_ids, None, |_| {})
220    }
221
222    pub fn find_perceptual_duplicates_with_progress(
223        conn: &Connection,
224        drive_root: &Path,
225        exclude_ids: &std::collections::HashSet<i64>,
226        cancel: Option<&AtomicBool>,
227        mut progress: impl FnMut(DuplicateProgress),
228    ) -> rusqlite::Result<Vec<DuplicateGroup>> {
229        // Backfill phash for any non-trashed photo that doesn't yet
230        // have one. Prefer the DB thumbnail path, then known thumbnail
231        // tiers, then the original file so duplicate detection is not
232        // coupled to a particular cache size.
233        Self::backfill_phashes(conn, drive_root, cancel, &mut progress)?;
234        if is_cancelled(cancel) {
235            return Ok(Vec::new());
236        }
237
238        // Pull (id, phash, file_path, date_taken, file_size) for
239        // photos with non-null phash that aren't already in an exact
240        // group. file_path / size feed `suggest_keep`.
241        let mut stmt = conn.prepare(
242            r#"
243            SELECT id, phash, file_path, date_taken, file_size
244            FROM photos
245            WHERE is_trashed = FALSE AND phash IS NOT NULL
246            "#,
247        )?;
248        let rows: Vec<(i64, i64, String, Option<String>, i64)> = stmt
249            .query_map([], |r| {
250                Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))
251            })?
252            .collect::<rusqlite::Result<Vec<_>>>()?
253            .into_iter()
254            .filter(|row| !exclude_ids.contains(&row.0))
255            .collect();
256
257        if rows.len() < 2 {
258            return Ok(Vec::new());
259        }
260        progress(DuplicateProgress {
261            stage: "perceptual-index",
262            processed: 0,
263            total: Some(rows.len() as u64),
264            message: format!("indexing {} visual fingerprints", rows.len()),
265        });
266
267        // Candidate generation uses five disjoint pHash bands. With a
268        // threshold of four bit differences across the whole 64-bit
269        // hash, the pigeonhole principle guarantees that any valid
270        // match has at least one identical band. That avoids the old
271        // O(n^2) full comparison while preserving recall for the
272        // configured threshold.
273        fn find(p: &mut [usize], mut x: usize) -> usize {
274            while p[x] != x {
275                p[x] = p[p[x]];
276                x = p[x];
277            }
278            x
279        }
280        let n = rows.len();
281        let phashes: Vec<u64> = rows.iter().map(|r| r.1 as u64).collect();
282        let mut parent: Vec<usize> = (0..n).collect();
283        let mut representatives = std::collections::HashMap::new();
284        const BANDS: [(u32, u32); 5] = [(0, 13), (13, 13), (26, 13), (39, 13), (52, 12)];
285        let mut buckets: std::collections::HashMap<(usize, u64), Vec<usize>> =
286            std::collections::HashMap::with_capacity(n * BANDS.len());
287        for (idx, hash) in phashes.iter().copied().enumerate() {
288            if is_cancelled(cancel) {
289                return Ok(Vec::new());
290            }
291            if let Some(&representative) = representatives.get(&hash) {
292                parent[idx] = representative;
293                continue;
294            }
295            representatives.insert(hash, idx);
296            for (band_idx, (shift, width)) in BANDS.iter().copied().enumerate() {
297                let mask = (1u64 << width) - 1;
298                buckets
299                    .entry((band_idx, (hash >> shift) & mask))
300                    .or_default()
301                    .push(idx);
302            }
303        }
304
305        progress(DuplicateProgress {
306            stage: "perceptual-compare",
307            processed: 0,
308            total: Some(buckets.len() as u64),
309            message: format!("checking {} candidate buckets", buckets.len()),
310        });
311
312        let mut matches = 0usize;
313        let total_buckets = buckets.len() as u64;
314        let tick = total_buckets.div_ceil(40).max(1_000);
315        for (bucket_idx, ((band_idx, _), members)) in buckets.into_iter().enumerate() {
316            if is_cancelled(cancel) {
317                return Ok(Vec::new());
318            }
319            if members.len() > 1 {
320                for i in 0..members.len() {
321                    if is_cancelled(cancel) {
322                        return Ok(Vec::new());
323                    }
324                    for j in (i + 1)..members.len() {
325                        if j % 256 == 0 && is_cancelled(cancel) {
326                            return Ok(Vec::new());
327                        }
328                        let a_idx = members[i].min(members[j]);
329                        let b_idx = members[i].max(members[j]);
330                        // Compare a pair only in its first shared band, without
331                        // retaining a potentially quadratic set of seen pairs.
332                        if BANDS[..band_idx].iter().any(|&(shift, width)| {
333                            ((phashes[a_idx] ^ phashes[b_idx]) >> shift) & ((1u64 << width) - 1)
334                                == 0
335                        }) {
336                            continue;
337                        }
338                        let dist = (phashes[a_idx] ^ phashes[b_idx]).count_ones();
339                        if dist <= PHASH_HAMMING_THRESHOLD {
340                            let ra = find(&mut parent, a_idx);
341                            let rb = find(&mut parent, b_idx);
342                            if ra != rb {
343                                parent[ra] = rb;
344                            }
345                            matches += 1;
346                        }
347                    }
348                }
349            }
350            let processed = (bucket_idx + 1) as u64;
351            if processed.is_multiple_of(tick) || processed == total_buckets {
352                progress(DuplicateProgress {
353                    stage: "perceptual-compare",
354                    processed,
355                    total: Some(total_buckets),
356                    message: format!("{} visual matches", matches),
357                });
358            }
359        }
360        if is_cancelled(cancel) {
361            return Ok(Vec::new());
362        }
363
364        let mut groups_map: std::collections::HashMap<usize, Vec<usize>> =
365            std::collections::HashMap::new();
366        for i in 0..rows.len() {
367            let r = find(&mut parent, i);
368            groups_map.entry(r).or_default().push(i);
369        }
370
371        let mut groups = Vec::new();
372        for (_root, members) in groups_map {
373            if members.len() < 2 {
374                continue;
375            }
376            let photo_quad: Vec<(i64, String, Option<String>, i64)> = members
377                .iter()
378                .map(|&m| (rows[m].0, rows[m].2.clone(), rows[m].3.clone(), rows[m].4))
379                .collect();
380            let suggested_keep_id = Self::suggest_keep(&photo_quad);
381            // Components are transitively connected; their endpoints need not
382            // be within the pairwise threshold. Use the first member as a key.
383            let phash_key = format!("phash:{:016x}", rows[members[0]].1 as u64);
384            groups.push(DuplicateGroup {
385                hash: phash_key,
386                photo_ids: photo_quad.into_iter().map(|(id, _, _, _)| id).collect(),
387                suggested_keep_id,
388                duplicate_type: "perceptual",
389            });
390        }
391        Ok(groups)
392    }
393
394    fn backfill_phashes(
395        conn: &Connection,
396        drive_root: &Path,
397        cancel: Option<&AtomicBool>,
398        progress: &mut impl FnMut(DuplicateProgress),
399    ) -> rusqlite::Result<()> {
400        let mut stmt = conn.prepare(
401            "SELECT id, file_hash, file_path, orientation, thumbnail_path
402             FROM photos
403             WHERE is_trashed = FALSE AND media_type = 'photo' AND phash IS NULL",
404        )?;
405        let pending: Vec<PendingHashPhoto> = stmt
406            .query_map([], |r| {
407                Ok(PendingHashPhoto {
408                    id: r.get(0)?,
409                    file_hash: r.get(1)?,
410                    file_path: r.get(2)?,
411                    orientation: r.get::<_, Option<i32>>(3)?.unwrap_or(1),
412                    thumbnail_path: r.get(4)?,
413                })
414            })?
415            .collect::<rusqlite::Result<Vec<_>>>()?;
416        if pending.is_empty() {
417            return Ok(());
418        }
419        let total = pending.len() as u64;
420        progress(DuplicateProgress {
421            stage: "perceptual-hash",
422            processed: 0,
423            total: Some(total),
424            message: format!("building visual fingerprints for {} photos", total),
425        });
426
427        let processed = AtomicU64::new(0);
428        let mut ready = 0usize;
429
430        // Chunked so each chunk's fingerprints are saved as soon as they
431        // are computed: cancelling (or closing the app) keeps the work done
432        // so far, and progress moves during long first-run backfills.
433        for chunk in pending.chunks(PHASH_WRITE_CHUNK) {
434            if is_cancelled(cancel) {
435                break;
436            }
437            let computed: Vec<(i64, i64)> = chunk
438                .par_iter()
439                .filter_map(|photo| {
440                    if is_cancelled(cancel) {
441                        return None;
442                    }
443                    let (source, apply_orientation) = Self::phash_source_path(drive_root, photo)?;
444                    let result = match Self::compute_phash(
445                        &source,
446                        apply_orientation.then_some(photo.orientation),
447                    ) {
448                        Ok(phash) => Some((photo.id, phash)),
449                        Err(e) => {
450                            tracing::trace!("phash skip {}: {}", source.display(), e);
451                            None
452                        }
453                    };
454                    processed.fetch_add(1, Ordering::Relaxed);
455                    result
456                })
457                .collect();
458
459            let tx = conn.unchecked_transaction()?;
460            {
461                let mut update = tx.prepare("UPDATE photos SET phash = ?2 WHERE id = ?1")?;
462                for (id, phash) in &computed {
463                    update.execute(rusqlite::params![id, phash])?;
464                }
465            }
466            tx.commit()?;
467            ready += computed.len();
468            progress(DuplicateProgress {
469                stage: "perceptual-hash",
470                processed: processed.load(Ordering::Relaxed),
471                total: Some(total),
472                message: format!("{ready} visual fingerprints ready"),
473            });
474        }
475        if ready > 0 {
476            tracing::info!("Backfilled phash for {ready} photos");
477        }
478        Ok(())
479    }
480
481    fn phash_source_path(drive_root: &Path, photo: &PendingHashPhoto) -> Option<(PathBuf, bool)> {
482        let mut candidates = Vec::with_capacity(5);
483        if let Some(path) = &photo.thumbnail_path {
484            if let Ok(path) = crate::services::path_util::safe_join_relative(drive_root, path) {
485                candidates.push((path, false));
486            }
487        }
488
489        let subdir = &photo.file_hash[..2.min(photo.file_hash.len())];
490        for size in ["small", "medium", "large"] {
491            candidates.push((
492                crate::services::cache_location::thumbnails_dir(drive_root)
493                    .join(size)
494                    .join("v2")
495                    .join(subdir)
496                    .join(format!("{}.jpg", photo.file_hash)),
497                false,
498            ));
499        }
500
501        if let Ok(path) =
502            crate::services::path_util::safe_join_relative(drive_root, &photo.file_path)
503        {
504            candidates.push((path, true));
505        }
506        candidates.into_iter().find(|(p, _)| p.exists())
507    }
508
509    fn compute_phash(path: &Path, orientation: Option<i32>) -> Result<i64, String> {
510        let img = crate::services::image_io::open_image(path)?;
511        let img = match orientation {
512            Some(o) => crate::services::image_utils::apply_exif_orientation(img, o),
513            None => img,
514        };
515        let hasher = HasherConfig::new()
516            .hash_alg(HashAlg::DoubleGradient)
517            .hash_size(8, 8)
518            .to_hasher();
519        let h = hasher.hash_image(&img);
520        let bytes = h.as_bytes();
521        let mut buf = [0u8; 8];
522        let n = bytes.len().min(8);
523        buf[..n].copy_from_slice(&bytes[..n]);
524        Ok(i64::from_le_bytes(buf))
525    }
526
527    /// Suggest which photo to keep from a duplicate group
528    ///
529    /// Priority:
530    /// 1. Prefer paths NOT containing "backup", "copy", "old", "duplicate"
531    ///    (as whole words — see `has_bad_token`)
532    /// 2. Prefer larger file size
533    /// 3. Prefer shortest path (better organized)
534    /// 4. Prefer oldest by date_taken (stable tie-break via query order)
535    fn suggest_keep(photos: &[(i64, String, Option<String>, i64)]) -> Option<i64> {
536        if photos.is_empty() {
537            return None;
538        }
539
540        let bad_folder_patterns = ["backup", "copy", "old", "duplicate", "temp", "tmp"];
541
542        // Score each photo (lower bad-pattern score is better, larger size is better)
543        let mut scored: Vec<(i64, i32, i64, usize)> = photos
544            .iter()
545            .map(|(id, path, _date, size)| {
546                let mut bad_score = 0i32;
547
548                // Penalize bad folder names
549                for pattern in &bad_folder_patterns {
550                    if Self::has_bad_token(path, pattern) {
551                        bad_score += 100;
552                    }
553                }
554
555                (*id, bad_score, *size, path.len())
556            })
557            .collect();
558
559        // Stable sort preserves original order (oldest first from query) when keys are equal.
560        scored.sort_by(|a, b| {
561            a.1.cmp(&b.1) // fewer bad-pattern penalties first
562                .then_with(|| b.2.cmp(&a.2)) // larger file first
563                .then_with(|| a.3.cmp(&b.3)) // shorter path first
564        });
565
566        scored.first().map(|(id, _, _, _)| *id)
567    }
568
569    /// True when `pattern` appears in `path` as a whole token (case-
570    /// insensitive, split on non-alphanumeric characters). Substring
571    /// matching penalized "golden" and "Gold Coast" for containing "old",
572    /// which pushed the keep-suggestion toward the wrong copy.
573    fn has_bad_token(path: &str, pattern: &str) -> bool {
574        path.to_lowercase()
575            .split(|c: char| !c.is_ascii_alphanumeric())
576            .any(|token| token == pattern)
577    }
578
579    /// Wasted bytes across the duplicate listing.
580    ///
581    /// Counts every detected duplicate group — both byte-exact dupes
582    /// (same file_hash) AND perceptual ones (pHash match). The earlier
583    /// version of this function only summed exact matches, which on a
584    /// perceptual-only library reported "0 MB potentially wasted" even
585    /// when the listing had dozens of groups. Now: walk the
586    /// duplicate_groups table directly and sum (total_size - largest)
587    /// per group, since the user's win is keeping one copy and
588    /// trashing the rest.
589    pub fn calculate_wasted_space(conn: &Connection) -> rusqlite::Result<u64> {
590        let wasted: i64 = conn.query_row(
591            r#"
592            SELECT COALESCE(SUM(total_size - max_size), 0)
593              FROM (
594                SELECT SUM(p.file_size) AS total_size,
595                       MAX(p.file_size) AS max_size
596                  FROM duplicate_groups g
597                  JOIN duplicate_group_members m ON m.group_id = g.id
598                  JOIN photos p ON p.id = m.photo_id
599                 WHERE p.is_trashed = FALSE
600              GROUP BY g.id
601                HAVING COUNT(*) > 1
602              )
603            "#,
604            [],
605            |row| row.get(0),
606        )?;
607
608        Ok(wasted.max(0) as u64)
609    }
610}
611
612#[cfg(test)]
613mod tests {
614    use super::*;
615    use crate::db::schema::create_schema;
616    use image::{Rgb, RgbImage};
617    use rusqlite::Connection;
618    use tempfile::tempdir;
619
620    #[test]
621    fn test_suggest_keep_prefers_good_paths() {
622        let photos = vec![
623            (1, "/Photos/backup/image.jpg".to_string(), None, 1000),
624            (2, "/Photos/2019/image.jpg".to_string(), None, 1000),
625            (3, "/Photos/old/copy/image.jpg".to_string(), None, 1000),
626        ];
627
628        let suggested = DuplicateDetector::suggest_keep(&photos);
629
630        // Should prefer ID 2 (no bad patterns, shorter path)
631        assert_eq!(suggested, Some(2));
632    }
633
634    #[test]
635    fn test_suggest_keep_prefers_shorter_path() {
636        let photos = vec![
637            (
638                1,
639                "/Photos/2019/March/Trip/image.jpg".to_string(),
640                None,
641                1000,
642            ),
643            (2, "/Photos/image.jpg".to_string(), None, 1000),
644        ];
645
646        let suggested = DuplicateDetector::suggest_keep(&photos);
647
648        // Should prefer ID 2 (shorter path)
649        assert_eq!(suggested, Some(2));
650    }
651
652    #[test]
653    fn test_suggest_keep_penalties_match_whole_tokens_only() {
654        // "golden" must not trip the "old" penalty.
655        let photos = vec![
656            (1, "/Photos/golden/image.jpg".to_string(), None, 1000),
657            (2, "/Photos/old/image.jpg".to_string(), None, 1000),
658        ];
659        assert_eq!(DuplicateDetector::suggest_keep(&photos), Some(1));
660
661        // Hyphenated, underscored and dotted tokens still match.
662        let photos = vec![
663            (1, "/Photos/old-copies/image.jpg".to_string(), None, 1000),
664            (2, "/Photos/2019/image.jpg".to_string(), None, 1000),
665        ];
666        assert_eq!(DuplicateDetector::suggest_keep(&photos), Some(2));
667
668        let photos = vec![
669            (1, "/Photos/vacation.old/photo.jpg".to_string(), None, 1000),
670            (2, "/Photos/vacation/photo.jpg".to_string(), None, 1000),
671        ];
672        assert_eq!(DuplicateDetector::suggest_keep(&photos), Some(2));
673    }
674
675    #[test]
676    fn exact_duplicates_use_full_file_hash_not_scanner_fast_hash() {
677        let temp = tempdir().unwrap();
678        let conn = Connection::open_in_memory().unwrap();
679        create_schema(&conn).unwrap();
680        std::fs::create_dir_all(temp.path().join("photos")).unwrap();
681        std::fs::write(temp.path().join("photos/a.jpg"), b"identical bytes").unwrap();
682        std::fs::write(temp.path().join("photos/a-copy.jpg"), b"identical bytes").unwrap();
683
684        conn.execute(
685            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, is_trashed)
686             VALUES
687             (1, 'photos/a.jpg', 'a.jpg', 'fast-hash-a', 15, FALSE),
688             (2, 'photos/a-copy.jpg', 'a-copy.jpg', 'fast-hash-b', 15, FALSE)",
689            [],
690        )
691        .unwrap();
692
693        let groups =
694            DuplicateDetector::find_duplicates_cancellable(&conn, temp.path(), None).unwrap();
695
696        assert_eq!(groups.len(), 1);
697        assert_eq!(groups[0].duplicate_type, "exact");
698        let mut ids = groups[0].photo_ids.clone();
699        ids.sort_unstable();
700        assert_eq!(ids, vec![1, 2]);
701
702        // The pass must cache the full hash so later runs skip re-reading.
703        let content_hashed: i64 = conn
704            .query_row(
705                "SELECT COUNT(*) FROM photos WHERE content_hash IS NOT NULL",
706                [],
707                |r| r.get(0),
708            )
709            .unwrap();
710        assert_eq!(content_hashed, 2);
711        assert_eq!(groups[0].hash, {
712            let mut hashes: Vec<String> = conn
713                .prepare("SELECT content_hash FROM photos ORDER BY id")
714                .unwrap()
715                .query_map([], |r| r.get(0))
716                .unwrap()
717                .collect::<rusqlite::Result<Vec<_>>>()
718                .unwrap();
719            hashes.sort();
720            hashes.dedup();
721            hashes[0].clone()
722        });
723    }
724
725    #[test]
726    fn perceptual_duplicates_use_medium_thumbnail_when_small_is_missing() {
727        let temp = tempdir().unwrap();
728        let conn = Connection::open_in_memory().unwrap();
729        create_schema(&conn).unwrap();
730
731        insert_photo_with_thumb(
732            &conn,
733            temp.path(),
734            1,
735            "photos/a.jpg",
736            "aa11111111111111111111111111111111111111111111111111111111111111",
737        );
738        insert_photo_with_thumb(
739            &conn,
740            temp.path(),
741            2,
742            "exports/a-copy.jpg",
743            "bb22222222222222222222222222222222222222222222222222222222222222",
744        );
745
746        let groups =
747            DuplicateDetector::find_perceptual_duplicates(&conn, temp.path(), &Default::default())
748                .unwrap();
749
750        assert_eq!(groups.len(), 1);
751        assert_eq!(groups[0].duplicate_type, "perceptual");
752        assert_eq!(groups[0].photo_ids.len(), 2);
753
754        let phash_count: i64 = conn
755            .query_row(
756                "SELECT COUNT(*) FROM photos WHERE phash IS NOT NULL",
757                [],
758                |r| r.get(0),
759            )
760            .unwrap();
761        assert_eq!(phash_count, 2);
762    }
763
764    #[test]
765    fn perceptual_duplicates_fall_back_to_original_file() {
766        let temp = tempdir().unwrap();
767        let conn = Connection::open_in_memory().unwrap();
768        create_schema(&conn).unwrap();
769
770        write_test_image(&temp.path().join("photos/a.jpg"));
771        write_test_image(&temp.path().join("exports/a-copy.jpg"));
772        conn.execute(
773            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, media_type, is_trashed)
774             VALUES
775             (1, 'photos/a.jpg', 'a.jpg', 'hash-a', 100, 'photo', 0),
776             (2, 'exports/a-copy.jpg', 'a-copy.jpg', 'hash-b', 100, 'photo', 0)",
777            [],
778        )
779        .unwrap();
780
781        let groups =
782            DuplicateDetector::find_perceptual_duplicates(&conn, temp.path(), &Default::default())
783                .unwrap();
784
785        assert_eq!(groups.len(), 1);
786        assert_eq!(groups[0].photo_ids.len(), 2);
787    }
788
789    fn insert_photo_with_thumb(
790        conn: &Connection,
791        drive_root: &Path,
792        id: i64,
793        file_path: &str,
794        file_hash: &str,
795    ) {
796        let subdir = &file_hash[..2];
797        let rel_thumb = format!(
798            ".photovault/thumbnails/medium/v2/{}/{}.jpg",
799            subdir, file_hash
800        );
801        write_test_image(&drive_root.join(&rel_thumb));
802        conn.execute(
803            "INSERT INTO photos
804             (id, file_path, file_name, file_hash, file_size, media_type, thumbnail_path, is_trashed)
805             VALUES (?1, ?2, ?3, ?4, 100, 'photo', ?5, 0)",
806            rusqlite::params![id, file_path, file_path, file_hash, rel_thumb],
807        )
808        .unwrap();
809    }
810
811    fn write_test_image(path: &Path) {
812        if let Some(parent) = path.parent() {
813            std::fs::create_dir_all(parent).unwrap();
814        }
815        let mut img = RgbImage::new(64, 64);
816        for y in 0..64 {
817            for x in 0..64 {
818                let color = if x < 32 {
819                    Rgb([220, 40, 40])
820                } else if y < 32 {
821                    Rgb([40, 180, 80])
822                } else {
823                    Rgb([40, 80, 220])
824                };
825                img.put_pixel(x, y, color);
826            }
827        }
828        img.save(path).unwrap();
829    }
830}