diff --git a/CHANGELOG.md b/CHANGELOG.md index c9ccf39..4cf1c67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,40 @@ All notable changes to StorageMaster are documented here. ## [Unreleased] +### Added + +- **The Duplicates page says why a selected file was not deleted.** After a + deletion, a warning lists every selected file that is still in place, with the + reason: it changed after the analysis, it could not be read again, it no longer + matches the file being kept, Windows refused (for example because it is open + in another program), Windows cannot recycle it there, the file being kept could + not be verified, or the scan recorded no stable identity for it. Before, the + status line only showed a lower count and the file stayed listed. In English, + German and Spanish. +- **Items the Recycle Bin refused get a second question.** Recycle Bin mode still + never deletes permanently on its own. Duplicates, Cleanup, Smart Cleaner and the + Results page now follow a refusal with "Delete these N item(s) permanently?", + listing the items, with No as the default. Only a yes deletes them, through the + same checks as any other deletion, and nothing that was not listed. Scheduled + cleanup has no one to ask and keeps the refusal. + +### Changed + +- **Hard links count once in sizes.** A file with several hard links is one file + on disk, but every name added its size to folder, category and scan totals. + Windows links most of WinSxS this way, so a system drive looked fuller than it + is. Every name is still listed with its own size; only the first one a scan + reaches adds to the totals. This applies to new scans: comparing one with an + older scan shows such folders shrinking once. Database schema v16. +- **Image duplicates are decoded by Windows.** The perceptual image hash and the + duplicate preview now use the Windows Imaging Component, the decoders File + Explorer uses, which Windows Update keeps patched. That removes ImageSharp + 3.1.12 and its five security advisories (the fix exists only in 4.x, which needs + a commercial license key). Formats Windows has a codec for, such as HEIC with the + HEIF extension, now work. Video frames come out of FFmpeg as raw grey pixels and + need no decoder. Image and video fingerprints are recomputed on the next + analysis. + ### Fixed - **Recycle Bin mode could delete files permanently.** Windows has no Recycle Bin diff --git a/README.md b/README.md index 5ceb8b9..7f7c12b 100644 --- a/README.md +++ b/README.md @@ -321,8 +321,8 @@ Schema migrations run on the first database access after an upgrade, each level sqlite3 "$env:LOCALAPPDATA\StorageMaster\storagemaster.db" "SELECT MAX(Version) FROM SchemaVersion;" ``` - -The expected value is `DatabaseSchema.CurrentVersion` for the build you are running — schema v15 at the time of writing. A lower number means migration has not run yet; it happens on first database access after an upgrade, not at install time. + +The expected value is `DatabaseSchema.CurrentVersion` for the build you are running — schema v16 at the time of writing. A lower number means migration has not run yet; it happens on first database access after an upgrade, not at install time. Uninstall keeps `%LOCALAPPDATA%\StorageMaster` by default, so the database and settings survive reinstall/upgrade cycles. diff --git a/docs/public/ARCHITECTURE.md b/docs/public/ARCHITECTURE.md index 1b17b8e..84f6ce2 100644 --- a/docs/public/ARCHITECTURE.md +++ b/docs/public/ARCHITECTURE.md @@ -1,9 +1,9 @@ # StorageMaster — Architecture Overview - + > **Version:** 2.2.1 | **Current-state review:** 2026-08-18 | **Framework:** .NET 8 / WinUI 3 / Windows App SDK 1.6 -> **Current-state note:** StorageMaster uses schema v15, independent pooled SQLite connection leases, persisted scan-time file identity, a managed/Rust scanner boundary, dedicated duplicate recovery, and fail-closed deletion guards. `DatabaseSchema.CurrentVersion` is authoritative for the schema number; a test asserts this document agrees with it. See `RELIABILITY_AUDIT_2026-08-18.md` for verified hardening and remaining limits (that audit is a dated snapshot and describes the schema as of v12). +> **Current-state note:** StorageMaster uses schema v16, independent pooled SQLite connection leases, persisted scan-time file identity, a managed/Rust scanner boundary, dedicated duplicate recovery, and fail-closed deletion guards. `DatabaseSchema.CurrentVersion` is authoritative for the schema number; a test asserts this document agrees with it. See `RELIABILITY_AUDIT_2026-08-18.md` for verified hardening and remaining limits (that audit is a dated snapshot and describes the schema as of v12). --- @@ -137,7 +137,7 @@ Pure SQLite persistence: | `CleanupLogRepository` | Append-only audit log | | `SettingsRepository` | JSON-serialized `AppSettings` as a key-value row | -Schema v8 adds `DuplicateOperationJournal`; v9 adds generic-quarantine restore support; v10 repairs the quarantine-member foreign key; v11 normalizes folder identity and collapses Windows case variants conservatively; v12 persists nullable volume/file identity for scan rows; v13 materializes `FolderEntries.ParentNormalizedPath` plus a `(SessionId, ParentNormalizedPath, TotalSizeBytes DESC)` index so parent/child lookups stop deriving the relationship inside the predicate; v14 adds `ScanSessions.OwnerProcessId` / `OwnerProcessStartedUtc` so a session left `Running` by a crash can be told apart from a live scan; v15 indexes the `FileEntries(Id)` cascade referrers (`DuplicateGroupMembers`, `DuplicateGroups`, `DuplicateErrors`, `DuplicateSignatures`) and adds `DuplicateErrors(RunId, FileEntryId)`. +Schema v8 adds `DuplicateOperationJournal`; v9 adds generic-quarantine restore support; v10 repairs the quarantine-member foreign key; v11 normalizes folder identity and collapses Windows case variants conservatively; v12 persists nullable volume/file identity for scan rows; v13 materializes `FolderEntries.ParentNormalizedPath` plus a `(SessionId, ParentNormalizedPath, TotalSizeBytes DESC)` index so parent/child lookups stop deriving the relationship inside the predicate; v14 adds `ScanSessions.OwnerProcessId` / `OwnerProcessStartedUtc` so a session left `Running` by a crash can be told apart from a live scan; v15 indexes the `FileEntries(Id)` cascade referrers (`DuplicateGroupMembers`, `DuplicateGroups`, `DuplicateErrors`, `DuplicateSignatures`) and adds `DuplicateErrors(RunId, FileEntryId)`; v16 adds `FileEntries.IsAdditionalHardLink`, set on every name of a hard-linked file after the first the scan reached, so the category breakdown counts the shared data once (folder and session totals already skip it during the scan). Historical identity-less rows remain readable for analysis but cannot authorize scan-backed deletion until rescanned. Duplicate deletion writes intent before filesystem operations and records final state afterward, so interrupted or partial duplicate operations can be inspected after restart. @@ -384,7 +384,7 @@ SmartCleanerService.CleanAsync(groups, method, progress) ## 8. Database architecture -### Schema (v15 current) +### Schema (v16 current) ```sql SchemaVersion (Version INTEGER, AppliedUtc TEXT) @@ -399,6 +399,7 @@ FileEntries (Id PK, SessionId FK→CASCADE, FullPath, FileName, Extension, Attributes, Category, IsReparsePoint, NormalizedFullPath NULL, IdentityVolumeSerial NULL, IdentityFileIndex NULL, + IsAdditionalHardLink, UNIQUE(SessionId, NormalizedFullPath)) FolderEntries (Id PK, SessionId FK→CASCADE, FullPath, NormalizedFullPath, diff --git a/docs/public/CODEMAP.md b/docs/public/CODEMAP.md index 7aa2ec9..330bfb8 100644 --- a/docs/public/CODEMAP.md +++ b/docs/public/CODEMAP.md @@ -1,10 +1,10 @@ # StorageMaster — Codemap - + > **Version:** 2.2.1 | **Current-state review:** 2026-08-18 > High-level source map for major files, types, methods, and database tables. Source remains authoritative for exhaustive membership. -> **Current-state note:** current source uses schema v15, independent SQLite connection leases, exact UTC timestamp reads, persisted scan-time file identity, indexed folder parent/child lookups, scan-session ownership with startup recovery, managed/Turbo persistence hardening, dedicated duplicate deletion/recovery, fail-closed path/snapshot checks, and strengthened release gates. `DatabaseSchema.CurrentVersion` is authoritative for the schema number. See `RELIABILITY_AUDIT_2026-08-18.md` for evidence and limits as of that dated audit (which describes the schema at v12). +> **Current-state note:** current source uses schema v16, independent SQLite connection leases, exact UTC timestamp reads, persisted scan-time file identity, indexed folder parent/child lookups, scan-session ownership with startup recovery, managed/Turbo persistence hardening, dedicated duplicate deletion/recovery, fail-closed path/snapshot checks, and strengthened release gates. `DatabaseSchema.CurrentVersion` is authoritative for the schema number. See `RELIABILITY_AUDIT_2026-08-18.md` for evidence and limits as of that dated audit (which describes the schema at v12). --- @@ -56,7 +56,7 @@ **Project file:** `src/StorageMaster.Core/StorageMaster.Core.csproj` **Target:** `net8.0` -**Packages:** `CommunityToolkit.Mvvm 8.4.0`, `Microsoft.Extensions.DI.Abstractions 10.0.0`, `Microsoft.Extensions.Logging.Abstractions 10.0.0`, `SixLabors.ImageSharp 3.1.12` +**Packages:** `CommunityToolkit.Mvvm 8.4.0`, `Microsoft.Extensions.DI.Abstractions 10.0.0`, `Microsoft.Extensions.Logging.Abstractions 10.0.0`. Image decoding for the perceptual hash goes through `IImageHashDecoder`, implemented in Platform.Windows on the Windows Imaging Component. --- @@ -698,6 +698,7 @@ Internal static class. `CurrentVersion = 15`; each level is a `VStatements` a | v13 | `FolderEntries.ParentNormalizedPath` + `(SessionId, ParentNormalizedPath, TotalSizeBytes DESC)` index | | v14 | `ScanSessions.OwnerProcessId` / `OwnerProcessStartedUtc` | | v15 | Indexes on the `FileEntries(Id)` cascade referrers, plus `DuplicateErrors(RunId, FileEntryId)` | +| v16 | `FileEntries.IsAdditionalHardLink`: further names of a hard-linked file, left out of the category totals | Path casing is never computed in SQL: SQLite's `upper()` is ASCII-only while the application uses `ToUpperInvariant`. v13's backfill therefore splits the parent off the already-normalized column instead of re-normalizing. @@ -1038,7 +1039,6 @@ The suite count changes as regression guards are added. Run the documented Relea | Core | `CommunityToolkit.Mvvm` | 8.4.0 | MVVM source generators | | Core | `Microsoft.Extensions.DependencyInjection.Abstractions` | 10.0.0 | DI interfaces | | Core | `Microsoft.Extensions.Logging.Abstractions` | 10.0.0 | `ILogger` | -| Core | `SixLabors.ImageSharp` | 3.1.12 | Image duplicate decoding and perceptual hashing | | Platform.Windows | `Microsoft.Extensions.Logging.Abstractions` | 10.0.0 | Logging | | Platform.Windows | `System.Management` | 9.0.5 | Windows drive-health queries | | Storage | `Microsoft.Data.Sqlite` | 9.0.4 | SQLite access | diff --git a/docs/public/DOCUMENTATION.md b/docs/public/DOCUMENTATION.md index 77e67b8..f5aa9ed 100644 --- a/docs/public/DOCUMENTATION.md +++ b/docs/public/DOCUMENTATION.md @@ -1,9 +1,9 @@ # StorageMaster — Full Technical Documentation - + > **Version:** 2.2.1 | **Current-state review:** 2026-08-18 | **.NET 8 / WinUI 3 / Windows App SDK 1.6** -> **Current storage/safety state:** schema v15 uses independent SQLite connection leases, normalized file/folder identity, exact UTC timestamp reads, duplicate recovery journals, nullable stable scan-time file identity, a materialized folder parent path, scan-session ownership with startup recovery, and indexed foreign-key cascade paths. Historical identity-less rows stay readable but require rescan before destructive scan-backed actions. `DatabaseSchema.CurrentVersion` is authoritative for the schema number. +> **Current storage/safety state:** schema v16 uses independent SQLite connection leases, normalized file/folder identity, exact UTC timestamp reads, duplicate recovery journals, nullable stable scan-time file identity, a materialized folder parent path, scan-session ownership with startup recovery, and indexed foreign-key cascade paths. Historical identity-less rows stay readable but require rescan before destructive scan-backed actions. `DatabaseSchema.CurrentVersion` is authoritative for the schema number. --- diff --git a/docs/public/SAFETY_RECOVERY.md b/docs/public/SAFETY_RECOVERY.md index bf5f993..95868c2 100644 --- a/docs/public/SAFETY_RECOVERY.md +++ b/docs/public/SAFETY_RECOVERY.md @@ -5,7 +5,7 @@ StorageMaster is a storage-management tool. Recoverability and auditability take ## Deletion modes - Quarantine: preferred for duplicate cleanup. Files are moved into the app quarantine and can be restored. -- Recycle Bin: preferred for general cleanup when Windows supports recycling the target path. Where it does not (network shares, many removable drives, an item larger than the bin's maximum size, a drive whose bin is turned off), the item is left in place and reported as not deleted; Recycle Bin mode never falls back to permanent deletion. +- Recycle Bin: preferred for general cleanup when Windows supports recycling the target path. Where it does not (network shares, many removable drives, an item larger than the bin's maximum size, a drive whose bin is turned off), the item is left in place and reported as not deleted; Recycle Bin mode never falls back to permanent deletion on its own. Where the app is interactive (Duplicates, Cleanup, Smart Cleaner, Results), it then asks a second question, "Delete these N item(s) permanently?", lists the items and defaults to No. Only a yes deletes them permanently, through the same live checks as any other deletion; items the user was not shown are never included. Scheduled cleanup has no one to ask and keeps the refusal. - Permanent delete: allowed only after explicit user intent and confirmation. ## Recovery journal @@ -41,7 +41,7 @@ Recycle Bin and quarantine operations move logical file data but do not normally - The current journal is inspectable through repository APIs and tests, but the WinUI recovery page still needs a first-class journal view. - A process or power failure in the narrow interval after a quarantine move but before its transactional/fallback journal write can still leave a moved file requiring manual quarantine-directory reconciliation. -- Files changed after scan are skipped by duplicate cleanup rather than force-deleted. +- Files changed after scan are skipped by duplicate cleanup rather than force-deleted. The Duplicates page lists every selected file it left in place with the reason (changed since the analysis, could not be re-read, no longer matches the kept file, Recycle Bin unavailable, refused by Windows, kept file not verifiable, no stable identity). - Permanent directory traversal is handle-bound and no-follow. Recycle Bin operations and individual file deletion still cross a final path-based Windows API boundary; snapshots and postchecks reduce risk but cannot mathematically eliminate a malicious last-instruction path swap. - The program-leftover rule is heuristic. It is disabled, unselected, high-risk, and Recycle-Bin-only by default, but a reviewed directory can still receive new content between analysis and execution. - Managed scanning resolves and checks reparse targets before enumeration, but Core-only metadata checks cannot close every adversarial junction swap. Turbo uses strong no-follow root-ancestor locks where ACL/sharing permits; protected ancestors and queued descendants retain a documented same-privilege swap window. Persisted identity and downstream deletion validation fail closed on changed files. diff --git a/src/StorageMaster.Core/Cleanup/CleanupEngine.cs b/src/StorageMaster.Core/Cleanup/CleanupEngine.cs index 3212302..a4f086a 100644 --- a/src/StorageMaster.Core/Cleanup/CleanupEngine.cs +++ b/src/StorageMaster.Core/Cleanup/CleanupEngine.cs @@ -143,6 +143,7 @@ private async Task ExecuteSuggestionAsync( long totalFreed = 0; var failedPaths = new List(); + var recycleBinRefusedPaths = new List(); var quarantinedPaths = new List(); var processedPaths = new HashSet(StringComparer.OrdinalIgnoreCase); var successfulPaths = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -188,6 +189,8 @@ private async Task ExecuteSuggestionAsync( else { failedPaths.Add(outcome.Path); + if (outcome.RecycleBinRefused) + recycleBinRefusedPaths.Add(outcome.Path); firstError ??= outcome.Error; _logger.LogWarning("Delete failed: {Path} — {Error}", outcome.Path, outcome.Error); } @@ -232,9 +235,56 @@ private async Task ExecuteSuggestionAsync( FailedPaths = failedPaths, ErrorMessage = firstError, QuarantinedPaths = quarantinedPaths, + RecycleBinRefusedPaths = recycleBinRefusedPaths, }, wasCancelled); } + /// + /// The suggestions of a finished Recycle Bin run, reduced to the targets the + /// Recycle Bin refused, for a permanent deletion the user has confirmed. + /// + /// Only refusals are carried over: targets that were recycled, failed for another + /// reason, or were never reached stay out, so the retry cannot touch anything the + /// user was not shown. A suggestion that may not be deleted permanently (high + /// risk, or not supported) contributes nothing. The retry itself still goes + /// through every snapshot check of a normal run. + /// + /// + public static IReadOnlyList BuildPermanentRetryForRecycleBinRefusals( + IReadOnlyList suggestions, + IReadOnlyList results) + { + var retry = new List(); + foreach (var result in results) + { + if (result.WasDryRun || result.RecycleBinRefusedPaths.Count == 0) + continue; + + var suggestion = suggestions.FirstOrDefault(candidate => candidate.Id == result.SuggestionId); + if (suggestion is null) + continue; + + var targets = new HashSet(suggestion.TargetPaths, StringComparer.OrdinalIgnoreCase); + var refused = result.RecycleBinRefusedPaths + .Where(targets.Contains) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + if (refused.Length == 0) + continue; + + var narrowed = suggestion with + { + TargetPaths = refused, + EstimatedBytes = refused.Sum(path => + suggestion.ExpectedFileSnapshots.TryGetValue(path, out var snapshot) ? snapshot.SizeBytes : 0L), + }; + if (ValidateDeletionPolicy(narrowed, DeletionMethod.Permanent) is null) + retry.Add(narrowed); + } + + return retry; + } + /// /// Writes a QuarantinedFiles restore record (MemberId=null, generic-cleanup /// run) so the file shows up in the app's quarantine view. A recording diff --git a/src/StorageMaster.Core/Deduplication/DuplicateDeletionService.cs b/src/StorageMaster.Core/Deduplication/DuplicateDeletionService.cs index b8fd835..0803619 100644 --- a/src/StorageMaster.Core/Deduplication/DuplicateDeletionService.cs +++ b/src/StorageMaster.Core/Deduplication/DuplicateDeletionService.cs @@ -60,7 +60,7 @@ public async Task DeleteSelectedWithResultAsync( .Where(static m => m.IsSelected && !m.IsKeeper && m.ExistsNow) .ToList(); if (selected.Count == 0) - return new DuplicateDeletionResult(0, 0, []); + return new DuplicateDeletionResult(0, 0, [], []); if (!_strategies.TryGetValue(group.Method, out var strategy) || !strategy.IsAvailable) { @@ -101,27 +101,35 @@ public async Task DeleteSelectedWithResultAsync( long processedBytes = 0L; var deletedMembers = new List(selected.Count); var warnings = new List(); + var skipped = new List(); foreach (var member in selected) { ct.ThrowIfCancellationRequested(); if (member.Identity is null) { - warnings.Add(new DuplicateDeletionWarning( - member.FullPath, - "Skipped because no stable scan-time file identity is available. Run duplicate analysis again.")); + Skip(member, DuplicateDeletionSkipReason.NoStableIdentity); continue; } var memberSnapshot = await _snapshotProvider.TakeSnapshotAsync(member.FullPath, ct); if (memberSnapshot is null || !MatchesRecordedState(member, memberSnapshot)) + { + Skip(member, DuplicateDeletionSkipReason.ChangedSinceAnalysis); continue; + } var memberCandidate = CreateLiveCandidate(member, memberSnapshot); var memberSignature = await strategy.ComputeSignatureAsync(memberCandidate, ct); - if (!IsReady(memberSignature) || - !AreLiveDuplicates(strategy, keeperCandidate, keeperSignature, memberCandidate, memberSignature)) + if (!IsReady(memberSignature)) { + Skip(member, DuplicateDeletionSkipReason.CouldNotVerify, memberSignature.ErrorMessage); + continue; + } + + if (!AreLiveDuplicates(strategy, keeperCandidate, keeperSignature, memberCandidate, memberSignature)) + { + Skip(member, DuplicateDeletionSkipReason.NoLongerDuplicate); continue; } @@ -145,6 +153,12 @@ await _duplicateRepository.UpdateDuplicateOperationOutcomeAsync( outcome.BytesFreed, outcome.Error ?? "Deletion failed.", CancellationToken.None); + Skip( + member, + outcome.RecycleBinRefused + ? DuplicateDeletionSkipReason.RecycleBinUnavailable + : DuplicateDeletionSkipReason.DeleteFailed, + outcome.Error); continue; } @@ -255,7 +269,14 @@ await _duplicateRepository.MarkMembersDeletedAsync( } } - return new DuplicateDeletionResult(processedBytes, deletedMembers.Count, warnings.ToArray()); + return new DuplicateDeletionResult( + processedBytes, + deletedMembers.Count, + warnings.ToArray(), + skipped.ToArray()); + + void Skip(DuplicateGroupMember member, DuplicateDeletionSkipReason reason, string? detail = null) => + skipped.Add(new DuplicateDeletionSkip(member.Id, member.FullPath, reason, detail)); } public async Task RestoreFromQuarantineAsync( diff --git a/src/StorageMaster.Core/Deduplication/DuplicateDeletionSkips.cs b/src/StorageMaster.Core/Deduplication/DuplicateDeletionSkips.cs new file mode 100644 index 0000000..699bfb4 --- /dev/null +++ b/src/StorageMaster.Core/Deduplication/DuplicateDeletionSkips.cs @@ -0,0 +1,57 @@ +using StorageMaster.Core.Interfaces; +using StorageMaster.Core.Models; + +namespace StorageMaster.Core.Deduplication; + +/// +/// The pieces of the "why was this not deleted" report that do not need a window: +/// which string explains a reason, what a group that failed as a whole leaves +/// behind, and which members a permanent retry of Recycle Bin refusals may touch. +/// Kept here rather than in the view model so they are tested. +/// +public static class DuplicateDeletionSkips +{ + /// Resource key explaining ; one exists per value in every UI language. + public static string ResourceKey(DuplicateDeletionSkipReason reason) => + $"Safety_Duplicates_NotDeleted_{reason}"; + + /// + /// A group whose keeper could not be verified deletes nothing, so every member + /// the user selected in it was left in place for that reason. + /// + public static IReadOnlyList ForUnprocessedGroup( + IReadOnlyList members, + string? detail) => + members + .Where(static member => member.IsSelected && !member.IsKeeper && member.ExistsNow) + .Select(member => new DuplicateDeletionSkip( + member.Id, + member.FullPath, + DuplicateDeletionSkipReason.KeeperNotVerified, + detail)) + .ToArray(); + + /// + /// The group's members with only the Recycle Bin refusals selected, for a + /// permanent retry the user has confirmed. Everything else — the keeper, files + /// already recycled, files skipped for any other reason — is deselected, so the + /// retry cannot reach a file the user was not asked about. The retry still goes + /// through every live check of a normal deletion. + /// + public static IReadOnlyList SelectOnlyRecycleBinRefusals( + IReadOnlyList members, + IEnumerable skipped) + { + var refused = skipped + .Where(static skip => skip.Reason == DuplicateDeletionSkipReason.RecycleBinUnavailable) + .Select(static skip => skip.MemberId) + .ToHashSet(); + + return members + .Select(member => member with + { + IsSelected = !member.IsKeeper && member.IsSelected && refused.Contains(member.Id), + }) + .ToArray(); + } +} diff --git a/src/StorageMaster.Core/Deduplication/ImagePHashStrategy.cs b/src/StorageMaster.Core/Deduplication/ImagePHashStrategy.cs index a614840..696ef39 100644 --- a/src/StorageMaster.Core/Deduplication/ImagePHashStrategy.cs +++ b/src/StorageMaster.Core/Deduplication/ImagePHashStrategy.cs @@ -1,10 +1,5 @@ using System.Numerics; using System.Text.Json; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Formats; -using SixLabors.ImageSharp.Metadata.Profiles.Exif; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing; using StorageMaster.Core.Interfaces; using StorageMaster.Core.Models; @@ -14,8 +9,9 @@ namespace StorageMaster.Core.Deduplication; /// Perceptual hash (pHash) strategy for image files. /// /// Algorithm: DCT-based 64-bit pHash -/// 1. Load image and correct EXIF orientation. -/// 2. Resize to 32×32 grayscale. +/// 1. Decode through (the Windows Imaging +/// Component on Windows), correcting EXIF orientation. +/// 2. Scale to 32×32 luminance. /// 3. Compute 2-D separable DCT. /// 4. Take top-left 8×8 coefficients (64 values); exclude DC component at [0,0]. /// 5. Compute average of those 63 values. @@ -31,18 +27,10 @@ public sealed class ImagePHashStrategy : IDuplicateDetectionStrategy public const int DefaultHammingThreshold = 10; // out of 64 bits public const double AutoSelectConfidenceThreshold = 0.98d; // future opt-in - private const int DctSize = 32; + /// Side of the square luminance surface the DCT reads. + internal const int DctSize = 32; private const int HashBits = 8; // top-left 8×8 block of DCT - /// - /// Decode-time size hint. Everything past this is thrown away by the 32×32 - /// resize, and for JPEG the decoder serves it straight from the scaled IDCT - /// instead of materialising the full-resolution surface. 256 rather than 64 - /// because the hint is aspect-preserving (ResizeMode.Max): a panorama at a - /// 64-px box would arrive with fewer than 32 usable rows. - /// - private const int DecodeTargetSize = 256; - /// /// cos(π·k·(2t+1) / 2·DctSize) for k < , t < . /// Only the top-left 8×8 block of the DCT is ever read, so the higher @@ -56,25 +44,30 @@ public sealed class ImagePHashStrategy : IDuplicateDetectionStrategy { ".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif", ".tif", ".tiff", - ".heic", ".heif", // requires platform decoder; errors surface gracefully + ".heic", ".heif", // requires the platform's HEIF codec; errors surface gracefully }; + private readonly IImageHashDecoder _decoder; private readonly int _hammingThreshold; private readonly IFileSnapshotProvider? _snapshotProvider; private readonly ISettingsSnapshotProvider? _settingsSnapshotProvider; public ImagePHashStrategy( + IImageHashDecoder decoder, IFileSnapshotProvider? snapshotProvider = null, int hammingThreshold = DefaultHammingThreshold) { + _decoder = decoder; _snapshotProvider = snapshotProvider; _hammingThreshold = hammingThreshold; } public ImagePHashStrategy( + IImageHashDecoder decoder, ISettingsSnapshotProvider settingsSnapshotProvider, IFileSnapshotProvider? snapshotProvider = null) { + _decoder = decoder; _settingsSnapshotProvider = settingsSnapshotProvider; _snapshotProvider = snapshotProvider; _hammingThreshold = DefaultHammingThreshold; @@ -82,7 +75,11 @@ public ImagePHashStrategy( public DuplicateMethod Method => DuplicateMethod.ImagePHash; public string Algorithm => "IMAGE-PHASH-DCT64"; - public int AlgorithmVersion => 2; // v2: decode-scaled input (hash values shift) + + // v3: decoded and scaled by the platform decoder instead of ImageSharp. The + // pipeline is the same, but resampling differs slightly, so cached v2 hashes + // are recomputed rather than compared against v3 ones. + public int AlgorithmVersion => 3; public bool SupportsAutoSelection => false; public double DefaultConfidence => 0.0d; // computed per-pair public string DisplayName => "Image perceptual hash"; @@ -123,9 +120,7 @@ public async Task ComputeSignatureAsync( if (_snapshotProvider is not null && before is null) return ErrorSig(candidate, "FileNotFound", "File no longer exists before image hashing."); - // Run synchronous ImageSharp I/O on thread-pool thread - var (hash64, width, height, orientation) = await Task.Run( - () => ComputePHash(candidate.File.FullPath), ct); + var (hash64, width, height, orientation) = await ComputePHashAsync(candidate.File.FullPath, ct); var after = _snapshotProvider is null ? null : await _snapshotProvider.TakeSnapshotAsync(candidate.File.FullPath, ct); @@ -241,60 +236,49 @@ public IEnumerable BuildMatches( // ── DCT pHash ───────────────────────────────────────────────────────────── - private static (ulong Hash, int Width, int Height, ushort Orientation) - ComputePHash(string path) + private async Task<(ulong Hash, int Width, int Height, ushort Orientation)> ComputePHashAsync( + string path, + CancellationToken ct) { - // One handle for both the header read and the decode; ReadWrite|Delete - // sharing matches the other hashing strategies so a file open elsewhere - // does not turn into a spurious PHashError. - using var stream = new FileStream( + ct.ThrowIfCancellationRequested(); + + // ReadWrite|Delete sharing matches the other hashing strategies so a file + // open elsewhere does not turn into a spurious PHashError. + await using var stream = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 64 * 1024, - FileOptions.SequentialScan); - - // Header first: the decode below is deliberately scaled down, so the true - // pixel dimensions have to come from the metadata rather than from the - // decoded surface. - var info = Image.Identify(stream); - stream.Position = 0; - - ushort orientation = 1; - if (info.Metadata.ExifProfile?.TryGetValue(ExifTag.Orientation, out var orientTag) == true) - orientation = orientTag?.Value ?? 1; - - using var img = Image.Load( - new DecoderOptions { TargetSize = new Size(DecodeTargetSize, DecodeTargetSize) }, - stream); - - // Correct EXIF orientation before hashing so that the same photo - // stored in different orientations gets the same hash. - img.Mutate(x => x.AutoOrient()); - - // Orientations 5-8 transpose the image, so the reported dimensions follow - // AutoOrient the way they did when this read them off the decoded image. - var transposed = orientation is >= 5 and <= 8; - var width = transposed ? info.Height : info.Width; - var height = transposed ? info.Width : info.Height; - - return (ComputeHashFromImage(img), width, height, orientation); + FileOptions.Asynchronous | FileOptions.SequentialScan); + + // The decoder corrects EXIF orientation before scaling, so the same photo + // stored in different orientations gets the same hash, and reports the + // displayed (oriented) dimensions. + var surface = await _decoder.DecodeAsync(stream, DctSize, ct).ConfigureAwait(false); + return ( + ComputeHashFromLuminance(surface.Luminance), + surface.Header.Width, + surface.Header.Height, + surface.Header.Orientation); } /// - /// pHash of an already-decoded, orientation-corrected grayscale surface. - /// Shared with so the frame hash and the - /// image hash cannot drift apart. + /// pHash of an orientation-corrected × + /// luminance surface, row-major. Shared with so + /// the frame hash and the image hash cannot drift apart. /// - internal static ulong ComputeHashFromImage(Image img) + internal static ulong ComputeHashFromLuminance(ReadOnlySpan luminance) { - img.Mutate(x => x.Resize(DctSize, DctSize)); + if (luminance.Length != DctSize * DctSize) + { + throw new InvalidDataException( + $"Expected a {DctSize}x{DctSize} luminance surface ({DctSize * DctSize} bytes), got {luminance.Length} bytes."); + } // Build float grayscale matrix var pixels = new float[DctSize * DctSize]; - for (var y = 0; y < DctSize; y++) - for (var x = 0; x < DctSize; x++) - pixels[y * DctSize + x] = img[x, y].PackedValue / 255f; + for (var i = 0; i < pixels.Length; i++) + pixels[i] = luminance[i] / 255f; // Top-left HashBits×HashBits block of the 2-D DCT var coeffs = ComputeTopLeftDct(pixels); diff --git a/src/StorageMaster.Core/Deduplication/VideoPHashStrategy.cs b/src/StorageMaster.Core/Deduplication/VideoPHashStrategy.cs index 92ed605..48b21dc 100644 --- a/src/StorageMaster.Core/Deduplication/VideoPHashStrategy.cs +++ b/src/StorageMaster.Core/Deduplication/VideoPHashStrategy.cs @@ -1,8 +1,6 @@ using System.Diagnostics; using System.Numerics; using System.Text.Json; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; using StorageMaster.Core.Interfaces; using StorageMaster.Core.Models; using StorageMaster.Core.Safety; @@ -78,7 +76,10 @@ public VideoPHashStrategy( public DuplicateMethod Method => DuplicateMethod.VideoPHash; public string Algorithm => "VIDEO-PHASH-FRAMES"; - public int AlgorithmVersion => 2; // v2: frames extracted pre-scaled (hash values shift) + // v3: frames come out of FFmpeg as raw 32×32 luminance instead of a PNG decoded + // by ImageSharp. Same DCT, slightly different grey conversion, so cached v2 + // fingerprints are recomputed rather than compared against v3 ones. + public int AlgorithmVersion => 3; public bool SupportsAutoSelection => false; public double DefaultConfidence => 0.0d; // computed per-pair public string DisplayName => "Video perceptual hash"; @@ -158,7 +159,7 @@ public async Task ComputeSignatureAsync( for (var fi = 0; fi < frameSampleCount; fi++) { ct.ThrowIfCancellationRequested(); - var framePath = Path.Combine(tempDir, $"frame_{fi:D2}.png"); + var framePath = Path.Combine(tempDir, $"frame_{fi:D2}.gray"); await ExtractFrameAsync(tools.FfmpegPath, candidate.File.FullPath, timestamps[fi], framePath, ct); @@ -328,11 +329,13 @@ private static async Task ExtractFrameAsync( psi.ArgumentList.Add(videoPath); psi.ArgumentList.Add("-frames:v"); psi.ArgumentList.Add("1"); - // The hash only ever sees a 32×32 surface, so scale in ffmpeg rather than - // PNG-encoding a 4K frame to disk and immediately throwing it away. Same - // stretch-to-square semantics the ImageSharp resize applied afterwards. + // The hash only ever sees a 32×32 luminance surface, so FFmpeg scales the + // frame (stretch-to-square), converts it to grey and writes the 1024 raw + // bytes. No image file is encoded, and none has to be decoded again. psi.ArgumentList.Add("-vf"); - psi.ArgumentList.Add("scale=32:32"); + psi.ArgumentList.Add($"scale={ImagePHashStrategy.DctSize}:{ImagePHashStrategy.DctSize},format=gray"); + psi.ArgumentList.Add("-f"); + psi.ArgumentList.Add("rawvideo"); psi.ArgumentList.Add(outPath); psi.ArgumentList.Add("-y"); @@ -350,12 +353,12 @@ private static string SummarizeError(string error) // ── Frame hash (reuse ImagePHashStrategy DCT logic) ─────────────────────── - private static ulong ComputeFrameHash(string framePath) + internal static ulong ComputeFrameHash(string framePath) { - using var img = Image.Load(framePath); // Shared with the image strategy — this file used to carry a verbatim copy - // of the DCT, which is exactly how the two hashes would drift apart. - return ImagePHashStrategy.ComputeHashFromImage(img); + // of the DCT, which is exactly how the two hashes would drift apart. The + // length check inside rejects a frame FFmpeg did not write in full. + return ImagePHashStrategy.ComputeHashFromLuminance(File.ReadAllBytes(framePath)); } // ── Fingerprint comparison ──────────────────────────────────────────────── diff --git a/src/StorageMaster.Core/Interfaces/IDuplicateDeletionService.cs b/src/StorageMaster.Core/Interfaces/IDuplicateDeletionService.cs index 4eb9d00..e7ed2a5 100644 --- a/src/StorageMaster.Core/Interfaces/IDuplicateDeletionService.cs +++ b/src/StorageMaster.Core/Interfaces/IDuplicateDeletionService.cs @@ -9,7 +9,8 @@ public interface IDuplicateDeletionService /// Recomputes live method-specific signatures, locks the keeper against /// replacement, and validates each selected file snapshot immediately before /// deletion. Files that changed since analysis are skipped (not deleted). - /// Returns total bytes processed. Recycle Bin and quarantine moves do not + /// Returns total bytes processed; + /// also says why each skipped file was left in place. Recycle Bin and quarantine moves do not /// necessarily release filesystem allocation. /// Task DeleteSelectedAsync( @@ -41,7 +42,45 @@ Task RestoreFromQuarantineAsync( public sealed record DuplicateDeletionWarning(string Path, string Message); +/// +/// Why a selected duplicate was left in place. Each value has a +/// Safety_Duplicates_NotDeleted_<value> string in every UI language. +/// +public enum DuplicateDeletionSkipReason +{ + /// The scan recorded no stable file identity, so a replaced file could not be told apart. + NoStableIdentity, + + /// The file changed, moved, was replaced or disappeared since the analysis. + ChangedSinceAnalysis, + + /// The file could not be read again to confirm it is still a duplicate. + CouldNotVerify, + + /// The file was read again and no longer matches the file being kept. + NoLongerDuplicate, + + /// Recycle Bin mode: Windows could only have deleted it permanently, so it was left alone. + RecycleBinUnavailable, + + /// Windows refused the deletion (locked, access denied, …). + DeleteFailed, + + /// The file being kept could not be verified, so nothing in its group was deleted. + KeeperNotVerified, +} + +/// A selected duplicate that was not deleted, and why. +/// Technical detail from Windows or the verifier, if any. English by policy. +public sealed record DuplicateDeletionSkip( + long MemberId, + string Path, + DuplicateDeletionSkipReason Reason, + string? Detail = null); + +/// Every selected member that was left in place, with the reason. public sealed record DuplicateDeletionResult( long ProcessedBytes, int DeletedFileCount, - IReadOnlyList Warnings); + IReadOnlyList Warnings, + IReadOnlyList Skipped); diff --git a/src/StorageMaster.Core/Interfaces/IFileDeleter.cs b/src/StorageMaster.Core/Interfaces/IFileDeleter.cs index 19d18d5..ab3a5ea 100644 --- a/src/StorageMaster.Core/Interfaces/IFileDeleter.cs +++ b/src/StorageMaster.Core/Interfaces/IFileDeleter.cs @@ -32,7 +32,14 @@ public sealed record DeletionOutcome( long BytesFreed, string? Error = null, /// Set when Method == Quarantine and move succeeded. - string? QuarantinePath = null); + string? QuarantinePath = null, + /// + /// True when Recycle Bin mode left the item in place because Windows could + /// only have deleted it permanently (no Recycle Bin on that drive, the item is + /// larger than the bin allows, or the bin is turned off). The item is untouched; + /// a caller that wants it gone must ask the user before a permanent delete. + /// + bool RecycleBinRefused = false); /// /// Platform abstraction for file/folder deletion. diff --git a/src/StorageMaster.Core/Interfaces/IImageHashDecoder.cs b/src/StorageMaster.Core/Interfaces/IImageHashDecoder.cs new file mode 100644 index 0000000..e096d09 --- /dev/null +++ b/src/StorageMaster.Core/Interfaces/IImageHashDecoder.cs @@ -0,0 +1,31 @@ +namespace StorageMaster.Core.Interfaces; + +/// +/// Decodes images for the perceptual image hash and the duplicate preview. +/// +/// Supplied by the platform — the Windows Imaging Component on Windows, the same +/// decoders File Explorer uses, kept current by Windows Update — so Core carries no +/// image codec of its own. Formats Windows has no codec for (HEIC without the HEIF +/// extension, for example) fail to decode and surface as a per-file hash error. +/// +/// +public interface IImageHashDecoder +{ + /// + /// Decodes the first frame of , applies its EXIF + /// orientation and scales it to × + /// 8-bit luminance, row-major. Throws when the data cannot be decoded. + /// + Task DecodeAsync(Stream stream, int size, CancellationToken ct = default); + + /// Reads the image's dimensions and orientation from its header without decoding pixels. + Task IdentifyAsync(Stream stream, CancellationToken ct = default); +} + +/// Pixel width as displayed, i.e. after EXIF orientation. +/// Pixel height as displayed, i.e. after EXIF orientation. +/// EXIF orientation tag, 1 (upright) when absent. +public sealed record ImageHeader(int Width, int Height, ushort Orientation); + +/// Size×Size 8-bit luminance, row-major. +public sealed record ImageHashSurface(byte[] Luminance, int Size, ImageHeader Header); diff --git a/src/StorageMaster.Core/Interfaces/ISmartCleanerService.cs b/src/StorageMaster.Core/Interfaces/ISmartCleanerService.cs index 8eddedd..0fadbd0 100644 --- a/src/StorageMaster.Core/Interfaces/ISmartCleanerService.cs +++ b/src/StorageMaster.Core/Interfaces/ISmartCleanerService.cs @@ -49,7 +49,11 @@ public sealed record SmartCleanGroup( IReadOnlyDictionary ExpectedFileSnapshots, bool IsSelected = true); -public sealed record SmartCleanFailure(string Path, string Error); +/// +/// True when Recycle Bin mode left the path in place because Windows could only +/// have deleted it permanently. The file is untouched. +/// +public sealed record SmartCleanFailure(string Path, string Error, bool RecycleBinRefused = false); /// Read-only Smart Cleaner findings plus path-specific scan warnings. public sealed record SmartCleanAnalysisResult( diff --git a/src/StorageMaster.Core/Models/CleanupResult.cs b/src/StorageMaster.Core/Models/CleanupResult.cs index 2a51db8..e51944b 100644 --- a/src/StorageMaster.Core/Models/CleanupResult.cs +++ b/src/StorageMaster.Core/Models/CleanupResult.cs @@ -21,4 +21,10 @@ public sealed record CleanupResult /// every moved file is preserved in the audit trail for manual recovery. /// public IReadOnlyList QuarantinedPaths { get; init; } = []; + + /// + /// Targets Recycle Bin mode left in place because Windows could only have deleted + /// them permanently. A subset of ; each is untouched. + /// + public IReadOnlyList RecycleBinRefusedPaths { get; init; } = []; } diff --git a/src/StorageMaster.Core/Models/FileEntry.cs b/src/StorageMaster.Core/Models/FileEntry.cs index 3c0145e..eeea26a 100644 --- a/src/StorageMaster.Core/Models/FileEntry.cs +++ b/src/StorageMaster.Core/Models/FileEntry.cs @@ -25,5 +25,12 @@ public sealed record FileEntry /// True when this entry was reachable only via a reparse point (symlink/junction). public bool IsReparsePoint { get; init; } + /// + /// True when the scan had already counted another hard link to the same file. + /// The entry keeps its real , but adds nothing to folder, + /// category or session totals: the data exists on disk once. + /// + public bool IsAdditionalHardLink { get; init; } + public string ParentPath => Path.GetDirectoryName(FullPath) ?? string.Empty; } diff --git a/src/StorageMaster.Core/Scanner/FileScanner.cs b/src/StorageMaster.Core/Scanner/FileScanner.cs index aa418d1..54a184d 100644 --- a/src/StorageMaster.Core/Scanner/FileScanner.cs +++ b/src/StorageMaster.Core/Scanner/FileScanner.cs @@ -457,6 +457,7 @@ private async Task ProcessDirectoryAsync( } var extension = Path.GetExtension(file.FileName); + var isAdditionalHardLink = !state.HardLinks.IsFirstLink(identity); var entry = new FileEntry { Id = 0, // assigned by DB @@ -472,13 +473,15 @@ private async Task ProcessDirectoryAsync( Category = FileTypeCategorizor.Categorize(extension), Identity = identity, IsReparsePoint = file.Attributes.HasFlag(FileAttributes.ReparsePoint), + IsAdditionalHardLink = isAdditionalHardLink, }; state.FileBuffer.Enqueue(entry); - directBytes += file.Length; + var countedBytes = HardLinkTracker.CountedBytes(entry); + directBytes += countedBytes; fileCount++; - Interlocked.Add(ref state._totalBytes, file.Length); + Interlocked.Add(ref state._totalBytes, countedBytes); Interlocked.Increment(ref state._fileCount); state.LastScannedPath = file.FullPath; } @@ -851,6 +854,9 @@ public string LastScannedPath public ConcurrentQueue FolderBuffer { get; } = new(); public ConcurrentQueue ErrorBuffer { get; } = new(); + /// Counts each file once in the byte totals, however many hard links reach it. + public HardLinkTracker HardLinks { get; } = new(); + // Serialise buffer drains so concurrent consumers never double-drain. public SemaphoreSlim FileFlushLock { get; } = new(1, 1); public SemaphoreSlim FolderFlushLock { get; } = new(1, 1); @@ -865,7 +871,7 @@ public void RecordPersistedFiles(IReadOnlyList entries) { long bytes = 0; foreach (var entry in entries) - bytes += entry.SizeBytes; + bytes += HardLinkTracker.CountedBytes(entry); Interlocked.Add(ref _persistedFileCount, entries.Count); Interlocked.Add(ref _persistedBytes, bytes); diff --git a/src/StorageMaster.Core/Scanner/HardLinkTracker.cs b/src/StorageMaster.Core/Scanner/HardLinkTracker.cs new file mode 100644 index 0000000..f0f7ea4 --- /dev/null +++ b/src/StorageMaster.Core/Scanner/HardLinkTracker.cs @@ -0,0 +1,61 @@ +using StorageMaster.Core.Models; + +namespace StorageMaster.Core.Scanner; + +/// +/// Remembers which files a scan has already counted, so a file with several hard +/// links adds its size to folder and session totals once. +/// +/// Hard links are separate names for one file: the data exists once on disk. +/// Windows uses them heavily (WinSxS links most of System32), and counting every +/// name made a system drive look far fuller than it is. The first name the scan +/// reaches carries the size; every further name is still listed, with its size, +/// but adds nothing to the totals. Files without a stable identity, or with a +/// placeholder file id, are always counted, as before. +/// +/// +/// Keyed by volume and file index only — 8 bytes per file plus set overhead — so +/// the cost stays small on scans of millions of files. Thread-safe: the parallel +/// scanner calls it from several workers. +/// +/// +public sealed class HardLinkTracker +{ + private readonly object _gate = new(); + private readonly Dictionary> _seenByVolume = new(StringComparer.OrdinalIgnoreCase); + + /// + /// True the first time a file is seen, false for every further hard link to it. + /// A null identity, or a file index that is not a real id, is always the first. + /// + public bool IsFirstLink(FileIdentity? identity) + { + if (identity is null || !IsUniqueFileIndex(identity.FileIndex)) + return true; + + lock (_gate) + { + if (!_seenByVolume.TryGetValue(identity.VolumeSerial, out var seen)) + { + seen = []; + _seenByVolume[identity.VolumeSerial] = seen; + } + + return seen.Add(identity.FileIndex); + } + } + + /// + /// A file system that cannot give a file a unique 64-bit id reports 0 or all ones + /// instead: ReFS for files whose 128-bit id does not fit, and some network and + /// user-mode (FUSE-style) file systems for every file. Unrelated files share + /// those values, so they prove nothing about hard links, and treating them as one + /// file would leave all but the first out of the totals. + /// + private static bool IsUniqueFileIndex(ulong fileIndex) => + fileIndex is not (0UL or ulong.MaxValue); + + /// The bytes adds to folder and session totals. + public static long CountedBytes(FileEntry entry) => + entry.IsAdditionalHardLink ? 0 : entry.SizeBytes; +} diff --git a/src/StorageMaster.Core/SmartCleaner/SmartCleanerService.cs b/src/StorageMaster.Core/SmartCleaner/SmartCleanerService.cs index c221190..d034f1a 100644 --- a/src/StorageMaster.Core/SmartCleaner/SmartCleanerService.cs +++ b/src/StorageMaster.Core/SmartCleaner/SmartCleanerService.cs @@ -347,7 +347,7 @@ public async Task CleanAsync( } else { - AddFailure(path, outcome.Error ?? "Deletion failed."); + AddFailure(path, outcome.Error ?? "Deletion failed.", outcome.RecycleBinRefused); _logger.LogWarning( "[SmartCleaner] Failed {Path}: {Error}", path, @@ -404,14 +404,14 @@ await WriteAuditAsync( auditWarnings) .ConfigureAwait(false); - void AddFailure(string path, string error) + void AddFailure(string path, string error, bool recycleBinRefused = false) { if (!reportedFailurePaths.Add(path)) return; failedPaths.Add(path); firstError ??= error; - allFailures.Add(new SmartCleanFailure(path, error)); + allFailures.Add(new SmartCleanFailure(path, error, recycleBinRefused)); } void RejectPath(string path, string error) @@ -654,6 +654,45 @@ private static bool IsThumbnailTargetUnder(string path, string explorerRoot) name.EndsWith(".db", StringComparison.OrdinalIgnoreCase); } + /// + /// The groups of a finished Recycle Bin run, reduced to the paths the Recycle Bin + /// refused, for a permanent deletion the user has confirmed. Paths that were + /// recycled, rejected or failed for another reason stay out, so the retry cannot + /// reach anything the user was not shown; it still revalidates every path against + /// its analysis-time snapshot like a normal run. + /// + public static IReadOnlyList NarrowToRecycleBinRefusals( + IReadOnlyList groups, + SmartCleanResult result) + { + var refused = result.Failures + .Where(static failure => failure.RecycleBinRefused) + .Select(static failure => failure.Path) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + if (refused.Count == 0) + return []; + + var narrowed = new List(); + foreach (var group in groups) + { + var paths = group.Paths + .Where(refused.Contains) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + if (paths.Length == 0) + continue; + + narrowed.Add(group with + { + Paths = paths, + EstimatedBytes = paths.Sum(path => + group.ExpectedFileSnapshots.TryGetValue(path, out var snapshot) ? snapshot.SizeBytes : 0L), + }); + } + + return narrowed; + } + private static bool PathsEqual(string left, string right) => TryCanonicalizeAbsolutePath(left, out var canonicalLeft) && TryCanonicalizeAbsolutePath(right, out var canonicalRight) && diff --git a/src/StorageMaster.Core/StorageMaster.Core.csproj b/src/StorageMaster.Core/StorageMaster.Core.csproj index 3686d1f..4e8acab 100644 --- a/src/StorageMaster.Core/StorageMaster.Core.csproj +++ b/src/StorageMaster.Core/StorageMaster.Core.csproj @@ -13,8 +13,6 @@ - - diff --git a/src/StorageMaster.Core/Strings/de-DE/Resources.resw b/src/StorageMaster.Core/Strings/de-DE/Resources.resw index 41652aa..6d4d5e4 100644 --- a/src/StorageMaster.Core/Strings/de-DE/Resources.resw +++ b/src/StorageMaster.Core/Strings/de-DE/Resources.resw @@ -2118,6 +2118,42 @@ Pro Gruppe bleibt eine beizubehaltende Datei unangetastet. Methode: {2}. Papierkorb [safety] Name of the deletion route, used inside two longer sentences on the Duplicates page: as {2} of Safety_Duplicates_ConfirmDelete_Body and as {0} of Safety_Duplicates_ConfirmDelete_Action ('Delete via Recycle Bin'). Use the exact Windows term. + + Die Datei wurde nach der Duplikatanalyse geändert, verschoben oder entfernt. + [safety] Reason shown under a duplicate that was not deleted: the file was changed, moved, replaced or removed after the duplicate analysis, so it was left alone. + + + Die Datei konnte nicht erneut gelesen werden, um zu bestätigen, dass sie noch ein Duplikat ist. + [safety] Reason shown under a duplicate that was not deleted: just before deleting, the app reads the file again to confirm it still matches the file being kept, and that read failed. A technical detail line in English may follow. + + + Windows hat das Löschen nicht zugelassen. Die Datei ist möglicherweise in einem anderen Programm geöffnet. + [safety] Reason shown under a duplicate that was not deleted because Windows refused the operation, most often because the file is open in another program or access was denied. A technical detail line in English may follow. + + + Die beizubehaltende Datei konnte nicht überprüft werden, daher wurde in dieser Gruppe nichts gelöscht. + [safety] Reason shown under a duplicate that was not deleted because the file being kept in its group could not be verified (missing, changed or unreadable), so nothing in that group was deleted. Glossary: Keeper = beizubehaltende Datei / archivo que se conserva. + + + Diese Dateien befinden sich weiterhin an ihrem Speicherort. Der Grund steht jeweils darunter. + [safety] Text of the warning banner on the Duplicates page that lists selected files a deletion left in place. Reassures the user that these files are untouched and points to the per-file reason below. Never imply the files are gone. + + + Die Datei stimmt nicht mehr mit der beizubehaltenden Datei überein. + [safety] Reason shown under a duplicate that was not deleted: read again just before deleting, it no longer matches the file being kept (glossary: Keeper = beizubehaltende Datei / archivo que se conserva). + + + Bei der Überprüfung wurde keine stabile Dateikennung erfasst. Überprüfen Sie erneut, und führen Sie dann die Duplikatanalyse erneut aus. + [safety] Reason shown under a duplicate that was not deleted: the scan recorded no stable file identity for it, so the app cannot prove the file was not replaced since. The fix is to scan the drive again and rerun the duplicate analysis. + + + Windows kann die Datei hier nicht in den Papierkorb verschieben, und im Papierkorbmodus wird nie endgültig gelöscht. + [safety] Reason shown under a duplicate that was not deleted in Recycle Bin mode: Windows could not put it in the Recycle Bin on that drive (network share, removable drive, too large, or bin turned off), and Recycle Bin mode never falls back to permanent deletion. Use the exact Windows term for the Recycle Bin. + + + {0} ausgewählte Datei(en) nicht gelöscht + [safety] Title of the warning banner on the Duplicates page after a deletion that left some selected files in place. {0} is an already-formatted count. Must say plainly that these files were NOT deleted; the list under the banner gives the reason for each file. + Endgültig gelöscht: {0} in {1} Datei(en) [safety] First half of the status line reported after duplicates were deleted permanently, with no way back. {0} is an already-formatted size, {1} an already-formatted file count. A sentence fragment continued by Duplicates_Status_DeleteDone and its variants - do not add a full stop. Must clearly say the deletion was permanent. @@ -2130,6 +2166,10 @@ Pro Gruppe bleibt eine beizubehaltende Datei unangetastet. Methode: {2}. In den Papierkorb verschoben: {0} in {1} Datei(en) [safety] First half of the status line reported after duplicates were deleted to the Windows Recycle Bin. {0} is an already-formatted size, {1} an already-formatted file count. A sentence fragment continued by Duplicates_Status_DeleteDone and its variants - do not add a full stop. Use the exact Windows term for the Recycle Bin. + + In den Papierkorb verschoben: {0} in {1} Datei(en); endgültig gelöscht: {2} in {3} Datei(en) + [safety] First half of the status line after a duplicate deletion in Recycle Bin mode where the user then agreed to delete the files Windows could not recycle permanently. {0} and {2} are already-formatted sizes, {1} and {3} already-formatted file counts. A sentence fragment continued by Duplicates_Status_DeleteDone and its variants - do not add a full stop. Must keep the recoverable part and the permanent part clearly apart. + · Bereinigungsquarantäne [label] Small muted tag on a quarantine-list row saying the file was quarantined by a Cleanup-page rule rather than by duplicate deletion. The leading middle dot is a separator from the timestamp printed before it - keep it and the space that follows. @@ -2194,6 +2234,24 @@ Pro Gruppe bleibt eine beizubehaltende Datei unangetastet. Methode: {2}. Nur endgültiges Löschen. Das Leeren des Papierkorbs kann nicht rückgängig gemacht werden. [safety] Safety note shown in its own line beneath the empty-Recycle-Bin suggestion on the Cleanup page. It states that this suggestion cannot be run in Recycle Bin or quarantine mode — the files go for good. Must not be softened or shortened. + + Diese {0} Element(e) endgültig löschen? + +Windows kann sie hier nicht in den Papierkorb verschieben: Das Laufwerk hat keinen Papierkorb, ein Element ist größer, als der Papierkorb zulässt, oder der Papierkorb ist für dieses Laufwerk deaktiviert. Sie wurden nicht gelöscht. Endgültig gelöschte Elemente können nicht wiederhergestellt werden. + [dialog] Body of the second confirmation after a Recycle Bin deletion. {0} is an already-formatted count of items Windows could not recycle; they are listed under this text. The first line is the question the user answers; the default answer is No. Keep the blank line, keep the statement that nothing has been deleted yet, and keep the warning that permanent deletion cannot be undone - never soften it. Use the glossary terms for the Recycle Bin and permanent deletion. + + + Nein, behalten + [button] The default, safe button of the 'Not moved to the Recycle Bin' dialog: answers No to the question and leaves every listed item where it is. Must read as a refusal. + + + …und {0} weitere + [label] Last line of the item list in the 'Not moved to the Recycle Bin' dialog when the list is too long to show in full. {0} is the already-formatted number of items not shown. Starts with a horizontal-ellipsis character in English. + + + Nicht in den Papierkorb verschoben + [dialog] Title of the second confirmation shown after a Recycle Bin deletion in which Windows could not move some items to the Recycle Bin. Those items were left untouched. Use the exact Windows term for the Recycle Bin. Its body is Safety_RecycleRefused_Body. + Prüfen Sie Duplikate, bevor Sie große oder alte Dateien löschen. [safety] Standing advice always listed last in the Dashboard "Recommended actions" list. Warns the user to inspect duplicate groups before deleting files. Must not be softened: it exists to stop unchecked deletion. diff --git a/src/StorageMaster.Core/Strings/en-US/Resources.resw b/src/StorageMaster.Core/Strings/en-US/Resources.resw index 7008fb7..108b303 100644 --- a/src/StorageMaster.Core/Strings/en-US/Resources.resw +++ b/src/StorageMaster.Core/Strings/en-US/Resources.resw @@ -2118,6 +2118,42 @@ One keeper per group stays untouched. Method: {2}. Recycle Bin [safety] Name of the deletion route, used inside two longer sentences on the Duplicates page: as {2} of Safety_Duplicates_ConfirmDelete_Body and as {0} of Safety_Duplicates_ConfirmDelete_Action ('Delete via Recycle Bin'). Use the exact Windows term. + + It changed, moved or disappeared after the duplicate analysis. + [safety] Reason shown under a duplicate that was not deleted: the file was changed, moved, replaced or removed after the duplicate analysis, so it was left alone. + + + It could not be read again to confirm it is still a duplicate. + [safety] Reason shown under a duplicate that was not deleted: just before deleting, the app reads the file again to confirm it still matches the file being kept, and that read failed. A technical detail line in English may follow. + + + Windows did not allow it to be deleted. It may be open in another program. + [safety] Reason shown under a duplicate that was not deleted because Windows refused the operation, most often because the file is open in another program or access was denied. A technical detail line in English may follow. + + + The file being kept could not be verified, so nothing in this group was deleted. + [safety] Reason shown under a duplicate that was not deleted because the file being kept in its group could not be verified (missing, changed or unreadable), so nothing in that group was deleted. Glossary: Keeper = beizubehaltende Datei / archivo que se conserva. + + + These files are still where they were. The reason is shown under each one. + [safety] Text of the warning banner on the Duplicates page that lists selected files a deletion left in place. Reassures the user that these files are untouched and points to the per-file reason below. Never imply the files are gone. + + + It no longer matches the file being kept. + [safety] Reason shown under a duplicate that was not deleted: read again just before deleting, it no longer matches the file being kept (glossary: Keeper = beizubehaltende Datei / archivo que se conserva). + + + The scan recorded no stable file identity for it. Scan again, then run the duplicate analysis again. + [safety] Reason shown under a duplicate that was not deleted: the scan recorded no stable file identity for it, so the app cannot prove the file was not replaced since. The fix is to scan the drive again and rerun the duplicate analysis. + + + Windows can't move it to the Recycle Bin here, and Recycle Bin mode never deletes permanently. + [safety] Reason shown under a duplicate that was not deleted in Recycle Bin mode: Windows could not put it in the Recycle Bin on that drive (network share, removable drive, too large, or bin turned off), and Recycle Bin mode never falls back to permanent deletion. Use the exact Windows term for the Recycle Bin. + + + {0} selected file(s) not deleted + [safety] Title of the warning banner on the Duplicates page after a deletion that left some selected files in place. {0} is an already-formatted count. Must say plainly that these files were NOT deleted; the list under the banner gives the reason for each file. + Permanently deleted {0} across {1} file(s) [safety] First half of the status line reported after duplicates were deleted permanently, with no way back. {0} is an already-formatted size, {1} an already-formatted file count. A sentence fragment continued by Duplicates_Status_DeleteDone and its variants - do not add a full stop. Must clearly say the deletion was permanent. @@ -2130,6 +2166,10 @@ One keeper per group stays untouched. Method: {2}. Moved {0} across {1} file(s) to the Recycle Bin [safety] First half of the status line reported after duplicates were deleted to the Windows Recycle Bin. {0} is an already-formatted size, {1} an already-formatted file count. A sentence fragment continued by Duplicates_Status_DeleteDone and its variants - do not add a full stop. Use the exact Windows term for the Recycle Bin. + + Moved {0} across {1} file(s) to the Recycle Bin and permanently deleted {2} across {3} file(s) + [safety] First half of the status line after a duplicate deletion in Recycle Bin mode where the user then agreed to delete the files Windows could not recycle permanently. {0} and {2} are already-formatted sizes, {1} and {3} already-formatted file counts. A sentence fragment continued by Duplicates_Status_DeleteDone and its variants - do not add a full stop. Must keep the recoverable part and the permanent part clearly apart. + · Cleanup quarantine [label] Small muted tag on a quarantine-list row saying the file was quarantined by a Cleanup-page rule rather than by duplicate deletion. The leading middle dot is a separator from the timestamp printed before it - keep it and the space that follows. @@ -2194,6 +2234,24 @@ One keeper per group stays untouched. Method: {2}. Permanent deletion only. Emptying the Recycle Bin cannot be undone. [safety] Safety note shown in its own line beneath the empty-Recycle-Bin suggestion on the Cleanup page. It states that this suggestion cannot be run in Recycle Bin or quarantine mode — the files go for good. Must not be softened or shortened. + + Delete these {0} item(s) permanently? + +Windows can't move them to the Recycle Bin here: the drive has no Recycle Bin, an item is larger than the Recycle Bin allows, or the Recycle Bin is turned off for this drive. They have not been deleted. Permanently deleted items can't be restored. + [dialog] Body of the second confirmation after a Recycle Bin deletion. {0} is an already-formatted count of items Windows could not recycle; they are listed under this text. The first line is the question the user answers; the default answer is No. Keep the blank line, keep the statement that nothing has been deleted yet, and keep the warning that permanent deletion cannot be undone - never soften it. Use the glossary terms for the Recycle Bin and permanent deletion. + + + No, keep them + [button] The default, safe button of the 'Not moved to the Recycle Bin' dialog: answers No to the question and leaves every listed item where it is. Must read as a refusal. + + + …and {0} more + [label] Last line of the item list in the 'Not moved to the Recycle Bin' dialog when the list is too long to show in full. {0} is the already-formatted number of items not shown. Starts with a horizontal-ellipsis character in English. + + + Not moved to the Recycle Bin + [dialog] Title of the second confirmation shown after a Recycle Bin deletion in which Windows could not move some items to the Recycle Bin. Those items were left untouched. Use the exact Windows term for the Recycle Bin. Its body is Safety_RecycleRefused_Body. + Review duplicates before deleting anything large or old. [safety] Standing advice always listed last in the Dashboard "Recommended actions" list. Warns the user to inspect duplicate groups before deleting files. Must not be softened: it exists to stop unchecked deletion. diff --git a/src/StorageMaster.Core/Strings/es-ES/Resources.resw b/src/StorageMaster.Core/Strings/es-ES/Resources.resw index 237423b..13a104f 100644 --- a/src/StorageMaster.Core/Strings/es-ES/Resources.resw +++ b/src/StorageMaster.Core/Strings/es-ES/Resources.resw @@ -2118,6 +2118,42 @@ En cada grupo se conserva intacto un archivo. Método: {2}. Papelera de reciclaje [safety] Name of the deletion route, used inside two longer sentences on the Duplicates page: as {2} of Safety_Duplicates_ConfirmDelete_Body and as {0} of Safety_Duplicates_ConfirmDelete_Action ('Delete via Recycle Bin'). Use the exact Windows term. + + El archivo cambió, se movió o desapareció después del análisis de duplicados. + [safety] Reason shown under a duplicate that was not deleted: the file was changed, moved, replaced or removed after the duplicate analysis, so it was left alone. + + + No se pudo volver a leer el archivo para confirmar que sigue siendo un duplicado. + [safety] Reason shown under a duplicate that was not deleted: just before deleting, the app reads the file again to confirm it still matches the file being kept, and that read failed. A technical detail line in English may follow. + + + Windows no permitió eliminarlo. Puede que el archivo esté abierto en otro programa. + [safety] Reason shown under a duplicate that was not deleted because Windows refused the operation, most often because the file is open in another program or access was denied. A technical detail line in English may follow. + + + No se pudo comprobar el archivo que se conserva, por lo que no se eliminó nada de este grupo. + [safety] Reason shown under a duplicate that was not deleted because the file being kept in its group could not be verified (missing, changed or unreadable), so nothing in that group was deleted. Glossary: Keeper = beizubehaltende Datei / archivo que se conserva. + + + Estos archivos siguen donde estaban. El motivo aparece debajo de cada uno. + [safety] Text of the warning banner on the Duplicates page that lists selected files a deletion left in place. Reassures the user that these files are untouched and points to the per-file reason below. Never imply the files are gone. + + + El archivo ya no coincide con el archivo que se conserva. + [safety] Reason shown under a duplicate that was not deleted: read again just before deleting, it no longer matches the file being kept (glossary: Keeper = beizubehaltende Datei / archivo que se conserva). + + + El análisis no registró una identidad de archivo estable. Vuelva a analizar y repita después el análisis de duplicados. + [safety] Reason shown under a duplicate that was not deleted: the scan recorded no stable file identity for it, so the app cannot prove the file was not replaced since. The fix is to scan the drive again and rerun the duplicate analysis. + + + Windows no puede moverlo a la Papelera de reciclaje aquí, y el modo Papelera de reciclaje nunca elimina definitivamente. + [safety] Reason shown under a duplicate that was not deleted in Recycle Bin mode: Windows could not put it in the Recycle Bin on that drive (network share, removable drive, too large, or bin turned off), and Recycle Bin mode never falls back to permanent deletion. Use the exact Windows term for the Recycle Bin. + + + {0} archivo(s) seleccionado(s) sin eliminar + [safety] Title of the warning banner on the Duplicates page after a deletion that left some selected files in place. {0} is an already-formatted count. Must say plainly that these files were NOT deleted; the list under the banner gives the reason for each file. + Se eliminaron definitivamente {0} en {1} archivo(s) [safety] First half of the status line reported after duplicates were deleted permanently, with no way back. {0} is an already-formatted size, {1} an already-formatted file count. A sentence fragment continued by Duplicates_Status_DeleteDone and its variants - do not add a full stop. Must clearly say the deletion was permanent. @@ -2130,6 +2166,10 @@ En cada grupo se conserva intacto un archivo. Método: {2}. Se movieron {0} en {1} archivo(s) a la Papelera de reciclaje [safety] First half of the status line reported after duplicates were deleted to the Windows Recycle Bin. {0} is an already-formatted size, {1} an already-formatted file count. A sentence fragment continued by Duplicates_Status_DeleteDone and its variants - do not add a full stop. Use the exact Windows term for the Recycle Bin. + + Se movieron {0} en {1} archivo(s) a la Papelera de reciclaje y se eliminaron definitivamente {2} en {3} archivo(s) + [safety] First half of the status line after a duplicate deletion in Recycle Bin mode where the user then agreed to delete the files Windows could not recycle permanently. {0} and {2} are already-formatted sizes, {1} and {3} already-formatted file counts. A sentence fragment continued by Duplicates_Status_DeleteDone and its variants - do not add a full stop. Must keep the recoverable part and the permanent part clearly apart. + · Cuarentena de limpieza [label] Small muted tag on a quarantine-list row saying the file was quarantined by a Cleanup-page rule rather than by duplicate deletion. The leading middle dot is a separator from the timestamp printed before it - keep it and the space that follows. @@ -2194,6 +2234,24 @@ En cada grupo se conserva intacto un archivo. Método: {2}. Solo eliminación definitiva. Vaciar la Papelera de reciclaje no se puede deshacer. [safety] Safety note shown in its own line beneath the empty-Recycle-Bin suggestion on the Cleanup page. It states that this suggestion cannot be run in Recycle Bin or quarantine mode — the files go for good. Must not be softened or shortened. + + ¿Eliminar definitivamente estos {0} elemento(s)? + +Windows no puede moverlos a la Papelera de reciclaje aquí: la unidad no tiene Papelera de reciclaje, un elemento supera el tamaño que admite la Papelera de reciclaje o la Papelera de reciclaje está desactivada para esta unidad. No se han eliminado. Los elementos eliminados definitivamente no se pueden restaurar. + [dialog] Body of the second confirmation after a Recycle Bin deletion. {0} is an already-formatted count of items Windows could not recycle; they are listed under this text. The first line is the question the user answers; the default answer is No. Keep the blank line, keep the statement that nothing has been deleted yet, and keep the warning that permanent deletion cannot be undone - never soften it. Use the glossary terms for the Recycle Bin and permanent deletion. + + + No, conservarlos + [button] The default, safe button of the 'Not moved to the Recycle Bin' dialog: answers No to the question and leaves every listed item where it is. Must read as a refusal. + + + …y {0} más + [label] Last line of the item list in the 'Not moved to the Recycle Bin' dialog when the list is too long to show in full. {0} is the already-formatted number of items not shown. Starts with a horizontal-ellipsis character in English. + + + No se movieron a la Papelera de reciclaje + [dialog] Title of the second confirmation shown after a Recycle Bin deletion in which Windows could not move some items to the Recycle Bin. Those items were left untouched. Use the exact Windows term for the Recycle Bin. Its body is Safety_RecycleRefused_Body. + Revise los duplicados antes de eliminar nada grande o antiguo. [safety] Standing advice always listed last in the Dashboard "Recommended actions" list. Warns the user to inspect duplicate groups before deleting files. Must not be softened: it exists to stop unchecked deletion. diff --git a/src/StorageMaster.Platform.Windows/FileDeleter.cs b/src/StorageMaster.Platform.Windows/FileDeleter.cs index 7b701e8..fd24fbc 100644 --- a/src/StorageMaster.Platform.Windows/FileDeleter.cs +++ b/src/StorageMaster.Platform.Windows/FileDeleter.cs @@ -149,7 +149,12 @@ public async Task DeleteAsync( if (notRecycled is not null) { _logger.LogWarning("Not moved to the Recycle Bin: {Path} — {Error}", request.Path, notRecycled); - return new DeletionOutcome(requestedPath, false, 0, notRecycled); + return new DeletionOutcome( + requestedPath, + false, + 0, + notRecycled, + RecycleBinRefused: string.Equals(notRecycled, RecycleBinUnavailableError, StringComparison.Ordinal)); } } else diff --git a/src/StorageMaster.Platform.Windows/TurboFileScanner.cs b/src/StorageMaster.Platform.Windows/TurboFileScanner.cs index 13d49e6..98ede27 100644 --- a/src/StorageMaster.Platform.Windows/TurboFileScanner.cs +++ b/src/StorageMaster.Platform.Windows/TurboFileScanner.cs @@ -138,6 +138,7 @@ public async Task ScanAsync( // consumer touches this for every record, and three hashes plus three // probes per file is pure overhead on the pipeline's only reader. var parentMetrics = new Dictionary(StringComparer.OrdinalIgnoreCase); + var hardLinks = new HardLinkTracker(); var folderMetricsPersisted = false; var processStarted = false; @@ -154,7 +155,7 @@ async Task FlushFileBufferAsync(CancellationToken ct) await _repo.InsertFileEntriesAsync(batch, ct).ConfigureAwait(false); fileBuffer.Clear(); persistedFileCount += batch.LongLength; - persistedBytes += batch.Sum(static entry => entry.SizeBytes); + persistedBytes += batch.Sum(HardLinkTracker.CountedBytes); } async Task FlushFolderBufferAsync(CancellationToken ct) @@ -410,6 +411,7 @@ static void AddSubFolderToParent( var modUtc = ReadUtcTimestamp(rec.ModifiedUtcTicks, rec.ModifiedUnix); var createUtc = ReadUtcTimestamp(rec.CreatedUtcTicks, rec.CreatedUnix); var attributes = ReadAttributes(rec); + var identity = ReadIdentity(rec); var fe = new FileEntry { @@ -424,16 +426,18 @@ static void AddSubFolderToParent( AccessedUtc = modUtc, Attributes = attributes, Category = FileTypeCategorizor.Categorize(ext), - Identity = ReadIdentity(rec), + Identity = identity, IsReparsePoint = (attributes & FileAttributes.ReparsePoint) != 0, + IsAdditionalHardLink = !hardLinks.IsFirstLink(identity), }; fileBuffer.Add(fe); fileCount++; - totalBytes += (long)rec.Size; + var countedBytes = HardLinkTracker.CountedBytes(fe); + totalBytes += countedBytes; var parentDir = Path.GetDirectoryName(rec.Path); if (parentDir is not null) - AddFileToParent(parentMetrics, parentDir, (long)rec.Size); + AddFileToParent(parentMetrics, parentDir, countedBytes); if (fileBuffer.Count >= 500) await FlushFileBufferAsync(abort.Token).ConfigureAwait(false); diff --git a/src/StorageMaster.Platform.Windows/WicImageHashDecoder.cs b/src/StorageMaster.Platform.Windows/WicImageHashDecoder.cs new file mode 100644 index 0000000..71f1e70 --- /dev/null +++ b/src/StorageMaster.Platform.Windows/WicImageHashDecoder.cs @@ -0,0 +1,153 @@ +using StorageMaster.Core.Interfaces; +using Windows.Graphics.Imaging; + +namespace StorageMaster.Platform.Windows; + +/// +/// on the Windows Imaging Component, through +/// Windows.Graphics.Imaging. +/// +/// These are the decoders File Explorer uses for thumbnails. Windows Update keeps +/// them patched, and any codec the user has installed (HEIF, WebP, camera raw) works +/// without the app shipping one. That replaced ImageSharp, whose 3.x line stopped +/// receiving security fixes. +/// +/// +/// The scale-down happens inside the decode: WIC asks the codec for a reduced +/// image where it can (JPEG decodes straight from its scaled IDCT), so a 50-megapixel +/// photo is never materialised at full size just to become 32×32. +/// +/// +public sealed class WicImageHashDecoder : IImageHashDecoder +{ + private const string OrientationProperty = "System.Photo.Orientation"; + + public async Task DecodeAsync(Stream stream, int size, CancellationToken ct = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(size, 1); + + using var randomAccess = stream.AsRandomAccessStream(); + var decoder = await OpenAsync(randomAccess, ct).ConfigureAwait(false); + var header = await ReadHeaderAsync(decoder, ct).ConfigureAwait(false); + + // Stretch-to-square with Fant (area-averaging) resampling, EXIF orientation + // applied, straight alpha so transparent pixels keep the colour they store, + // and no colour management: the hash compares structure, not appearance. + var transform = new BitmapTransform + { + ScaledWidth = (uint)size, + ScaledHeight = (uint)size, + InterpolationMode = BitmapInterpolationMode.Fant, + }; + PixelDataProvider pixelData; + try + { + pixelData = await decoder.GetPixelDataAsync( + BitmapPixelFormat.Bgra8, + BitmapAlphaMode.Straight, + transform, + ExifOrientationMode.RespectExifOrientation, + ColorManagementMode.DoNotColorManage) + .AsTask(ct) + .ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + throw DecodeFailure("decode the pixels of", ex); + } + + var bgra = pixelData.DetachPixelData(); + if (bgra.Length != size * size * 4) + { + throw new InvalidDataException( + $"The image decoder returned {bgra.Length} bytes for a {size}x{size} BGRA surface."); + } + + return new ImageHashSurface(ToLuminance(bgra), size, header); + } + + public async Task IdentifyAsync(Stream stream, CancellationToken ct = default) + { + using var randomAccess = stream.AsRandomAccessStream(); + var decoder = await OpenAsync(randomAccess, ct).ConfigureAwait(false); + return await ReadHeaderAsync(decoder, ct).ConfigureAwait(false); + } + + private static async Task OpenAsync( + global::Windows.Storage.Streams.IRandomAccessStream stream, + CancellationToken ct) + { + try + { + return await BitmapDecoder.CreateAsync(stream).AsTask(ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + throw DecodeFailure("read", ex); + } + } + + /// + /// WinRT decode failures often carry an empty message, which would surface as a + /// blank per-file error. Name the failure and keep the HRESULT for diagnosis. + /// + private static InvalidDataException DecodeFailure(string action, Exception inner) + { + var detail = string.IsNullOrWhiteSpace(inner.Message) ? string.Empty : " " + inner.Message.Trim(); + return new InvalidDataException( + $"Windows could not {action} this image (HRESULT 0x{inner.HResult:X8}).{detail}", + inner); + } + + /// + /// Rec. 709 luma, the weighting the hash was computed with before. Integer + /// arithmetic (coefficients scaled by 2^16) keeps the result identical on every + /// machine. + /// + internal static byte[] ToLuminance(ReadOnlySpan bgra) + { + var luminance = new byte[bgra.Length / 4]; + for (int pixel = 0, offset = 0; pixel < luminance.Length; pixel++, offset += 4) + { + var b = bgra[offset]; + var g = bgra[offset + 1]; + var r = bgra[offset + 2]; + luminance[pixel] = (byte)(((13933 * r) + (46871 * g) + (4732 * b) + 32768) >> 16); + } + + return luminance; + } + + private static async Task ReadHeaderAsync(BitmapDecoder decoder, CancellationToken ct) + { + var orientation = await ReadOrientationAsync(decoder, ct).ConfigureAwait(false); + return new ImageHeader( + checked((int)decoder.OrientedPixelWidth), + checked((int)decoder.OrientedPixelHeight), + orientation); + } + + private static async Task ReadOrientationAsync(BitmapDecoder decoder, CancellationToken ct) + { + try + { + var properties = await decoder.BitmapProperties + .GetPropertiesAsync([OrientationProperty]) + .AsTask(ct) + .ConfigureAwait(false); + if (properties.TryGetValue(OrientationProperty, out var value) && + value.Value is ushort orientation && + orientation is >= 1 and <= 8) + { + return orientation; + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Formats without a metadata block (BMP, most PNGs) report the property as + // unsupported rather than absent. Either way the image is upright. + } + + return 1; + } +} diff --git a/src/StorageMaster.Storage/Repositories/ScanRepository.cs b/src/StorageMaster.Storage/Repositories/ScanRepository.cs index eb1f994..c455ff9 100644 --- a/src/StorageMaster.Storage/Repositories/ScanRepository.cs +++ b/src/StorageMaster.Storage/Repositories/ScanRepository.cs @@ -136,11 +136,11 @@ public async Task InsertFileEntriesAsync(IReadOnlyList entries, Cance INSERT INTO FileEntries (SessionId, FullPath, FileName, Extension, SizeBytes, CreatedUtc, ModifiedUtc, AccessedUtc, Attributes, Category, IsReparsePoint, - NormalizedFullPath, IdentityVolumeSerial, IdentityFileIndex) + NormalizedFullPath, IdentityVolumeSerial, IdentityFileIndex, IsAdditionalHardLink) VALUES ($sid, $path, $name, $ext, $size, $created, $modified, $accessed, $attrs, $cat, $reparse, - $normalized, $identityVolume, $identityIndex) + $normalized, $identityVolume, $identityIndex, $additionalLink) ON CONFLICT(SessionId, NormalizedFullPath) DO UPDATE SET FileName = excluded.FileName, Extension = excluded.Extension, @@ -152,7 +152,8 @@ ON CONFLICT(SessionId, NormalizedFullPath) DO UPDATE SET Category = excluded.Category, IsReparsePoint = excluded.IsReparsePoint, IdentityVolumeSerial = excluded.IdentityVolumeSerial, - IdentityFileIndex = excluded.IdentityFileIndex; + IdentityFileIndex = excluded.IdentityFileIndex, + IsAdditionalHardLink = excluded.IsAdditionalHardLink; """; var pSid = cmd.Parameters.Add("$sid", SqliteType.Integer); @@ -169,6 +170,7 @@ ON CONFLICT(SessionId, NormalizedFullPath) DO UPDATE SET var pNormalized = cmd.Parameters.Add("$normalized", SqliteType.Text); var pIdentityVolume = cmd.Parameters.Add("$identityVolume", SqliteType.Text); var pIdentityIndex = cmd.Parameters.Add("$identityIndex", SqliteType.Text); + var pAdditionalLink = cmd.Parameters.Add("$additionalLink", SqliteType.Integer); foreach (var e in entries) { @@ -188,6 +190,7 @@ ON CONFLICT(SessionId, NormalizedFullPath) DO UPDATE SET pIdentityIndex.Value = e.Identity is null ? DBNull.Value : e.Identity.FileIndex.ToString(CultureInfo.InvariantCulture); + pAdditionalLink.Value = e.IsAdditionalHardLink ? 1 : 0; await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false); } @@ -448,7 +451,10 @@ FROM FolderEntries await using var conn = await _db.GetConnectionAsync(ct); using var cmd = conn.CreateCommand(); cmd.CommandText = """ - SELECT Category, COUNT(*) AS FileCount, SUM(SizeBytes) AS TotalBytes + SELECT Category, + COUNT(*) AS FileCount, + -- A file with several hard links occupies its size once. + SUM(CASE WHEN IsAdditionalHardLink = 0 THEN SizeBytes ELSE 0 END) AS TotalBytes FROM FileEntries WHERE SessionId = $sid GROUP BY Category; diff --git a/src/StorageMaster.Storage/Schema/DatabaseSchema.cs b/src/StorageMaster.Storage/Schema/DatabaseSchema.cs index 0b5b653..75abf53 100644 --- a/src/StorageMaster.Storage/Schema/DatabaseSchema.cs +++ b/src/StorageMaster.Storage/Schema/DatabaseSchema.cs @@ -7,7 +7,7 @@ /// internal static class DatabaseSchema { - internal const int CurrentVersion = 15; + internal const int CurrentVersion = 16; /// SQL executed once at version 1 creation. internal static readonly string[] V1Statements = @@ -569,4 +569,19 @@ ELSE substr(trimmed, 1, length(trimmed) - 1) "CREATE INDEX IF NOT EXISTS IX_DuplicateErrors_Run_File ON DuplicateErrors (RunId, FileEntryId);", "CREATE INDEX IF NOT EXISTS IX_DuplicateSignatures_FileEntryId ON DuplicateSignatures (FileEntryId);", ]; + + /// + /// V16: mark file entries that are a further hard link to a file the scan had + /// already counted. + /// + /// The scanner now counts each file's size once in folder and session totals, + /// whatever number of names it has. The per-category breakdown is summed in SQL, + /// so it needs to know which rows to leave out. Rows written before this version + /// default to 0 and keep counting every link, exactly as they were displayed. + /// + /// + internal static readonly string[] V16Statements = + [ + "ALTER TABLE FileEntries ADD COLUMN IsAdditionalHardLink INTEGER NOT NULL DEFAULT 0;", + ]; } diff --git a/src/StorageMaster.Storage/StorageDbContext.cs b/src/StorageMaster.Storage/StorageDbContext.cs index 9d9be79..6f2f0dc 100644 --- a/src/StorageMaster.Storage/StorageDbContext.cs +++ b/src/StorageMaster.Storage/StorageDbContext.cs @@ -299,6 +299,9 @@ private async Task MigrateAsync(SqliteConnection conn, CancellationToken ct) if (current < 15) await ApplyMigrationAsync(conn, transaction, DatabaseSchema.V15Statements, 15, ct).ConfigureAwait(false); + if (current < 16) + await ApplyMigrationAsync(conn, transaction, DatabaseSchema.V16Statements, 16, ct).ConfigureAwait(false); + await transaction.CommitAsync(ct).ConfigureAwait(false); } diff --git a/src/StorageMaster.UI/Infrastructure/DialogService.cs b/src/StorageMaster.UI/Infrastructure/DialogService.cs index f696ccf..035a396 100644 --- a/src/StorageMaster.UI/Infrastructure/DialogService.cs +++ b/src/StorageMaster.UI/Infrastructure/DialogService.cs @@ -1,5 +1,7 @@ +using System.Globalization; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; +using StorageMaster.Core.Localization; namespace StorageMaster.UI.Infrastructure; @@ -24,6 +26,70 @@ public async Task ConfirmAsync( return result == ContentDialogResult.Primary; } + /// + /// Items listed in full before the list is cut short. A refusal list can run to + /// hundreds of paths; past this the dialog would only scroll, and the count in + /// the message already says how many there are. + /// + internal const int MaxListedItems = 200; + + public async Task ConfirmItemsAsync( + string title, + string message, + IReadOnlyList items, + string primaryButtonText, + string closeButtonText) + { + var list = new StackPanel { Spacing = 2 }; + foreach (var item in items.Take(MaxListedItems)) + { + list.Children.Add(new TextBlock + { + Text = item, + FontSize = 12, + TextWrapping = TextWrapping.Wrap, + IsTextSelectionEnabled = true, + }); + } + + if (items.Count > MaxListedItems) + { + list.Children.Add(new TextBlock + { + Text = Loc.Format( + "Safety_RecycleRefused_More", + (items.Count - MaxListedItems).ToString("N0", CultureInfo.CurrentCulture)), + FontSize = 12, + Opacity = 0.7, + }); + } + + var content = new StackPanel { Spacing = 12 }; + content.Children.Add(new TextBlock + { + Text = message, + TextWrapping = TextWrapping.WrapWholeWords, + }); + content.Children.Add(new ScrollViewer + { + Content = list, + MaxHeight = 240, + VerticalScrollBarVisibility = ScrollBarVisibility.Auto, + HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, + }); + + var result = await ShowAsync(new ContentDialog + { + Title = title, + Content = content, + PrimaryButtonText = primaryButtonText, + CloseButtonText = closeButtonText, + DefaultButton = ContentDialogButton.Close, + }).ConfigureAwait(true); + + return result == ContentDialogResult.Primary; + } + public async Task ShowErrorAsync( string title, string message, diff --git a/src/StorageMaster.UI/Infrastructure/DuplicatePreviewService.cs b/src/StorageMaster.UI/Infrastructure/DuplicatePreviewService.cs index 26a14b0..fab019c 100644 --- a/src/StorageMaster.UI/Infrastructure/DuplicatePreviewService.cs +++ b/src/StorageMaster.UI/Infrastructure/DuplicatePreviewService.cs @@ -1,7 +1,6 @@ using System.Diagnostics; using System.Security.Cryptography; using System.Text; -using SixLabors.ImageSharp; using StorageMaster.Core.Interfaces; using StorageMaster.Core.Models; using StorageMaster.Core.Safety; @@ -9,7 +8,8 @@ namespace StorageMaster.UI.Infrastructure; public sealed class DuplicatePreviewService( - ISettingsRepository settingsRepository) : IDuplicatePreviewService + ISettingsRepository settingsRepository, + IImageHashDecoder imageDecoder) : IDuplicatePreviewService { public async Task BuildPreviewAsync( DuplicateMethod method, @@ -41,7 +41,7 @@ private static DuplicatePreviewResult BuildExactPreview(IReadOnlyList BuildImagePreviewAsync( + private async Task BuildImagePreviewAsync( IReadOnlyList members, CancellationToken ct) { @@ -52,9 +52,15 @@ private static async Task BuildImagePreviewAsync( var subtitle = $"{member.SizeBytes:N0} bytes"; try { - var info = await Image.IdentifyAsync(member.FullPath, ct); - if (info is not null) - subtitle = $"{info.Width}x{info.Height} • {member.SizeBytes:N0} bytes"; + await using var stream = new FileStream( + member.FullPath, + FileMode.Open, + FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete, + bufferSize: 4096, + FileOptions.Asynchronous); + var info = await imageDecoder.IdentifyAsync(stream, ct); + subtitle = $"{info.Width}x{info.Height} • {member.SizeBytes:N0} bytes"; } catch { diff --git a/src/StorageMaster.UI/Infrastructure/IDialogService.cs b/src/StorageMaster.UI/Infrastructure/IDialogService.cs index 7476e49..b91167d 100644 --- a/src/StorageMaster.UI/Infrastructure/IDialogService.cs +++ b/src/StorageMaster.UI/Infrastructure/IDialogService.cs @@ -11,6 +11,18 @@ Task ConfirmAsync( string closeButtonText = "Cancel", ContentDialogButton defaultButton = ContentDialogButton.Close); + /// + /// Asks a question about a list of items and shows the items under it. The close + /// button — the answer that changes nothing — is always the default, so Enter + /// or Esc never confirms. + /// + Task ConfirmItemsAsync( + string title, + string message, + IReadOnlyList items, + string primaryButtonText, + string closeButtonText); + Task ShowErrorAsync( string title, string message, diff --git a/src/StorageMaster.UI/Infrastructure/ScenarioCatalogue.cs b/src/StorageMaster.UI/Infrastructure/ScenarioCatalogue.cs index 89e8900..bb9ea9d 100644 --- a/src/StorageMaster.UI/Infrastructure/ScenarioCatalogue.cs +++ b/src/StorageMaster.UI/Infrastructure/ScenarioCatalogue.cs @@ -76,6 +76,16 @@ public static class ScenarioCatalogue BodyKey: "Safety_SendToRecycleBin_Body", PrimaryKey: "Safety_SendToRecycleBin", BodyArguments: ["rootfs.vhdx", "7,70 GB"]), + + // The second question after a Recycle Bin run: what Windows would not recycle + // may be deleted permanently instead. The real dialog lists the items under + // the body; the harness shows the wording, which is what needs review. + new( + Id: "dialog-recyclebin-refused", + TitleKey: "Safety_RecycleRefused_Title", + BodyKey: "Safety_RecycleRefused_Body", + PrimaryKey: "Safety_PermanentDelete", + BodyArguments: ["37"]), ]; /// diff --git a/src/StorageMaster.UI/Pages/CleanupPage.xaml.cs b/src/StorageMaster.UI/Pages/CleanupPage.xaml.cs index 9b9dc65..96087e5 100644 --- a/src/StorageMaster.UI/Pages/CleanupPage.xaml.cs +++ b/src/StorageMaster.UI/Pages/CleanupPage.xaml.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Microsoft.Extensions.DependencyInjection; using Microsoft.UI; using Microsoft.UI.Text; @@ -7,6 +8,7 @@ using Microsoft.UI.Xaml.Navigation; using StorageMaster.Core.Interfaces; using StorageMaster.Core.Localization; +using StorageMaster.UI.Infrastructure; namespace StorageMaster.UI.Pages; @@ -177,6 +179,20 @@ private async Task ShowReportLoopAsync(int navigationGeneration) break; } } + else if (!wasDry && + wasMethod == DeletionMethod.RecycleBin && + ViewModel.RecycleBinRefusedPaths is { Count: > 0 } refusedPaths) + { + // Recycle Bin mode never deletes permanently on its own. What Windows + // would not recycle is still in place; deleting it permanently is a + // separate decision, asked with the items listed and "no" as the + // default. The next pass shows that run's own report. + if (!await ConfirmPermanentForRecycleBinRefusalsAsync(refusedPaths, navigationGeneration) || + !await ViewModel.RunPermanentForRecycleBinRefusalsAsync()) + { + break; + } + } else { break; // User dismissed, or no further action available. @@ -184,6 +200,24 @@ private async Task ShowReportLoopAsync(int navigationGeneration) } } + private async Task ConfirmPermanentForRecycleBinRefusalsAsync( + IReadOnlyList refusedPaths, + int navigationGeneration) + { + if (!IsCurrentNavigation(navigationGeneration)) + return false; + + var confirmed = await App.Services.GetRequiredService().ConfirmItemsAsync( + Loc.Get("Safety_RecycleRefused_Title"), + Loc.Format( + "Safety_RecycleRefused_Body", + refusedPaths.Count.ToString("N0", CultureInfo.CurrentCulture)), + refusedPaths, + Loc.Get("Safety_PermanentDelete"), + Loc.Get("Safety_RecycleRefused_Keep")); + return confirmed && IsCurrentNavigation(navigationGeneration); + } + // ── Dialog builder ───────────────────────────────────────────────────── private ContentDialog BuildReportDialog( diff --git a/src/StorageMaster.UI/Pages/CleanupViewModel.cs b/src/StorageMaster.UI/Pages/CleanupViewModel.cs index 2d7c9ec..7bf286d 100644 --- a/src/StorageMaster.UI/Pages/CleanupViewModel.cs +++ b/src/StorageMaster.UI/Pages/CleanupViewModel.cs @@ -215,6 +215,17 @@ partial void OnIsExecutingChanged(bool value) // Stored between initial run and any follow-up re-runs. private IReadOnlyList _lastSelectedSuggestions = []; + + /// + /// After a real Recycle Bin run: the targets Windows would not recycle, as + /// permanent-deletion suggestions waiting for the user's explicit yes. Empty + /// otherwise, and emptied as soon as it is used or another run starts. + /// + private IReadOnlyList _recycleBinRefusalRetry = []; + + /// Targets the last Recycle Bin run left in place that may be deleted permanently instead. + public IReadOnlyList RecycleBinRefusedPaths => + _recycleBinRefusalRetry.SelectMany(static suggestion => suggestion.TargetPaths).ToArray(); private CancellationTokenSource? _analysisCts; private int _analysisGeneration; private bool _isInitializing; @@ -549,6 +560,22 @@ public async Task RunCleanupWithMethodAsync(bool dryRun, DeletionMethod me return true; } + /// + /// Permanently deletes the targets the last Recycle Bin run left in place. Only + /// call after the user confirmed the listed items; returns false when there is + /// nothing to retry. Every target is checked against its scan-time snapshot again. + /// + public async Task RunPermanentForRecycleBinRefusalsAsync() + { + var retry = _recycleBinRefusalRetry; + _recycleBinRefusalRetry = []; + if (retry.Count == 0) + return false; + + await RunCleanupCoreAsync(dryRun: false, DeletionMethod.Permanent, retry); + return true; + } + public string LastRunSelectedSizeDisplay => ByteSizeConverter.Format( _lastSelectedSuggestions.Sum(suggestion => suggestion.EstimatedBytes)); @@ -558,6 +585,7 @@ private async Task RunCleanupCoreAsync( IReadOnlyList suggestions) { IsExecuting = true; + _recycleBinRefusalRetry = []; LastRunWasDryRun = dryRun; LastRunDeletionMethod = method; LastPreviewAllowsExecution = false; @@ -604,6 +632,8 @@ void Apply() error)); } HasExecutionResults = ExecutionResults.Count > 0; + if (!dryRun && method == DeletionMethod.RecycleBin) + _recycleBinRefusalRetry = CleanupEngine.BuildPermanentRetryForRecycleBinRefusals(suggestions, results); long totalFreed = results.Sum(r => r.BytesFreed); int succeeded = results.Count(r => r.Status == CleanupResultStatus.Success); diff --git a/src/StorageMaster.UI/Pages/DuplicatesPage.xaml b/src/StorageMaster.UI/Pages/DuplicatesPage.xaml index 508ac7c..4d46045 100644 --- a/src/StorageMaster.UI/Pages/DuplicatesPage.xaml +++ b/src/StorageMaster.UI/Pages/DuplicatesPage.xaml @@ -251,6 +251,36 @@ + + + + + + + + + + + + + + + + + diff --git a/src/StorageMaster.UI/Pages/DuplicatesViewModel.cs b/src/StorageMaster.UI/Pages/DuplicatesViewModel.cs index 1371a6b..0ff684a 100644 --- a/src/StorageMaster.UI/Pages/DuplicatesViewModel.cs +++ b/src/StorageMaster.UI/Pages/DuplicatesViewModel.cs @@ -3,6 +3,7 @@ using System.Text.Json; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; +using StorageMaster.Core.Deduplication; using StorageMaster.Core.Interfaces; using StorageMaster.Core.Localization; using StorageMaster.Core.Models; @@ -26,6 +27,12 @@ public sealed record DuplicateMethodFilterOption(string Label, DuplicateMethod? public string SettingsName { get; init; } = string.Empty; } +/// A selected duplicate the last deletion left in place, and why, as shown on the page. +public sealed record DuplicateNotDeletedItem(string Path, string Reason, string Detail) +{ + public bool HasDetail => !string.IsNullOrWhiteSpace(Detail); +} + public sealed partial class DuplicateMemberItem : ObservableObject { [ObservableProperty] private bool _isSelected; @@ -173,7 +180,13 @@ private sealed record DuplicateDeletionOutcome( long ProcessedBytes, int DeletedFileCount, IReadOnlyList GroupErrors, - IReadOnlyList PersistenceWarnings); + IReadOnlyList PersistenceWarnings, + IReadOnlyList Skipped); + + /// The members of one planned group that were left in place, and why. + private sealed record DuplicateDeletionGroupSkips( + DuplicateDeletionGroupPlan GroupPlan, + IReadOnlyList Skipped); private readonly IScanRepository _scanRepository; private readonly ISettingsRepository _settingsRepository; @@ -251,6 +264,7 @@ private sealed record DuplicateDeletionOutcome( public ObservableCollection Errors { get; } = []; public ObservableCollection PreviewItems { get; } = []; public ObservableCollection QuarantineItems { get; } = []; + public ObservableCollection NotDeletedItems { get; } = []; public Array KeeperPolicyOptions => Enum.GetValues(typeof(KeeperPolicy)); public Array ScopeModeOptions => Enum.GetValues(typeof(DuplicateScopeMode)); @@ -280,6 +294,9 @@ private sealed record DuplicateDeletionOutcome( public bool HasSelectedGroup => SelectedGroup is not null; public bool HasPreviewItems => PreviewItems.Count > 0; public bool HasQuarantineItems => QuarantineItems.Count > 0; + public bool HasNotDeletedItems => NotDeletedItems.Count > 0; + public string NotDeletedTitle => + Loc.Format("Safety_Duplicates_NotDeleted_Title", NotDeletedItems.Count.ToString("N0")); public bool IsWholeSessionScope => SelectedScopeMode == DuplicateScopeMode.WholeSession; public bool IsIncludedScopeMode => SelectedScopeMode == DuplicateScopeMode.IncludedFolders; public bool IsExcludedScopeMode => SelectedScopeMode == DuplicateScopeMode.ExcludedFolders; @@ -371,6 +388,7 @@ public DuplicatesViewModel( partial void OnSelectedSessionChanged(ScanSession? value) { OnPropertyChanged(nameof(CanRun)); + SetNotDeletedItems([]); if (!_suppressReactiveLoads) _ = LoadLatestRunSafeAsync(value?.Id, CurrentLifetimeToken); } @@ -1043,6 +1061,8 @@ private async Task DeleteSelectedAsync() if (!confirmed || !IsCurrentLifetime(lifetimeVersion)) return; + SetNotDeletedItems([]); + // Created here, on the UI thread, so Progress captures the dispatcher's // synchronisation context: the pool thread reports text and the assignment // to the bound property still happens on the UI thread. @@ -1061,38 +1081,95 @@ private async Task DeleteSelectedAsync() if (!IsCurrentLifetime(lifetimeVersion)) return; - var processedBytes = outcome.ProcessedBytes; - var processedFileCount = outcome.DeletedFileCount; - var groupErrors = outcome.GroupErrors; - var persistenceWarnings = outcome.PersistenceWarnings; - var processedSize = ByteSizeConverter.Format(processedBytes); - var processedCount = processedFileCount.ToString("N0"); - var operationSummary = plan.Method switch + // Recycle Bin mode never deletes permanently on its own. Files Windows could + // not recycle are still in place; deleting them permanently instead is a + // separate decision, asked with the files listed and "no" as the default, + // and the retry goes through every live check again. + DuplicateDeletionOutcome? permanentRetry = null; + var refused = plan.Method == DeletionMethod.RecycleBin + ? outcome.Skipped + .SelectMany(static group => group.Skipped) + .Where(static skip => skip.Reason == DuplicateDeletionSkipReason.RecycleBinUnavailable) + .ToArray() + : []; + if (refused.Length > 0) { - DeletionMethod.Quarantine => Loc.Format("Safety_Duplicates_Outcome_Quarantine", processedSize, processedCount), - DeletionMethod.RecycleBin => Loc.Format("Safety_Duplicates_Outcome_RecycleBin", processedSize, processedCount), + var deletePermanently = await _dialogs.ConfirmItemsAsync( + Loc.Get("Safety_RecycleRefused_Title"), + Loc.Format("Safety_RecycleRefused_Body", refused.Length.ToString("N0")), + refused.Select(static skip => skip.Path).ToArray(), + Loc.Get("Safety_PermanentDelete"), + Loc.Get("Safety_RecycleRefused_Keep")); + if (!IsCurrentLifetime(lifetimeVersion)) + return; + + if (deletePermanently) + { + var retryPlan = BuildPermanentRetryPlan(plan, outcome); + permanentRetry = await Task.Run(() => ExecuteDeletionPlanAsync(retryPlan, progress)); + if (!IsCurrentLifetime(lifetimeVersion)) + return; + } + } + + var processedSize = ByteSizeConverter.Format(outcome.ProcessedBytes); + var processedCount = outcome.DeletedFileCount.ToString("N0"); + var operationSummary = (plan.Method, permanentRetry) switch + { + (DeletionMethod.RecycleBin, not null) => Loc.Format( + "Safety_Duplicates_Outcome_RecycleBinThenPermanent", + processedSize, + processedCount, + ByteSizeConverter.Format(permanentRetry.ProcessedBytes), + permanentRetry.DeletedFileCount.ToString("N0")), + (DeletionMethod.Quarantine, _) => Loc.Format("Safety_Duplicates_Outcome_Quarantine", processedSize, processedCount), + (DeletionMethod.RecycleBin, _) => Loc.Format("Safety_Duplicates_Outcome_RecycleBin", processedSize, processedCount), _ => Loc.Format("Safety_Duplicates_Outcome_Permanent", processedSize, processedCount), }; - StatusText = (groupErrors.Count, persistenceWarnings.Count) switch + + var groupErrors = outcome.GroupErrors + .Concat(permanentRetry?.GroupErrors ?? []) + .ToArray(); + var persistenceWarnings = outcome.PersistenceWarnings + .Concat(permanentRetry?.PersistenceWarnings ?? []) + .ToArray(); + StatusText = (groupErrors.Length, persistenceWarnings.Length) switch { (0, 0) => Loc.Format("Duplicates_Status_DeleteDone", operationSummary, plan.Page.ToString("N0")), (0, _) => Loc.Format( "Duplicates_Status_DeleteWarnings", operationSummary, - persistenceWarnings.Count.ToString("N0"), + persistenceWarnings.Length.ToString("N0"), persistenceWarnings[0]), (_, 0) => Loc.Format( "Duplicates_Status_DeleteErrors", operationSummary, - groupErrors.Count.ToString("N0"), + groupErrors.Length.ToString("N0"), groupErrors[0]), _ => Loc.Format( "Duplicates_Status_DeleteErrorsAndWarnings", operationSummary, - groupErrors.Count.ToString("N0"), - persistenceWarnings.Count.ToString("N0"), + groupErrors.Length.ToString("N0"), + persistenceWarnings.Length.ToString("N0"), groupErrors[0]), }; + + // A refusal the permanent retry dealt with is replaced by what the retry + // did: nothing if the file is now gone, its own reason if it is not. + var retried = permanentRetry is null + ? new HashSet() + : refused.Select(static skip => skip.MemberId).ToHashSet(); + var stillInPlace = outcome.Skipped + .SelectMany(static group => group.Skipped) + .Where(skip => !retried.Contains(skip.MemberId)) + .Concat(permanentRetry?.Skipped.SelectMany(static group => group.Skipped) ?? []); + SetNotDeletedItems(stillInPlace + .Select(static skip => new DuplicateNotDeletedItem( + skip.Path, + Loc.Get(DuplicateDeletionSkips.ResourceKey(skip.Reason)), + skip.Detail ?? string.Empty)) + .ToArray()); + await LoadLatestRunAsync(selectedSessionId, CurrentLifetimeToken); } catch (OperationCanceledException) @@ -1110,6 +1187,37 @@ private async Task DeleteSelectedAsync() } } + private void SetNotDeletedItems(IReadOnlyList items) + { + NotDeletedItems.Clear(); + foreach (var item in items) + NotDeletedItems.Add(item); + + OnPropertyChanged(nameof(HasNotDeletedItems)); + OnPropertyChanged(nameof(NotDeletedTitle)); + } + + /// + /// The confirmed plan again, reduced to the files the Recycle Bin refused, as a + /// permanent deletion. Every other member is deselected, so the retry can only + /// reach files the user has just seen listed. + /// + private static DuplicateDeletionPlan BuildPermanentRetryPlan( + DuplicateDeletionPlan plan, + DuplicateDeletionOutcome outcome) + { + var groups = outcome.Skipped + .Select(static group => new DuplicateDeletionGroupPlan( + group.GroupPlan.Group, + DuplicateDeletionSkips.SelectOnlyRecycleBinRefusals(group.GroupPlan.Members, group.Skipped))) + .Where(static group => group.Members.Any(static member => member.IsSelected && !member.IsKeeper)) + .ToArray(); + + var selectedMemberCount = groups.Sum(static group => + group.Members.Count(static member => member.IsSelected && !member.IsKeeper)); + return new DuplicateDeletionPlan(plan.Page, DeletionMethod.Permanent, selectedMemberCount, groups); + } + /// /// Executes a frozen deletion plan group by group. Runs on the thread pool: it /// reads nothing from the view model and writes nothing to it, reporting progress @@ -1129,6 +1237,7 @@ private async Task ExecuteDeletionPlanAsync( var processedFileCount = 0; var groupErrors = new List(); var persistenceWarnings = new List(); + var skipped = new List(); var completedGroups = 0; foreach (var groupPlan in plan.Groups) @@ -1145,10 +1254,15 @@ private async Task ExecuteDeletionPlanAsync( processedFileCount += result.DeletedFileCount; persistenceWarnings.AddRange(result.Warnings.Select(warning => $"Group {groupPlan.Group.Id}, {warning.Path}: {warning.Message}")); + if (result.Skipped.Count > 0) + skipped.Add(new DuplicateDeletionGroupSkips(groupPlan, result.Skipped)); } catch (Exception ex) { groupErrors.Add($"Group {groupPlan.Group.Id}: {ex.Message}"); + skipped.Add(new DuplicateDeletionGroupSkips( + groupPlan, + DuplicateDeletionSkips.ForUnprocessedGroup(groupPlan.Members, ex.Message))); } completedGroups++; @@ -1162,7 +1276,8 @@ private async Task ExecuteDeletionPlanAsync( processedBytes, processedFileCount, groupErrors, - persistenceWarnings); + persistenceWarnings, + skipped); } private DuplicateDeletionPlan? CaptureDeletionPlan() diff --git a/src/StorageMaster.UI/Pages/ResultsViewModel.cs b/src/StorageMaster.UI/Pages/ResultsViewModel.cs index ca06772..930ad29 100644 --- a/src/StorageMaster.UI/Pages/ResultsViewModel.cs +++ b/src/StorageMaster.UI/Pages/ResultsViewModel.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Collections.ObjectModel; using System.Diagnostics; using CommunityToolkit.Mvvm.ComponentModel; @@ -554,6 +555,23 @@ private async Task DeleteFileAsync(FileEntry file) return; var outcome = await _resultDeletionService.DeleteAsync(file, DeletionMethod.RecycleBin); + if (!outcome.Success && outcome.RecycleBinRefused) + { + // Recycle Bin mode never deletes permanently on its own. The file is still + // in place; deleting it permanently instead is a separate decision, with + // "no" as the default. + var deletePermanently = await _dialogs.ConfirmItemsAsync( + Loc.Get("Safety_RecycleRefused_Title"), + Loc.Format("Safety_RecycleRefused_Body", 1.ToString("N0", CultureInfo.CurrentCulture)), + [file.FullPath], + Loc.Get("Safety_PermanentDelete"), + Loc.Get("Safety_RecycleRefused_Keep")); + if (!deletePermanently) + return; + + outcome = await _resultDeletionService.DeleteAsync(file, DeletionMethod.Permanent); + } + if (!outcome.Success) { // The reason comes from the deletion service and stays as it is — only the diff --git a/src/StorageMaster.UI/Pages/SmartCleanerViewModel.cs b/src/StorageMaster.UI/Pages/SmartCleanerViewModel.cs index 99f02fa..8af54e2 100644 --- a/src/StorageMaster.UI/Pages/SmartCleanerViewModel.cs +++ b/src/StorageMaster.UI/Pages/SmartCleanerViewModel.cs @@ -7,6 +7,7 @@ using StorageMaster.Core.Interfaces; using StorageMaster.Core.Localization; using StorageMaster.Core.Models; +using StorageMaster.Core.SmartCleaner; using StorageMaster.UI.Converters; using StorageMaster.UI.Infrastructure; @@ -242,7 +243,40 @@ void Apply() if (!IsCurrentOperation(operationVersion, operationCts)) return; - ApplyCleanupResult(result, method); + // Recycle Bin mode never deletes permanently on its own. Files Windows could + // not recycle are still in place; deleting them permanently instead is a + // separate decision, asked with the files listed and "no" as the default. + SmartCleanResult? permanentRetry = null; + var retryGroups = method == DeletionMethod.RecycleBin && !result.WasCancelled + ? SmartCleanerService.NarrowToRecycleBinRefusals(selected, result) + : []; + if (retryGroups.Count > 0) + { + var refusedPaths = retryGroups.SelectMany(static group => group.Paths).ToArray(); + var deletePermanently = await _dialogs.ConfirmItemsAsync( + Loc.Get("Safety_RecycleRefused_Title"), + Loc.Format( + "Safety_RecycleRefused_Body", + refusedPaths.Length.ToString("N0", CultureInfo.CurrentCulture)), + refusedPaths, + Loc.Get("Safety_PermanentDelete"), + Loc.Get("Safety_RecycleRefused_Keep")); + if (!IsCurrentOperation(operationVersion, operationCts)) + return; + + if (deletePermanently) + { + permanentRetry = await _service.CleanAsync( + retryGroups, + DeletionMethod.Permanent, + progress, + operationCts.Token); + if (!IsCurrentOperation(operationVersion, operationCts)) + return; + } + } + + ApplyCleanupResult(result, method, permanentRetry); } catch (OperationCanceledException) when (operationCts.IsCancellationRequested) { @@ -305,8 +339,45 @@ public void CancelOperations() UnsubscribeGroups(); } - private void ApplyCleanupResult(SmartCleanResult result, DeletionMethod method) + private void ApplyCleanupResult( + SmartCleanResult result, + DeletionMethod method, + SmartCleanResult? permanentRetry = null) { + var operationSummary = method == DeletionMethod.RecycleBin + ? Loc.Format("Safety_Smart_Summary_RecycleBin", ByteSizeConverter.Format(result.BytesProcessed)) + : Loc.Format( + "Safety_Smart_Summary_Permanent", + ByteSizeConverter.Format(result.BytesProcessed), + ByteSizeConverter.Format(result.BytesFreed)); + + if (permanentRetry is not null) + { + // Both summaries are self-contained sentences, so the user reads what went + // to the Recycle Bin and what was deleted permanently, separately. + operationSummary += " " + Loc.Format( + "Safety_Smart_Summary_Permanent", + ByteSizeConverter.Format(permanentRetry.BytesProcessed), + ByteSizeConverter.Format(permanentRetry.BytesFreed)); + + // A refusal the retry dealt with is replaced by what the retry did. + var retried = result.Failures + .Where(static failure => failure.RecycleBinRefused) + .Select(static failure => failure.Path) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + result = new SmartCleanResult( + result.BytesFreed + permanentRetry.BytesFreed, + result.BytesProcessed + permanentRetry.BytesProcessed, + result.SuccessfulPathCount + permanentRetry.SuccessfulPathCount, + result.Failures + .Where(failure => !retried.Contains(failure.Path)) + .Concat(permanentRetry.Failures) + .ToArray(), + result.AuditWarnings.Concat(permanentRetry.AuditWarnings).ToArray(), + result.WasCancelled || permanentRetry.WasCancelled, + result.ErrorMessage ?? permanentRetry.ErrorMessage); + } + InvalidateGroups(); FreedText = ByteSizeConverter.Format(result.BytesFreed); @@ -318,11 +389,6 @@ private void ApplyCleanupResult(SmartCleanResult result, DeletionMethod method) FailureDetails.Add(Loc.Format("Smart_FailureDetails_CleanupError", result.ErrorMessage)); HasFailureDetails = FailureDetails.Count > 0; - var processedText = ByteSizeConverter.Format(result.BytesProcessed); - var operationSummary = method == DeletionMethod.RecycleBin - ? Loc.Format("Safety_Smart_Summary_RecycleBin", processedText) - : Loc.Format("Safety_Smart_Summary_Permanent", processedText, FreedText); - if (result.SuccessfulPathCount == 0) { CompletionSeverity = result.WasCancelled ? InfoBarSeverity.Warning : InfoBarSeverity.Error; diff --git a/src/StorageMaster.UI/ServiceBootstrapper.cs b/src/StorageMaster.UI/ServiceBootstrapper.cs index 8f9f758..ea59595 100644 --- a/src/StorageMaster.UI/ServiceBootstrapper.cs +++ b/src/StorageMaster.UI/ServiceBootstrapper.cs @@ -155,8 +155,10 @@ public static IServiceProvider BuildServices() services.AddSingleton(sp => new NormalizedTextStrategy( sp.GetRequiredService())); + services.AddSingleton(); services.AddSingleton(sp => new ImagePHashStrategy( + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService())); services.AddSingleton(sp => diff --git a/tests/StorageMaster.Tests/Cleanup/CleanupEngineTests.cs b/tests/StorageMaster.Tests/Cleanup/CleanupEngineTests.cs index 1fec7b7..1e3fafc 100644 --- a/tests/StorageMaster.Tests/Cleanup/CleanupEngineTests.cs +++ b/tests/StorageMaster.Tests/Cleanup/CleanupEngineTests.cs @@ -494,6 +494,128 @@ await engine.ExecuteAsync([.. suggestions], dryRun: false, "last progress report should signal 100% complete"); } + // ── Recycle Bin refusals ────────────────────────────────────────────────── + + [Fact] + public async Task ExecuteAsync_RecycleBinRefusals_AreReportedApartFromOtherFailures() + { + _deleter + .Setup(d => d.DeleteManyAsync( + It.IsAny>(), + It.IsAny())) + .Returns, CancellationToken>((requests, _) => MakeRefusalOutcomes(requests)); + var suggestion = MakeSuggestion("rule.x", "Mixed", + [@"C:\Temp\ok.tmp", @"\\nas\share\refused.tmp", @"C:\Temp\locked.tmp"]); + var engine = BuildEngine([]); + + var results = await engine.ExecuteAsync([suggestion], dryRun: false, DeletionMethod.RecycleBin); + + results.Should().ContainSingle(); + results[0].FailedPaths.Should().BeEquivalentTo([@"\\nas\share\refused.tmp", @"C:\Temp\locked.tmp"]); + results[0].RecycleBinRefusedPaths.Should().Equal(@"\\nas\share\refused.tmp"); + } + + [Fact] + public void BuildPermanentRetryForRecycleBinRefusals_CarriesOverOnlyTheRefusedTargets() + { + var suggestion = MakeSuggestion("rule.x", "Mixed", + [@"C:\Temp\ok.tmp", @"\\nas\share\refused.tmp", @"C:\Temp\locked.tmp"]); + var result = RecycleResult(suggestion, refused: [@"\\nas\share\refused.tmp"]); + + var retry = CleanupEngine.BuildPermanentRetryForRecycleBinRefusals([suggestion], [result]); + + retry.Should().ContainSingle(); + retry[0].Id.Should().Be(suggestion.Id); + retry[0].TargetPaths.Should().Equal(@"\\nas\share\refused.tmp"); + } + + [Fact] + public void BuildPermanentRetryForRecycleBinRefusals_OffersNothingTheEngineWouldNotDeletePermanently() + { + var highRisk = MakeSuggestion("rule.high", "High risk", [@"\\nas\a.tmp"]) with { Risk = CleanupRisk.High }; + var recycleOnly = MakeSuggestion("rule.recycle", "Recycle only", [@"\\nas\b.tmp"]) with + { + SupportsPermanentDelete = false, + }; + var foreign = MakeSuggestion("rule.foreign", "Foreign", [@"\\nas\c.tmp"]); + + var retry = CleanupEngine.BuildPermanentRetryForRecycleBinRefusals( + [highRisk, recycleOnly, foreign], + [ + RecycleResult(highRisk, refused: [@"\\nas\a.tmp"]), + RecycleResult(recycleOnly, refused: [@"\\nas\b.tmp"]), + // A refused path that is not one of the suggestion's own targets is ignored. + RecycleResult(foreign, refused: [@"\\nas\elsewhere.tmp"]), + // And a dry run refuses nothing. + RecycleResult(foreign, refused: [@"\\nas\c.tmp"]) with { WasDryRun = true }, + ]); + + retry.Should().BeEmpty(); + } + + [Fact] + public async Task ExecuteAsync_PermanentRetryOfRefusals_SendsOnlyThoseTargetsWithTheirSnapshots() + { + var snapshot = new FileSnapshot( + @"\\nas\share\refused.tmp", + new FileIdentity("ABCD1234", 7), + 2048, + new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc), + FileAttributes.Archive); + var suggestion = MakeSuggestion("rule.x", "Mixed", [@"C:\Temp\ok.tmp", snapshot.Path]) with + { + ExpectedFileSnapshots = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [snapshot.Path] = snapshot, + }, + }; + var retry = CleanupEngine.BuildPermanentRetryForRecycleBinRefusals( + [suggestion], + [RecycleResult(suggestion, refused: [snapshot.Path])]); + SetupDeleterSuccess(); + var engine = BuildEngine([]); + + await engine.ExecuteAsync(retry, dryRun: false, DeletionMethod.Permanent); + + retry.Single().EstimatedBytes.Should().Be(2048); + _deleter.Verify(d => d.DeleteManyAsync( + It.Is>(requests => + requests.Count == 1 && + requests[0].Path == snapshot.Path && + requests[0].Method == DeletionMethod.Permanent && + requests[0].ExpectedSnapshot == snapshot), + It.IsAny()), Times.Once); + } + + private static CleanupResult RecycleResult(CleanupSuggestion suggestion, IReadOnlyList refused) => new() + { + SuggestionId = suggestion.Id, + Status = CleanupResultStatus.PartialSuccess, + BytesFreed = 0, + ExecutedUtc = DateTime.UtcNow, + WasDryRun = false, + FailedPaths = refused, + RecycleBinRefusedPaths = refused, + }; + + private static async IAsyncEnumerable MakeRefusalOutcomes( + IReadOnlyList requests) + { + foreach (var request in requests) + { + yield return request.Path switch + { + var path when path.StartsWith(@"\\", StringComparison.Ordinal) => + new DeletionOutcome(path, Success: false, BytesFreed: 0, Error: "No Recycle Bin", RecycleBinRefused: true), + var path when path.EndsWith("locked.tmp", StringComparison.Ordinal) => + new DeletionOutcome(path, Success: false, BytesFreed: 0, Error: "Locked"), + var path => new DeletionOutcome(path, Success: true, BytesFreed: 1024L), + }; + } + + await Task.CompletedTask; + } + // ── Helpers ──────────────────────────────────────────────────────────────── private CleanupEngine BuildEngine(IEnumerable rules) => diff --git a/tests/StorageMaster.Tests/Cleanup/SmartCleanerServiceTests.cs b/tests/StorageMaster.Tests/Cleanup/SmartCleanerServiceTests.cs index db66cce..2fe16db 100644 --- a/tests/StorageMaster.Tests/Cleanup/SmartCleanerServiceTests.cs +++ b/tests/StorageMaster.Tests/Cleanup/SmartCleanerServiceTests.cs @@ -297,6 +297,61 @@ public async Task CleanAsync_ThumbnailSource_AcceptsOnlyThumbcacheFilesDirectlyI .Should().BeEquivalentTo(new[] { otherFile.Path, nested.Path }); } + [Fact] + public async Task CleanAsync_RecycleBinRefusal_IsFlaggedApartFromOtherFailures() + { + var recycled = SnapshotFor(LocalTempPath($"smclean_refusal_{Guid.NewGuid():N}_1.tmp"), 50, 5); + var refused = SnapshotFor(LocalTempPath($"smclean_refusal_{Guid.NewGuid():N}_2.tmp"), 51, 6); + var locked = SnapshotFor(LocalTempPath($"smclean_refusal_{Guid.NewGuid():N}_3.tmp"), 52, 7); + var enumerator = CreateValidationEnumerator(expected => new TrackingLease(expected)); + var deleter = new Mock(); + deleter.Setup(service => service.DeleteAsync( + It.IsAny(), + It.IsAny())) + .Returns((request, _) => Task.FromResult( + PathsEqual(request.Path, refused.Path) + ? new DeletionOutcome(request.Path, false, 0, "no Recycle Bin", RecycleBinRefused: true) + : PathsEqual(request.Path, locked.Path) + ? new DeletionOutcome(request.Path, false, 0, "locked") + : new DeletionOutcome(request.Path, true, 0))); + var service = CreateService(deleter.Object, enumerator.Object, CreateLog().Object); + + var result = await service.CleanAsync([GroupFor(recycled, refused, locked)], DeletionMethod.RecycleBin); + + result.Failures.Should().HaveCount(2); + result.Failures.Single(failure => failure.Path == refused.Path).RecycleBinRefused.Should().BeTrue(); + result.Failures.Single(failure => failure.Path == locked.Path).RecycleBinRefused.Should().BeFalse(); + } + + [Fact] + public void NarrowToRecycleBinRefusals_KeepsOnlyRefusedPathsAndTheirSnapshots() + { + var recycled = SnapshotFor(LocalTempPath($"smclean_narrow_{Guid.NewGuid():N}_1.tmp"), 60, 5); + var refused = SnapshotFor(LocalTempPath($"smclean_narrow_{Guid.NewGuid():N}_2.tmp"), 61, 6); + var locked = SnapshotFor(LocalTempPath($"smclean_narrow_{Guid.NewGuid():N}_3.tmp"), 62, 7); + var untouchedGroup = GroupFor(SmartCleanSource.ThumbnailCache, SnapshotFor(LocalTempPath("thumbcache_x.db"), 63, 8)); + var result = new SmartCleanResult( + BytesFreed: 0, + BytesProcessed: 5, + SuccessfulPathCount: 1, + Failures: + [ + new SmartCleanFailure(refused.Path, "no Recycle Bin", RecycleBinRefused: true), + new SmartCleanFailure(locked.Path, "locked"), + ], + AuditWarnings: []); + + var narrowed = SmartCleanerService.NarrowToRecycleBinRefusals( + [GroupFor(recycled, refused, locked), untouchedGroup], + result); + + narrowed.Should().ContainSingle(); + narrowed[0].Paths.Should().Equal(refused.Path); + narrowed[0].EstimatedBytes.Should().Be(6); + narrowed[0].ExpectedFileSnapshots[refused.Path].Should().Be(refused, + "the retry revalidates the file against its analysis-time snapshot"); + } + private static SmartCleanerService CreateService( IFileDeleter deleter, INoFollowFileEnumerator enumerator, diff --git a/tests/StorageMaster.Tests/CriticalFixes/RecycleBinGuardTests.cs b/tests/StorageMaster.Tests/CriticalFixes/RecycleBinGuardTests.cs index 3464f98..9a40f54 100644 --- a/tests/StorageMaster.Tests/CriticalFixes/RecycleBinGuardTests.cs +++ b/tests/StorageMaster.Tests/CriticalFixes/RecycleBinGuardTests.cs @@ -42,6 +42,8 @@ public async Task DeleteAsync_RecycleBinWhereThereIsNoRecycleBin_RefusesAndKeeps outcome.Success.Should().BeFalse("the shell could only have deleted it permanently"); outcome.BytesFreed.Should().Be(0); outcome.Error.Should().Be(FileDeleter.RecycleBinUnavailableError); + outcome.RecycleBinRefused.Should().BeTrue( + "callers offer a permanent delete only for items the Recycle Bin refused"); File.Exists(local).Should().BeTrue("Recycle Bin mode must not destroy the file"); } @@ -66,6 +68,7 @@ public async Task DeleteManyAsync_RecycleBatchWhereThereIsNoRecycleBin_RefusesEv // its own and refused there too. outcomes.Should().HaveCount(2); outcomes.Should().OnlyContain(o => !o.Success && o.Error == FileDeleter.RecycleBinUnavailableError); + outcomes.Should().OnlyContain(o => o.RecycleBinRefused); outcomes.Select(o => o.Path).Should().BeEquivalentTo([firstNetwork, secondNetwork]); File.Exists(first).Should().BeTrue(); File.Exists(second).Should().BeTrue(); @@ -99,8 +102,9 @@ public async Task DeleteManyAsync_MixedBatchWithItemWithoutRecycleBin_RecyclesLo outcomes.Should().HaveCount(3); outcomes.Should().ContainSingle(o => o.Path == recyclable).Which.Success.Should().BeTrue( "the local file can be recycled on its own once the batch has been refused"); + outcomes.Single(o => o.Path == recyclable).RecycleBinRefused.Should().BeFalse(); outcomes.Where(o => o.Path != recyclable).Should().OnlyContain( - o => !o.Success && o.Error == FileDeleter.RecycleBinUnavailableError); + o => !o.Success && o.Error == FileDeleter.RecycleBinUnavailableError && o.RecycleBinRefused); File.Exists(recyclable).Should().BeFalse(); File.Exists(first).Should().BeTrue(); File.Exists(second).Should().BeTrue(); @@ -163,6 +167,8 @@ public async Task DeleteManyAsync_GuardedBatchWithLockedFile_ReportsRecycledItem outcomes.Should().ContainSingle(o => o.Path == recyclable).Which.Success.Should().BeTrue( "the file is in the Recycle Bin, so reporting it as changed or failed is wrong"); outcomes.Should().ContainSingle(o => o.Path == locked).Which.Success.Should().BeFalse(); + outcomes.Single(o => o.Path == locked).RecycleBinRefused.Should().BeFalse( + "a locked file is not a Recycle Bin refusal; deleting it permanently would fail the same way"); File.Exists(recyclable).Should().BeFalse(); File.Exists(locked).Should().BeTrue(); } @@ -184,6 +190,7 @@ public async Task DeleteAsync_RecycleBinLockedFile_ReportsFailureInsteadOfSucces outcome.Success.Should().BeFalse(); outcome.BytesFreed.Should().Be(0); + outcome.RecycleBinRefused.Should().BeFalse(); File.Exists(local).Should().BeTrue(); } diff --git a/tests/StorageMaster.Tests/CriticalFixes/TurboScannerCriticalTests.cs b/tests/StorageMaster.Tests/CriticalFixes/TurboScannerCriticalTests.cs index 1c32d4d..29ef027 100644 --- a/tests/StorageMaster.Tests/CriticalFixes/TurboScannerCriticalTests.cs +++ b/tests/StorageMaster.Tests/CriticalFixes/TurboScannerCriticalTests.cs @@ -434,6 +434,111 @@ private static bool CreateJunction(string junction, string target) return process.ExitCode == 0 && Directory.Exists(junction); } + [Fact] + public async Task NativeScan_CountsAHardLinkedFileOnce() + { + var root = CreateTempDir(files: 0); + var child = Path.Combine(root, "child"); + Directory.CreateDirectory(child); + + // Two names for one file (same volume and file index), plus one other file. + var records = new[] + { + JsonRecord(root, size: 0, isDirectory: true), + JsonFileRecord(Path.Combine(root, "original.bin"), size: 100, volumeSerial: 0xA1B2_C3D4u, fileIndex: 7), + JsonRecord(child, size: 0, isDirectory: true), + JsonFileRecord(Path.Combine(child, "link.bin"), size: 100, volumeSerial: 0xA1B2_C3D4u, fileIndex: 7), + JsonFileRecord(Path.Combine(child, "other.bin"), size: 5, volumeSerial: 0xA1B2_C3D4u, fileIndex: 8), + }; + + var persistedFiles = new List(); + var persistedFolders = new Dictionary(StringComparer.OrdinalIgnoreCase); + IReadOnlyDictionary? folderTotals = null; + var terminalSessions = new List(); + ConfigurePersistenceCapture(persistedFiles, persistedFolders, terminalSessions, + totals => folderTotals = totals); + var turbo = CreateInjectedTurboScanner( + _ => CreatePowerShellStartInfo(BuildRecordScript(records))); + + try + { + var result = await turbo.ScanAsync( + new ScanOptions { RootPath = root, MaxParallelism = 1 }, + new Progress()); + + result.Status.Should().Be(ScanStatus.Completed); + result.TotalFiles.Should().Be(3, "every name is still listed"); + result.TotalSizeBytes.Should().Be(105, "the linked data exists on disk once"); + persistedFiles.Single(file => file.FileName == "link.bin").Should().Match( + file => file.IsAdditionalHardLink && file.SizeBytes == 100); + persistedFiles.Single(file => file.FileName == "original.bin").IsAdditionalHardLink.Should().BeFalse(); + persistedFolders[root].DirectSizeBytes.Should().Be(100); + persistedFolders[child].DirectSizeBytes.Should().Be(5); + folderTotals![root].Should().Be(105); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public async Task NativeScan_CountsEveryFileWhoseIdIsAPlaceholder() + { + var root = CreateTempDir(files: 0); + + // A file system without unique 64-bit ids (ReFS for large ids, some network + // and user-mode file systems) reports the same placeholder for unrelated files. + var records = new[] + { + JsonRecord(root, size: 0, isDirectory: true), + JsonFileRecord(Path.Combine(root, "a.bin"), size: 100, volumeSerial: 0xA1B2_C3D4u, fileIndex: 0), + JsonFileRecord(Path.Combine(root, "b.bin"), size: 20, volumeSerial: 0xA1B2_C3D4u, fileIndex: 0), + JsonFileRecord(Path.Combine(root, "c.bin"), size: 3, volumeSerial: 0xA1B2_C3D4u, fileIndex: ulong.MaxValue), + JsonFileRecord(Path.Combine(root, "d.bin"), size: 4, volumeSerial: 0xA1B2_C3D4u, fileIndex: ulong.MaxValue), + }; + + var persistedFiles = new List(); + var persistedFolders = new Dictionary(StringComparer.OrdinalIgnoreCase); + IReadOnlyDictionary? folderTotals = null; + var terminalSessions = new List(); + ConfigurePersistenceCapture(persistedFiles, persistedFolders, terminalSessions, + totals => folderTotals = totals); + var turbo = CreateInjectedTurboScanner( + _ => CreatePowerShellStartInfo(BuildRecordScript(records))); + + try + { + var result = await turbo.ScanAsync( + new ScanOptions { RootPath = root, MaxParallelism = 1 }, + new Progress()); + + result.Status.Should().Be(ScanStatus.Completed); + result.TotalFiles.Should().Be(4); + result.TotalSizeBytes.Should().Be(127, "a placeholder id proves nothing about hard links"); + persistedFiles.Should().OnlyContain(static file => !file.IsAdditionalHardLink); + persistedFolders[root].DirectSizeBytes.Should().Be(127); + folderTotals![root].Should().Be(127); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + private static string JsonFileRecord(string path, long size, uint volumeSerial, ulong fileIndex) => + JsonSerializer.Serialize(new + { + path, + size, + modified_unix = 1, + created_unix = 1, + volume_serial = volumeSerial, + file_index = fileIndex, + is_dir = false, + is_hidden = false, + }); + private TurboFileScanner CreateInjectedTurboScanner( Func processStartInfoFactory) => new( diff --git a/tests/StorageMaster.Tests/Deduplication/DuplicateDeletionServiceTests.cs b/tests/StorageMaster.Tests/Deduplication/DuplicateDeletionServiceTests.cs index 3d57ba8..4137eca 100644 --- a/tests/StorageMaster.Tests/Deduplication/DuplicateDeletionServiceTests.cs +++ b/tests/StorageMaster.Tests/Deduplication/DuplicateDeletionServiceTests.cs @@ -3,6 +3,7 @@ using StorageMaster.Core.Cleanup; using StorageMaster.Core.Deduplication; using StorageMaster.Core.Interfaces; +using StorageMaster.Core.Localization; using StorageMaster.Core.Models; using StorageMaster.Platform.Windows; @@ -475,6 +476,208 @@ public async Task DeleteSelectedAsync_SelectedMemberAttributesChanged_SkipsDelet repo.VerifyNoOtherCalls(); } + // ── Why a selected file was not deleted ───────────────────────────────── + + [Fact] + public async Task DeleteSelectedWithResultAsync_ReportsAReasonForEverySelectedFileLeftInPlace() + { + var keeperPath = WriteFile("reason-keeper.txt", "same"); + var changedPath = WriteFile("reason-changed.txt", "same"); + var differentPath = WriteFile("reason-different.txt", "diff"); + var lockedPath = WriteFile("reason-locked.txt", "same"); + var refusedPath = WriteFile("reason-refused.txt", "same"); + var deletedPath = WriteFile("reason-deleted.txt", "same"); + + var keeper = MakeMember(1, 10, keeperPath, isKeeper: true, isSelected: false); + var changed = MakeMember(2, 10, changedPath, isKeeper: false, isSelected: true); + var different = MakeMember(3, 10, differentPath, isKeeper: false, isSelected: true); + var locked = MakeMember(4, 10, lockedPath, isKeeper: false, isSelected: true); + var refused = MakeMember(5, 10, refusedPath, isKeeper: false, isSelected: true); + var deleted = MakeMember(6, 10, deletedPath, isKeeper: false, isSelected: true); + var noIdentityPath = WriteFile("reason-noidentity.txt", "same"); + var noIdentity = MakeMember(7, 10, noIdentityPath, isKeeper: false, isSelected: true) with { Identity = null }; + await File.AppendAllTextAsync(changedPath, " changed"); + + var deleter = new Mock(); + deleter.Setup(x => x.DeleteAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync((DeletionRequest request, CancellationToken _) => + request.Path == lockedPath + ? new DeletionOutcome(request.Path, false, 0, "The process cannot access the file.") + : request.Path == refusedPath + ? new DeletionOutcome(request.Path, false, 0, "Not deleted: no Recycle Bin.", RecycleBinRefused: true) + : new DeletionOutcome(request.Path, true, 4)); + var service = CreateService(deleter.Object, Mock.Of(), CreatePermissiveRepository().Object); + + var result = await service.DeleteSelectedWithResultAsync( + MakeGroup(), + [keeper, changed, different, locked, refused, deleted, noIdentity], + DeletionMethod.RecycleBin); + + result.DeletedFileCount.Should().Be(1); + result.Skipped.Should().BeEquivalentTo(new[] + { + new DuplicateDeletionSkip(changed.Id, changedPath, DuplicateDeletionSkipReason.ChangedSinceAnalysis), + new DuplicateDeletionSkip(different.Id, differentPath, DuplicateDeletionSkipReason.NoLongerDuplicate), + new DuplicateDeletionSkip(locked.Id, lockedPath, DuplicateDeletionSkipReason.DeleteFailed, "The process cannot access the file."), + new DuplicateDeletionSkip(refused.Id, refusedPath, DuplicateDeletionSkipReason.RecycleBinUnavailable, "Not deleted: no Recycle Bin."), + new DuplicateDeletionSkip(noIdentity.Id, noIdentity.FullPath, DuplicateDeletionSkipReason.NoStableIdentity), + }); + result.Warnings.Should().BeEmpty( + "a file left in place is not a bookkeeping warning; it is reported with its reason"); + } + + [Fact] + public async Task DeleteSelectedWithResultAsync_MemberThatCannotBeReread_IsReportedAsNotVerified() + { + var keeperPath = WriteFile("verify-keeper.txt", "same"); + var memberPath = WriteFile("verify-member.txt", "same"); + var keeper = MakeMember(1, 10, keeperPath, isKeeper: true, isSelected: false); + var member = MakeMember(2, 10, memberPath, isKeeper: false, isSelected: true); + + var strategy = new Mock(); + strategy.SetupGet(x => x.Method).Returns(DuplicateMethod.ExactSha256); + strategy.SetupGet(x => x.Algorithm).Returns("SHA-256"); + strategy.SetupGet(x => x.IsAvailable).Returns(true); + strategy.Setup(x => x.ComputeSignatureAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync((DuplicateCandidate candidate, CancellationToken _) => candidate.File.FullPath == keeperPath + ? Signature(candidate, "Ready", text: "AA") + : Signature(candidate, "Error", error: "sharing violation")); + + var service = new DuplicateDeletionService( + new Mock(MockBehavior.Strict).Object, + Mock.Of(), + new Mock(MockBehavior.Strict).Object, + new FileSnapshotProvider(), + [strategy.Object]); + + var result = await service.DeleteSelectedWithResultAsync(MakeGroup(), [keeper, member], DeletionMethod.Permanent); + + result.Skipped.Should().ContainSingle().Which.Should().Be( + new DuplicateDeletionSkip(member.Id, memberPath, DuplicateDeletionSkipReason.CouldNotVerify, "sharing violation")); + File.Exists(memberPath).Should().BeTrue(); + + static DuplicateSignature Signature(DuplicateCandidate candidate, string status, string? text = null, string? error = null) => + new() + { + Id = 0, + SessionId = 0, + FileEntryId = candidate.File.Id, + Method = DuplicateMethod.ExactSha256, + Algorithm = "SHA-256", + AlgorithmVersion = 1, + ComputedUtc = DateTime.UtcNow, + Status = status, + SignatureText = text, + ErrorMessage = error, + }; + } + + [Fact] + public void EveryNotDeletedReasonHasAStringInEveryLanguage() + { + foreach (var language in LocalizationCatalog.ShippedLanguages) + { + var strings = LocalizationCatalog.Strings(language); + foreach (var reason in Enum.GetValues()) + { + strings.Should().ContainKey(DuplicateDeletionSkips.ResourceKey(reason), + "the Duplicates page explains every file it did not delete, in {0} too", language); + } + } + } + + [Fact] + public void ForUnprocessedGroup_ListsOnlyTheSelectedNonKeepers() + { + var keeper = MakeMember(1, 10, WriteFile("group-keeper.txt", "x"), isKeeper: true, isSelected: true); + var selected = MakeMember(2, 10, WriteFile("group-selected.txt", "x"), isKeeper: false, isSelected: true); + var unselected = MakeMember(3, 10, WriteFile("group-unselected.txt", "x"), isKeeper: false, isSelected: false); + + var skips = DuplicateDeletionSkips.ForUnprocessedGroup([keeper, selected, unselected], "keeper changed"); + + skips.Should().ContainSingle().Which.Should().Be(new DuplicateDeletionSkip( + selected.Id, selected.FullPath, DuplicateDeletionSkipReason.KeeperNotVerified, "keeper changed")); + } + + [Fact] + public void SelectOnlyRecycleBinRefusals_SelectsNothingTheUserWasNotAskedAbout() + { + var keeper = MakeMember(1, 10, WriteFile("retry-keeper.txt", "x"), isKeeper: true, isSelected: false); + var refused = MakeMember(2, 10, WriteFile("retry-refused.txt", "x"), isKeeper: false, isSelected: true); + var locked = MakeMember(3, 10, WriteFile("retry-locked.txt", "x"), isKeeper: false, isSelected: true); + var recycled = MakeMember(4, 10, WriteFile("retry-recycled.txt", "x"), isKeeper: false, isSelected: true); + var unselected = MakeMember(5, 10, WriteFile("retry-unselected.txt", "x"), isKeeper: false, isSelected: false); + + var members = DuplicateDeletionSkips.SelectOnlyRecycleBinRefusals( + [keeper, refused, locked, recycled, unselected], + [ + new DuplicateDeletionSkip(refused.Id, refused.FullPath, DuplicateDeletionSkipReason.RecycleBinUnavailable), + new DuplicateDeletionSkip(locked.Id, locked.FullPath, DuplicateDeletionSkipReason.DeleteFailed), + // A refusal for a member the user had not selected must not select it. + new DuplicateDeletionSkip(unselected.Id, unselected.FullPath, DuplicateDeletionSkipReason.RecycleBinUnavailable), + ]); + + members.Should().HaveCount(5, "the keeper stays in the plan so the retry can verify against it"); + members.Where(static member => member.IsSelected).Select(static member => member.Id) + .Should().Equal(refused.Id); + members.Single(member => member.Id == keeper.Id).IsKeeper.Should().BeTrue(); + } + + [Fact] + public async Task PermanentRetryOfARefusal_DeletesOnlyTheRefusedFileAndRechecksIt() + { + var keeperPath = WriteFile("again-keeper.txt", "same"); + var refusedPath = WriteFile("again-refused.txt", "same"); + var otherPath = WriteFile("again-other.txt", "same"); + var keeper = MakeMember(1, 10, keeperPath, isKeeper: true, isSelected: false); + var refused = MakeMember(2, 10, refusedPath, isKeeper: false, isSelected: true); + var other = MakeMember(3, 10, otherPath, isKeeper: false, isSelected: true); + + var requests = new List(); + var deleter = new Mock(); + deleter.Setup(x => x.DeleteAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync((DeletionRequest request, CancellationToken _) => + { + requests.Add(request); + return request.Method == DeletionMethod.RecycleBin && request.Path == refusedPath + ? new DeletionOutcome(request.Path, false, 0, "no bin", RecycleBinRefused: true) + : new DeletionOutcome(request.Path, true, 4); + }); + var service = CreateService(deleter.Object, Mock.Of(), CreatePermissiveRepository().Object); + + var first = await service.DeleteSelectedWithResultAsync(MakeGroup(), [keeper, refused, other], DeletionMethod.RecycleBin); + var retry = await service.DeleteSelectedWithResultAsync( + MakeGroup(), + DuplicateDeletionSkips.SelectOnlyRecycleBinRefusals([keeper, refused, other], first.Skipped), + DeletionMethod.Permanent); + + first.Skipped.Should().ContainSingle().Which.Reason.Should().Be(DuplicateDeletionSkipReason.RecycleBinUnavailable); + retry.DeletedFileCount.Should().Be(1); + retry.Skipped.Should().BeEmpty(); + var permanent = requests.Where(static request => request.Method == DeletionMethod.Permanent).ToArray(); + permanent.Should().ContainSingle(); + permanent[0].Path.Should().Be(refusedPath); + permanent[0].ExpectedSnapshot.Should().NotBeNull("the retry re-validates the file like any deletion"); + } + + private static Mock CreatePermissiveRepository() + { + var repo = new Mock(); + repo.Setup(x => x.MarkMembersDeletedAsync(It.IsAny>(), It.IsAny())) + .Returns(Task.CompletedTask); + repo.Setup(x => x.RecordDuplicateOperationIntentAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync((DuplicateOperationJournalEntry entry, CancellationToken _) => entry with { Id = 1 }); + repo.Setup(x => x.UpdateDuplicateOperationOutcomeAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Returns(Task.CompletedTask); + return repo; + } + public void Dispose() { if (Directory.Exists(_tempDir)) diff --git a/tests/StorageMaster.Tests/Deduplication/DuplicateStrategyCancellationTests.cs b/tests/StorageMaster.Tests/Deduplication/DuplicateStrategyCancellationTests.cs index 8fdb620..a0d14df 100644 --- a/tests/StorageMaster.Tests/Deduplication/DuplicateStrategyCancellationTests.cs +++ b/tests/StorageMaster.Tests/Deduplication/DuplicateStrategyCancellationTests.cs @@ -3,6 +3,7 @@ using StorageMaster.Core.Deduplication; using StorageMaster.Core.Interfaces; using StorageMaster.Core.Models; +using StorageMaster.Platform.Windows; namespace StorageMaster.Tests.Deduplication; @@ -59,7 +60,7 @@ public async Task ImagePHash_Cancellation_IsNotConvertedToPHashError() { using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - var strategy = new ImagePHashStrategy(); + var strategy = new ImagePHashStrategy(new WicImageHashDecoder()); var candidate = MakeCandidate(@"C:\data\sample.png", ".png"); Func act = () => strategy.ComputeSignatureAsync(candidate, cancellation.Token); diff --git a/tests/StorageMaster.Tests/Deduplication/ImagePHashStrategyTests.cs b/tests/StorageMaster.Tests/Deduplication/ImagePHashStrategyTests.cs new file mode 100644 index 0000000..7a88934 --- /dev/null +++ b/tests/StorageMaster.Tests/Deduplication/ImagePHashStrategyTests.cs @@ -0,0 +1,282 @@ +using System.Numerics; +using System.Text.Json; +using FluentAssertions; +using StorageMaster.Core.Deduplication; +using StorageMaster.Core.Models; +using StorageMaster.Platform.Windows; +using Windows.Graphics.Imaging; + +namespace StorageMaster.Tests.Deduplication; + +/// +/// The image perceptual hash on the Windows Imaging Component. +/// +/// The fixtures are drawn and encoded here, through the same WIC encoders, so the +/// tests need no binary files and no network. Every file lives in a temp folder +/// created for the test and removed afterwards. +/// +/// +public sealed class ImagePHashStrategyTests : IDisposable +{ + private const int Width = 160; + private const int Height = 96; + + private readonly string _directory = Path.Combine(Path.GetTempPath(), $"sm_phash_{Guid.NewGuid():N}"); + private readonly ImagePHashStrategy _strategy = new(new WicImageHashDecoder()); + + public ImagePHashStrategyTests() => Directory.CreateDirectory(_directory); + + [Fact] + public async Task SamePictureAsPngJpegAndBmp_HashesAlike_AndItsNegativeDoesNot() + { + var png = await WriteAsync("picture.png", BitmapEncoder.PngEncoderId, Width, Height, Upright); + var jpeg = await WriteAsync("picture.jpg", BitmapEncoder.JpegEncoderId, Width, Height, Upright); + var bmp = await WriteAsync("picture.bmp", BitmapEncoder.BmpEncoderId, Width, Height, Upright); + var negative = await WriteAsync("negative.png", BitmapEncoder.PngEncoderId, Width, Height, + (x, y) => (byte)(255 - Upright(x, y))); + + var pngHash = await HashAsync(png); + var jpegHash = await HashAsync(jpeg); + var bmpHash = await HashAsync(bmp); + var negativeHash = await HashAsync(negative); + + Distance(pngHash, bmpHash).Should().Be(0, "PNG and BMP carry the same pixels losslessly"); + Distance(pngHash, jpegHash).Should().BeLessThanOrEqualTo(4, "JPEG compression barely moves low frequencies"); + Distance(pngHash, negativeHash).Should().BeGreaterThan(ImagePHashStrategy.DefaultHammingThreshold); + } + + [Fact] + public async Task ExifOrientation_IsAppliedBeforeHashing() + { + // Stored rotated 90° counter-clockwise and tagged "rotate 90° clockwise to + // display" (orientation 6), which is how a camera held upright on its side + // writes a photo. Displayed, it is the upright picture. + var upright = await WriteAsync("upright.jpg", BitmapEncoder.JpegEncoderId, Width, Height, Upright); + var tagged = await WriteAsync("tagged.jpg", BitmapEncoder.JpegEncoderId, Height, Width, StoredSideways, orientation: 6); + var untagged = await WriteAsync("untagged.jpg", BitmapEncoder.JpegEncoderId, Height, Width, StoredSideways); + + var uprightSignature = await SignAsync(upright); + var taggedSignature = await SignAsync(tagged); + var untaggedHash = await HashAsync(untagged); + + Distance(Parse(uprightSignature), Parse(taggedSignature)).Should().BeLessThanOrEqualTo(4, + "the same photo stored in another orientation must hash the same"); + Distance(Parse(uprightSignature), untaggedHash).Should().BeGreaterThan(ImagePHashStrategy.DefaultHammingThreshold, + "without the tag the stored pixels really are a different picture, so the test would prove nothing otherwise"); + + using var metadata = JsonDocument.Parse(taggedSignature.MetadataJson!); + metadata.RootElement.GetProperty("width").GetInt32().Should().Be(Width, "dimensions are reported as displayed"); + metadata.RootElement.GetProperty("height").GetInt32().Should().Be(Height); + metadata.RootElement.GetProperty("orientation").GetInt32().Should().Be(6); + } + + [Fact] + public async Task UndecodableFile_BecomesAPerFileHashError() + { + var path = Path.Combine(_directory, "broken.png"); + await File.WriteAllBytesAsync(path, [0x89, 0x50, 0x4E, 0x47, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05]); + + var signature = await _strategy.ComputeSignatureAsync(Candidate(path)); + + signature.Status.Should().Be("Error"); + signature.ErrorMessage.Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task DamagedFiles_NeverThrow_AndAreClosedAfterwards() + { + var jpeg = await File.ReadAllBytesAsync( + await WriteAsync("source.jpg", BitmapEncoder.JpegEncoderId, Width, Height, Upright)); + var damaged = new (string Name, byte[] Bytes, bool MustFail)[] + { + ("empty.jpg", [], true), + ("one-byte.jpg", [0xFF], true), + ("header-only.jpg", jpeg[..Math.Min(200, jpeg.Length)], true), + ("text.png", "not an image at all"u8.ToArray(), true), + ("noise.webp", Enumerable.Range(0, 4096).Select(static i => (byte)(i * 7919 % 251)).ToArray(), true), + // A cut-off JPEG may still decode, with the missing rows filled in; either + // outcome is fine as long as it is a per-file result and not an exception. + ("truncated.jpg", jpeg[..(jpeg.Length / 2)], false), + }; + + foreach (var (name, bytes, mustFail) in damaged) + { + var path = Path.Combine(_directory, name); + await File.WriteAllBytesAsync(path, bytes); + + var signature = await _strategy.ComputeSignatureAsync(Candidate(path)); + + signature.Status.Should().BeOneOf(["Ready", "Error"], name); + if (mustFail) + signature.Status.Should().Be("Error", name); + + // The decoder must not keep the file open: a later delete, move or + // re-hash of the same file would otherwise fail. + using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + { + } + } + } + + [Fact] + public async Task Identify_ReadsDisplayedDimensionsWithoutDecodingPixels() + { + var tagged = await WriteAsync("identify.jpg", BitmapEncoder.JpegEncoderId, Height, Width, StoredSideways, orientation: 6); + + await using var stream = File.OpenRead(tagged); + var header = await new WicImageHashDecoder().IdentifyAsync(stream); + + header.Should().Be(new Core.Interfaces.ImageHeader(Width, Height, 6)); + } + + [Theory] + [InlineData(255, 255, 255, 255)] + [InlineData(0, 0, 0, 0)] + [InlineData(0, 255, 0, 182)] // Rec. 709: green carries most of the luma + [InlineData(255, 0, 0, 54)] + [InlineData(0, 0, 255, 18)] + public void Luminance_UsesRec709Weights(byte red, byte green, byte blue, byte expected) + => WicImageHashDecoder.ToLuminance([blue, green, red, 255]).Should().Equal(expected); + + [Fact] + public void CoreCarriesNoImageCodecOfItsOwn() + { + typeof(ImagePHashStrategy).Assembly.GetReferencedAssemblies() + .Select(static reference => reference.Name) + .Should().NotContain(name => name != null && name.StartsWith("SixLabors", StringComparison.OrdinalIgnoreCase), + "image decoding goes through the platform decoder, which Windows Update keeps patched"); + } + + [Fact] + public async Task VideoFrame_RawLuminanceHashesLikeTheSameImage() + { + var png = await WriteAsync("frame-source.png", BitmapEncoder.PngEncoderId, 32, 32, Upright); + await using var stream = File.OpenRead(png); + var surface = await new WicImageHashDecoder().DecodeAsync(stream, ImagePHashStrategy.DctSize); + var raw = Path.Combine(_directory, "frame_00.gray"); + await File.WriteAllBytesAsync(raw, surface.Luminance); + + VideoPHashStrategy.ComputeFrameHash(raw) + .Should().Be(ImagePHashStrategy.ComputeHashFromLuminance(surface.Luminance)); + } + + [Fact] + public async Task VideoFrame_ThatFfmpegDidNotWriteInFull_IsRejected() + { + var raw = Path.Combine(_directory, "frame_short.gray"); + await File.WriteAllBytesAsync(raw, new byte[ImagePHashStrategy.DctSize * ImagePHashStrategy.DctSize - 1]); + + var act = () => VideoPHashStrategy.ComputeFrameHash(raw); + + act.Should().Throw(); + } + + public void Dispose() + { + try + { + Directory.Delete(_directory, recursive: true); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } + + /// A bright block in the top-left quarter over a left-to-right ramp: no rotational symmetry. + private static byte Upright(int x, int y) => + x < Width / 2 && y < Height / 2 + ? (byte)230 + : (byte)(30 + (x * 120 / Width) + (y * 40 / Height)); + + /// rotated 90° counter-clockwise: stored Height wide and Width tall. + private static byte StoredSideways(int x, int y) => Upright(Width - 1 - y, x); + + private async Task WriteAsync( + string name, + Guid encoderId, + int width, + int height, + Func luminance, + ushort? orientation = null) + { + var bgra = new byte[width * height * 4]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var value = luminance(x, y); + var offset = ((y * width) + x) * 4; + bgra[offset] = value; + bgra[offset + 1] = value; + bgra[offset + 2] = value; + bgra[offset + 3] = 255; + } + } + + var path = Path.Combine(_directory, name); + await using (var file = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) + using (var stream = file.AsRandomAccessStream()) + { + var encoder = await BitmapEncoder.CreateAsync(encoderId, stream); + encoder.SetPixelData( + BitmapPixelFormat.Bgra8, + BitmapAlphaMode.Ignore, + (uint)width, + (uint)height, + 96, + 96, + bgra); + if (orientation is { } value) + { + await encoder.BitmapProperties.SetPropertiesAsync( + [ + new KeyValuePair( + "System.Photo.Orientation", + new BitmapTypedValue(value, global::Windows.Foundation.PropertyType.UInt16)), + ]); + } + + await encoder.FlushAsync(); + } + + return path; + } + + private async Task SignAsync(string path) + { + var signature = await _strategy.ComputeSignatureAsync(Candidate(path)); + signature.Status.Should().Be("Ready", signature.ErrorMessage); + return signature; + } + + private async Task HashAsync(string path) => Parse(await SignAsync(path)); + + private static ulong Parse(DuplicateSignature signature) => + ulong.Parse(signature.SignatureText!, System.Globalization.NumberStyles.HexNumber); + + private static int Distance(ulong left, ulong right) => BitOperations.PopCount(left ^ right); + + private static DuplicateCandidate Candidate(string path) + { + var info = new FileInfo(path); + return new DuplicateCandidate( + new FileEntry + { + Id = 1, + SessionId = 1, + FullPath = path, + FileName = info.Name, + Extension = info.Extension, + SizeBytes = info.Length, + CreatedUtc = info.CreationTimeUtc, + ModifiedUtc = info.LastWriteTimeUtc, + AccessedUtc = info.LastAccessTimeUtc, + Attributes = info.Attributes, + Category = FileTypeCategory.Image, + }, + null); + } +} diff --git a/tests/StorageMaster.Tests/Localization/SafetyDialogCoverageTests.cs b/tests/StorageMaster.Tests/Localization/SafetyDialogCoverageTests.cs index c9779fb..b1ea3bf 100644 --- a/tests/StorageMaster.Tests/Localization/SafetyDialogCoverageTests.cs +++ b/tests/StorageMaster.Tests/Localization/SafetyDialogCoverageTests.cs @@ -41,8 +41,8 @@ public void EverySafetyConfirmationIsInTheScenarioCatalogue() } /// - /// The first argument of every ConfirmAsync call, which is the dialog's - /// title key. + /// The first argument of every ConfirmAsync and ConfirmItemsAsync + /// call, which is the dialog's title key. /// private static IReadOnlyCollection ConfirmationTitleKeysInSource() { @@ -58,7 +58,7 @@ private static IReadOnlyCollection ConfirmationTitleKeysInSource() foreach (Match match in Regex.Matches( text, - @"ConfirmAsync\(\s*Loc\.(?:Get|Format)\(""(Safety_[A-Za-z0-9_]+)""", + @"Confirm(?:Items)?Async\(\s*Loc\.(?:Get|Format)\(""(Safety_[A-Za-z0-9_]+)""", RegexOptions.Singleline)) { keys.Add(match.Groups[1].Value); diff --git a/tests/StorageMaster.Tests/Scanner/FileScannerTests.cs b/tests/StorageMaster.Tests/Scanner/FileScannerTests.cs index 7d9909b..2954f42 100644 --- a/tests/StorageMaster.Tests/Scanner/FileScannerTests.cs +++ b/tests/StorageMaster.Tests/Scanner/FileScannerTests.cs @@ -47,9 +47,11 @@ public FileScannerTests() .Setup(r => r.UpdateFolderTotalsAsync(It.IsAny(), It.IsAny>(), It.IsAny())) .Returns(Task.CompletedTask); + // One identity per path, as on a real volume. A single shared identity would + // model every file as a hard link to the same one, which the scanner counts once. _identityProvider .Setup(provider => provider.GetIdentityAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(new FileIdentity("TESTVOL", 123)); + .ReturnsAsync((string path, CancellationToken _) => IdentityFor(path)); _scanner = new FileScanner( _repoMock.Object, @@ -99,7 +101,7 @@ await _scanner.ScanAsync( inserted.Should().HaveCount(3); inserted.Should().OnlyContain(static entry => - entry.Identity == new FileIdentity("TESTVOL", 123)); + entry.Identity == IdentityFor(entry.FullPath)); _identityProvider.Verify(provider => provider.GetIdentityAsync( It.IsAny(), It.IsAny()), Times.Exactly(3)); @@ -742,6 +744,9 @@ private static bool CreateJunction(string junction, string target) } } + private static FileIdentity IdentityFor(string path) => + new("TESTVOL", (ulong)(uint)StringComparer.OrdinalIgnoreCase.GetHashCode(Path.GetFullPath(path))); + private static string CreateTempDir(int files, int subdirs) { var root = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); diff --git a/tests/StorageMaster.Tests/Scanner/HardLinkSizeTests.cs b/tests/StorageMaster.Tests/Scanner/HardLinkSizeTests.cs new file mode 100644 index 0000000..5d9795e --- /dev/null +++ b/tests/StorageMaster.Tests/Scanner/HardLinkSizeTests.cs @@ -0,0 +1,189 @@ +using System.Runtime.InteropServices; +using FluentAssertions; +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using StorageMaster.Core.Interfaces; +using StorageMaster.Core.Models; +using StorageMaster.Core.Scanner; +using StorageMaster.Platform.Windows; +using StorageMaster.Storage; +using StorageMaster.Storage.Repositories; + +namespace StorageMaster.Tests.Scanner; + +/// +/// A file with several hard links is one file on disk, so it counts once in folder, +/// category and session totals. Every name is still listed with its real size. +/// +/// The scanner test creates real hard links, inside a temp folder it owns, so the +/// identities come from Windows rather than from a fixture. +/// +/// +public sealed class HardLinkSizeTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"sm_hardlink_{Guid.NewGuid():N}"); + + public HardLinkSizeTests() => Directory.CreateDirectory(_root); + + [Fact] + public void Tracker_CountsAFileOncePerVolumeAndAlwaysCountsUnknownIdentities() + { + var tracker = new HardLinkTracker(); + + tracker.IsFirstLink(new FileIdentity("VOL1", 7)).Should().BeTrue(); + tracker.IsFirstLink(new FileIdentity("vol1", 7)).Should().BeFalse("the same file reached through another name"); + tracker.IsFirstLink(new FileIdentity("VOL2", 7)).Should().BeTrue("the same index on another volume is another file"); + tracker.IsFirstLink(new FileIdentity("VOL1", 8)).Should().BeTrue(); + tracker.IsFirstLink(null).Should().BeTrue(); + tracker.IsFirstLink(null).Should().BeTrue("without an identity nothing can be proven to be shared"); + } + + [Theory] + [InlineData(0UL)] + [InlineData(ulong.MaxValue)] + public void Tracker_NeverTreatsAPlaceholderFileIdAsAHardLink(ulong placeholder) + { + // ReFS reports all ones for a file whose 128-bit id does not fit in 64 bits, + // and some network and user-mode file systems report 0 for every file. + // Unrelated files share those values; folding them would drop all but the + // first file from the totals. + var tracker = new HardLinkTracker(); + + tracker.IsFirstLink(new FileIdentity("VOL1", placeholder)).Should().BeTrue(); + tracker.IsFirstLink(new FileIdentity("VOL1", placeholder)).Should().BeTrue( + "a placeholder id is shared by unrelated files and proves nothing"); + tracker.IsFirstLink(new FileIdentity("VOL1", 5)).Should().BeTrue(); + tracker.IsFirstLink(new FileIdentity("VOL1", 5)).Should().BeFalse("real ids are still tracked"); + } + + [Fact] + public async Task ManagedScan_CountsAHardLinkedFileOnce() + { + var original = Path.Combine(_root, "original.bin"); + File.WriteAllBytes(original, new byte[4096]); + var sub = Directory.CreateDirectory(Path.Combine(_root, "sub")).FullName; + var link = Path.Combine(sub, "link.bin"); + CreateHardLinkOrFail(link, original); + File.WriteAllBytes(Path.Combine(sub, "other.bin"), new byte[100]); + + var files = new List(); + var folders = new List(); + IReadOnlyDictionary? totals = null; + var repo = CapturingRepository(files, folders, captured => totals = captured); + var scanner = new FileScanner(repo.Object, NullLogger.Instance, new FileIdentityProvider()); + + var session = await scanner.ScanAsync( + new ScanOptions { RootPath = _root, MaxParallelism = 1 }, + new Progress()); + + session.Status.Should().Be(ScanStatus.Completed); + session.TotalFiles.Should().Be(3, "every name is still listed"); + session.TotalSizeBytes.Should().Be(4096 + 100, "the linked data exists on disk once"); + files.Should().OnlyContain(entry => entry.SizeBytes == new FileInfo(entry.FullPath).Length, + "each entry keeps the file's real size"); + files.Count(static entry => entry.IsAdditionalHardLink).Should().Be(1); + files.Where(static entry => entry.FileName != "other.bin") + .Should().ContainSingle(static entry => !entry.IsAdditionalHardLink); + folders.Sum(static folder => folder.DirectSizeBytes).Should().Be(4096 + 100); + totals.Should().NotBeNull(); + totals![ScanOptionValidator.NormalizeDirectoryPath(_root)].Should().Be(4096 + 100); + } + + [Fact] + public async Task CategoryBreakdown_CountsAdditionalHardLinksOnce() + { + var databasePath = Path.Combine(_root, "hardlinks.db"); + await using var db = new StorageDbContext(databasePath, NullLogger.Instance); + var repository = new ScanRepository(db); + var session = await repository.CreateSessionAsync(_root); + + await repository.InsertFileEntriesAsync( + [ + Entry(session.Id, @"C:\data\a.jpg", 1000, new FileIdentity("VOL1", 1), additional: false), + Entry(session.Id, @"C:\data\copy\a.jpg", 1000, new FileIdentity("VOL1", 1), additional: true), + Entry(session.Id, @"C:\data\b.jpg", 10, new FileIdentity("VOL1", 2), additional: false), + ]); + + var breakdown = await repository.GetCategoryBreakdownAsync(session.Id); + + breakdown[FileTypeCategory.Image].Should().Be((3L, 1010L), + "both names are counted as files, but the shared data only once"); + } + + public void Dispose() + { + SqliteConnection.ClearAllPools(); + try + { + Directory.Delete(_root, recursive: true); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } + + private static FileEntry Entry(long sessionId, string path, long size, FileIdentity identity, bool additional) => new() + { + Id = 0, + SessionId = sessionId, + FullPath = path, + FileName = Path.GetFileName(path), + Extension = Path.GetExtension(path), + SizeBytes = size, + CreatedUtc = DateTime.UtcNow, + ModifiedUtc = DateTime.UtcNow, + AccessedUtc = DateTime.UtcNow, + Attributes = FileAttributes.Archive, + Category = FileTypeCategory.Image, + Identity = identity, + IsAdditionalHardLink = additional, + }; + + private static Mock CapturingRepository( + List files, + List folders, + Action> onTotals) + { + var repo = new Mock(); + repo.Setup(r => r.CreateSessionAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(new ScanSession { Id = 1, RootPath = @"C:\", StartedUtc = DateTime.UtcNow, Status = ScanStatus.Running }); + repo.Setup(r => r.UpdateSessionAsync(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + repo.Setup(r => r.InsertFileEntriesAsync(It.IsAny>(), It.IsAny())) + .Callback, CancellationToken>((batch, _) => + { + lock (files) + files.AddRange(batch); + }) + .Returns(Task.CompletedTask); + repo.Setup(r => r.UpsertFolderEntriesAsync(It.IsAny>(), It.IsAny())) + .Callback, CancellationToken>((batch, _) => + { + lock (folders) + folders.AddRange(batch); + }) + .Returns(Task.CompletedTask); + repo.Setup(r => r.GetAllFolderPathsForSessionAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(() => (IReadOnlyList)folders.ToArray()); + repo.Setup(r => r.UpdateFolderTotalsAsync( + It.IsAny(), + It.IsAny>(), + It.IsAny())) + .Callback, CancellationToken>((_, captured, _) => onTotals(captured)) + .Returns(Task.CompletedTask); + return repo; + } + + private static void CreateHardLinkOrFail(string link, string existing) + { + if (!CreateHardLink(link, existing, IntPtr.Zero)) + throw new IOException($"CreateHardLink failed with Win32 error {Marshal.GetLastWin32Error()}."); + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); +} diff --git a/tests/StorageMaster.Tests/Storage/SchemaV13MigrationTests.cs b/tests/StorageMaster.Tests/Storage/SchemaV13MigrationTests.cs index c3756b3..0e8338c 100644 --- a/tests/StorageMaster.Tests/Storage/SchemaV13MigrationTests.cs +++ b/tests/StorageMaster.Tests/Storage/SchemaV13MigrationTests.cs @@ -106,6 +106,13 @@ ErrorMessage TEXT INSERT INTO ScanSessions (Id, RootPath, StartedUtc, Status) VALUES (1, 'C:\', '2026-01-01T00:00:00Z', 'Completed'); + -- Every real database has had FileEntries since v1; later levels alter it. + CREATE TABLE FileEntries ( + Id INTEGER PRIMARY KEY AUTOINCREMENT, + SessionId INTEGER NOT NULL REFERENCES ScanSessions(Id) ON DELETE CASCADE, + SizeBytes INTEGER NOT NULL DEFAULT 0 + ); + CREATE TABLE IF NOT EXISTS DuplicateRuns ( Id INTEGER PRIMARY KEY AUTOINCREMENT, SessionId INTEGER NOT NULL REFERENCES ScanSessions(Id) ON DELETE CASCADE, diff --git a/tests/StorageMaster.Tests/Storage/SchemaV16MigrationTests.cs b/tests/StorageMaster.Tests/Storage/SchemaV16MigrationTests.cs new file mode 100644 index 0000000..5e73a2c --- /dev/null +++ b/tests/StorageMaster.Tests/Storage/SchemaV16MigrationTests.cs @@ -0,0 +1,187 @@ +using FluentAssertions; +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Logging.Abstractions; +using StorageMaster.Core.Models; +using StorageMaster.Storage; +using StorageMaster.Storage.Repositories; +using StorageMaster.Storage.Schema; + +namespace StorageMaster.Tests.Storage; + +/// +/// Schema v16 adds FileEntries.IsAdditionalHardLink. An existing database is +/// upgraded in place, so the migration must keep every row and every total exactly +/// as the user saw them before. +/// +public sealed class SchemaV16MigrationTests : IAsyncDisposable +{ + private readonly string _dbPath = + Path.Combine(Path.GetTempPath(), $"test_v16_{Guid.NewGuid():N}.db"); + private StorageDbContext? _context; + + [Fact] + public async Task V15ToV16_KeepsEveryRowAndEveryTotal() + { + await CreateV15DatabaseWithScanAsync(); + + _context = new StorageDbContext(_dbPath, NullLogger.Instance); + var repository = new ScanRepository(_context); + + await using (var connection = await _context.GetConnectionAsync()) + { + (await ScalarAsync(connection, "SELECT MAX(Version) FROM SchemaVersion;")) + .Should().Be(DatabaseSchema.CurrentVersion); + (await ScalarAsync(connection, "SELECT COUNT(*) FROM FileEntries;")).Should().Be(4); + (await ScalarAsync(connection, "SELECT COUNT(*) FROM FileEntries WHERE IsAdditionalHardLink <> 0;")) + .Should().Be(0, "rows written before v16 were never marked"); + + using var columns = connection.CreateCommand(); + columns.CommandText = + "SELECT \"notnull\", dflt_value FROM pragma_table_info('FileEntries') WHERE name = 'IsAdditionalHardLink';"; + using var reader = await columns.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue("v16 adds the column"); + reader.GetInt64(0).Should().Be(1); + reader.GetString(1).Should().Be("0"); + } + + // Older scans keep counting every name, exactly as they were displayed: the + // two names that share an identity were both counted before the upgrade. + var breakdown = await repository.GetCategoryBreakdownAsync(1); + breakdown[FileTypeCategory.Image].Should().Be((3L, 2010L)); + breakdown[FileTypeCategory.Document].Should().Be((1L, 7L)); + + // New rows go in alongside the old ones. + await repository.InsertFileEntriesAsync( + [ + new FileEntry + { + Id = 0, + SessionId = 1, + FullPath = @"C:\data\new\a.jpg", + FileName = "a.jpg", + Extension = ".jpg", + SizeBytes = 1000, + CreatedUtc = DateTime.UtcNow, + ModifiedUtc = DateTime.UtcNow, + AccessedUtc = DateTime.UtcNow, + Attributes = FileAttributes.Archive, + Category = FileTypeCategory.Image, + Identity = new FileIdentity("VOL1", 1), + IsAdditionalHardLink = true, + }, + ]); + (await repository.GetCategoryBreakdownAsync(1))[FileTypeCategory.Image] + .Should().Be((4L, 2010L), "an additional hard link adds a name but no bytes"); + } + + [Fact] + public async Task V16_OpeningAgainDoesNotMigrateTwice() + { + await CreateV15DatabaseWithScanAsync(); + + await using (var first = new StorageDbContext(_dbPath, NullLogger.Instance)) + await using (var connection = await first.GetConnectionAsync()) + { + (await ScalarAsync(connection, "SELECT MAX(Version) FROM SchemaVersion;")) + .Should().Be(DatabaseSchema.CurrentVersion); + } + + SqliteConnection.ClearAllPools(); + _context = new StorageDbContext(_dbPath, NullLogger.Instance); + await using var reopened = await _context.GetConnectionAsync(); + + (await ScalarAsync(reopened, "SELECT COUNT(*) FROM SchemaVersion WHERE Version = 16;")) + .Should().Be(1, "the column is added once; a second ALTER TABLE would fail"); + (await ScalarAsync(reopened, "SELECT COUNT(*) FROM FileEntries;")).Should().Be(4); + } + + public async ValueTask DisposeAsync() + { + if (_context is not null) + await _context.DisposeAsync(); + + SqliteConnection.ClearAllPools(); + try + { + File.Delete(_dbPath); + File.Delete(_dbPath + "-wal"); + File.Delete(_dbPath + "-shm"); + } + catch (IOException) + { + } + } + + /// + /// A database exactly as v15 left it: every migration level up to 15 applied in + /// order, then a scan written with the v15 column set, including two names that + /// share one file identity. + /// + private async Task CreateV15DatabaseWithScanAsync() + { + string[][] levels = + [ + DatabaseSchema.V1Statements, DatabaseSchema.V2Statements, DatabaseSchema.V3Statements, + DatabaseSchema.V4Statements, DatabaseSchema.V5Statements, DatabaseSchema.V6Statements, + DatabaseSchema.V7Statements, DatabaseSchema.V8Statements, DatabaseSchema.V9Statements, + DatabaseSchema.V10Statements, DatabaseSchema.V11Statements, DatabaseSchema.V12Statements, + DatabaseSchema.V13Statements, DatabaseSchema.V14Statements, DatabaseSchema.V15Statements, + ]; + + await using var connection = new SqliteConnection($"Data Source={_dbPath}"); + await connection.OpenAsync(); + using (var transaction = connection.BeginTransaction()) + { + for (var level = 0; level < levels.Length; level++) + { + foreach (var sql in levels[level]) + await ExecuteAsync(connection, transaction, sql); + + await ExecuteAsync( + connection, + transaction, + $"INSERT INTO SchemaVersion (Version, AppliedUtc) VALUES ({level + 1}, '2026-01-01T00:00:00Z');"); + } + + transaction.Commit(); + } + + await ExecuteAsync(connection, null, """ + INSERT INTO ScanSessions (Id, RootPath, StartedUtc, Status) + VALUES (1, 'C:\data', '2026-01-01T00:00:00Z', 'Completed'); + + INSERT INTO FileEntries + (SessionId, FullPath, FileName, Extension, SizeBytes, + CreatedUtc, ModifiedUtc, AccessedUtc, Attributes, Category, IsReparsePoint, + NormalizedFullPath, IdentityVolumeSerial, IdentityFileIndex) + VALUES + (1, 'C:\data\a.jpg', 'a.jpg', '.jpg', 1000, + '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', 32, 'Image', 0, + 'C:\DATA\A.JPG', 'VOL1', '1'), + (1, 'C:\data\link\a.jpg', 'a.jpg', '.jpg', 1000, + '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', 32, 'Image', 0, + 'C:\DATA\LINK\A.JPG', 'VOL1', '1'), + (1, 'C:\data\b.jpg', 'b.jpg', '.jpg', 10, + '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', 32, 'Image', 0, + 'C:\DATA\B.JPG', 'VOL1', '2'), + (1, 'C:\data\c.txt', 'c.txt', '.txt', 7, + '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', 32, 'Document', 0, + 'C:\DATA\C.TXT', NULL, NULL); + """); + } + + private static async Task ExecuteAsync(SqliteConnection connection, SqliteTransaction? transaction, string sql) + { + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = sql; + await command.ExecuteNonQueryAsync(); + } + + private static async Task ScalarAsync(SqliteConnection connection, string sql) + { + using var command = connection.CreateCommand(); + command.CommandText = sql; + return Convert.ToInt64(await command.ExecuteScalarAsync()); + } +} diff --git a/tests/StorageMaster.Tests/UI/PageViewModelThreadingGuardTests.cs b/tests/StorageMaster.Tests/UI/PageViewModelThreadingGuardTests.cs index dc49347..66100bc 100644 --- a/tests/StorageMaster.Tests/UI/PageViewModelThreadingGuardTests.cs +++ b/tests/StorageMaster.Tests/UI/PageViewModelThreadingGuardTests.cs @@ -86,6 +86,61 @@ public void SpaceMapResizeDoesNotRelayoutOnEveryEvent() "the coalescing window is what collapses a drag into one relayout"); } + /// + /// Recycle Bin mode never deletes permanently on its own. Where a page offers to + /// delete what Windows would not recycle, it asks first, lists the items, and only + /// a yes leads to the permanent retry. + /// + [Theory] + [InlineData("DuplicatesViewModel.cs", "private async Task DeleteSelectedAsync()", "BuildPermanentRetryPlan(")] + [InlineData("SmartCleanerViewModel.cs", "private async Task CleanAsync()", "DeletionMethod.Permanent")] + [InlineData("ResultsViewModel.cs", "private async Task DeleteFileAsync(FileEntry file)", "DeletionMethod.Permanent")] + [InlineData("CleanupPage.xaml.cs", "private async Task ShowReportLoopAsync(int navigationGeneration)", "")] + public void RecycleBinRefusalsAreDeletedPermanentlyOnlyAfterTheirOwnConfirmation( + string fileName, + string declaration, + string permanentRetry) + { + var body = MethodBody(fileName, declaration); + if (fileName == "CleanupPage.xaml.cs") + { + // The page delegates the question to a helper; check the helper too. + body.Should().Contain("ConfirmPermanentForRecycleBinRefusalsAsync(", + "the permanent retry of Recycle Bin refusals must sit behind its own question"); + body.IndexOf("ConfirmPermanentForRecycleBinRefusalsAsync(", StringComparison.Ordinal) + .Should().BeLessThan( + body.IndexOf("RunPermanentForRecycleBinRefusalsAsync(", StringComparison.Ordinal), + "the question comes before the retry"); + body = MethodBody(fileName, "private async Task ConfirmPermanentForRecycleBinRefusalsAsync("); + } + + body.Should().Contain("ConfirmItemsAsync(", + "the refused items are listed in the question"); + body.Should().Contain("\"Safety_RecycleRefused_Title\""); + + if (fileName != "CleanupPage.xaml.cs") + { + var question = body.IndexOf("ConfirmItemsAsync(", StringComparison.Ordinal); + var retry = body.IndexOf(permanentRetry, question, StringComparison.Ordinal); + retry.Should().BeGreaterThan(question, "the permanent retry follows the question"); + body[question..retry].Should().MatchRegex(@"if \(!?deletePermanently\)", + "only the user's yes may lead to the permanent retry"); + } + } + + [Fact] + public void TheListedConfirmationDefaultsToNo() + { + var path = Path.Combine(Directory.GetParent(PagesDirectory)!.FullName, "Infrastructure", "DialogService.cs"); + var source = File.ReadAllText(path); + var start = source.IndexOf("public async Task ConfirmItemsAsync(", StringComparison.Ordinal); + start.Should().BeGreaterThanOrEqualTo(0); + var end = source.IndexOf("public async Task ShowErrorAsync(", start, StringComparison.Ordinal); + + source[start..end].Should().Contain("DefaultButton = ContentDialogButton.Close", + "Enter must never answer yes to a permanent deletion"); + } + /// /// Returns the block body of a method, located by the exact text of its declaration /// and delimited by brace matching. The view-model sources contain no brace-escaped