Files
Chronos/tests/Chronos.App.Tests/Archive/TrashDialogTests.cs
T
Alby96 51782a3ada feat(archive): photo delete, tombstones, trash kinds and emptying, library API
Owner review 2, R6: the web panel manages the library without editing it, so
the engine and the server must delete single photos safely, keep them out of
sync afterwards, and let an administrator restore or finally erase the trash.

- Migration 0008: frame_removals (tombstones by sequence and SHA-256, reason,
  replacement); the sidecar gains "removed" (omitted when empty) and frames a
  reserved "source"; the indexer writes the tombstones on every sync, so a
  rebuild keeps them, and drops a hero frame that is gone.
- FrameTrash: dry run (busy, frames changed, offline, would empty), delete under
  the sequence lease with a write-ahead journal that the next writer undoes
  after a crash, files to trash/photos/<seq>-<time>/originals with a record,
  sidecar without the frames plus tombstones, index sync clearing analyses,
  thumbnails and proxies, proxies renamed to follow their frames, follow-up
  jobs. Restore re-hashes every file, keeps mismatches in the trash, puts the
  same frame records back and drops their tombstones, or files the photos into
  a new sequence through the ingest when theirs is gone.
- Project positions on vanished photos are translated by photo and wait as
  pending frames, so they come back with a restore.
- Trash entries have a kind (sequence, photos, replaced); emptying is a dry run
  with a fingerprint and a new EmptyTrash job (18) that erases exactly the
  planned entries, refuses a stale plan and erases replaced originals only
  while their replacements still hash right.
- Sync honours tombstones: nothing one side deleted is offered back, local
  files are never deleted, replaced photos count as their replacement; the
  server answers an upload of a tombstoned SHA-256 as already there.
- Server: sequence thumbnail, photo delete, bulk delete/retag/jobs, trash
  list/restore/empty endpoints with their error messages; a verify of
  sequences now targets their archive (POST /jobs failed before).
- Desktop trash dialog lists photo entries and empties the trash after a
  typed confirmation through the same job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 35bb56690a1d69eae57153d036e1409201cd73f7)
2026-10-27 10:49:34 +01:00

124 lines
6.3 KiB
C#

using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Testing;
namespace Chronos.App.Tests.Archiving;
/// <summary>The trash dialog (owner review 2, R6): photo entries next to sequences, and Empty… behind a dry run and a typed confirmation.</summary>
public sealed class TrashDialogTests(TestContext context)
{
private static readonly DateTimeOffset Deleted = new(2026, 10, 27, 9, 30, 0, TimeSpan.Zero);
private static TrashEntry Entry(string title, TrashKind kind, int photos, long bytes) =>
new(Guid.CreateVersion7(), (kind == TrashKind.Sequence ? string.Empty : FrameTrash.EntryPrefix) + Guid.CreateVersion7().ToString("N"),
Guid.CreateVersion7(), title, "2026/" + title, photos, photos, bytes, Deleted, "alberto", kind);
[Test]
public void EveryKindOfEntryHasWordsAndTheRowSaysWhatItHolds()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
foreach (var kind in Enum.GetValues<TrashKind>())
Assert.NotEqual("Archive.Trash.Kind." + kind, TrashEmptyPlans.KindText(kind), "every kind has words");
var row = new TrashRowViewModel(Entry("Harbour sunset", TrashKind.Photos, 12, 340_000_000), new Chronos.Ui.Mvvm.RelayCommand(() => { }));
Assert.Equal(Loc.L("Archive.Trash.Kind.Photos"), row.KindText);
Assert.True(row.Detail.StartsWith(row.KindText, StringComparison.Ordinal), row.Detail);
Assert.Contains(Loc.Plural("Shell.Status.Photos", 12), row.Detail);
}
[Test]
public void EmptyingAsksToTypeHowManyEntriesAreErased()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var entries = new[] { Entry("Harbour sunset", TrashKind.Photos, 12, 340_000_000), Entry("Comet", TrashKind.Sequence, 1_005, 21_000_000_000) };
var plan = new TrashEmptyPlan(Guid.CreateVersion7(), entries, 21_340_000_000, "f1", []);
var request = Assert.NotNull(TrashEmptyPlans.Request(plan));
Assert.True(request.IsDestructive, "the action is outlined, never primary");
Assert.Equal("2", request.TypedConfirmation);
Assert.Equal(Loc.L("Archive.Delete.Type", "2"), request.TypedPrompt);
Assert.Equal(Loc.Plural("Archive.Trash.EmptyHeading", 2), request.Heading);
Assert.Equal(Loc.L("Archive.Trash.EmptyMessage", Loc.Plural("Shell.Status.Photos", 1_017), Loc.Plural("Archive.Delete.Files", 1_017),
Formatting.Bytes(21_340_000_000)), request.Message);
Assert.Equal(Loc.L("Archive.Trash.Erase"), request.ActionText);
Assert.Equal(Loc.L("Archive.Delete.Keep"), request.SafeText);
var lines = request.Detail!.Split(Environment.NewLine);
Assert.Equal(2, lines.Length);
Assert.Contains(Loc.L("Archive.Trash.Kind.Photos"), lines[0]);
Assert.Null(TrashEmptyPlans.Request(plan with { Entries = [] }), "nothing to erase: no confirmation");
}
[Test]
public async Task EmptyQueuesTheJobOfTheConfirmedPlanOnly()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var directory = context.CreateTempDirectory("trash-dialog");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")));
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)) });
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main");
// A sequence deleted earlier: its folder and its record in the archive's trash.
var id = Guid.CreateVersion7();
var trash = SequenceTrash.TrashDirectory(new Core.Archiving.ArchivePaths(archive.RootPath));
Directory.CreateDirectory(Path.Combine(trash, id.ToString("N")));
await File.WriteAllBytesAsync(Path.Combine(trash, id.ToString("N"), "IMG_0001.JPG"), [1, 2, 3]);
await File.WriteAllTextAsync(Path.Combine(trash, id.ToString("N") + ".json"),
$$"""{"sequence":{"id":"{{id}}","archiveId":"{{archive.Id}}","title":"Harbour sunset","folder":"2026/Harbour","frameCount":1},"renders":[],"files":1,"bytes":3,"deletedAt":"2026-10-27T09:30:00+00:00","deletedBy":"alberto"}""");
var plain = new TrashDialogViewModel(archives, archive, () => Task.CompletedTask, _ => { });
await plain.LoadAsync();
Assert.Count(1, plain.Rows);
Assert.False(plain.CanEmpty, "a host without a job engine offers no emptying");
ConfirmRequest? asked = null;
var answer = false;
var queued = new TaskCompletionSource<ArchiveJobRequest>(TaskCreationOptions.RunContinuationsAsynchronously);
var closed = false;
var dialog = new TrashDialogViewModel(archives, archive, () => Task.CompletedTask, _ => closed = true, r =>
{
asked = r;
return answer;
}, r =>
{
queued.TrySetResult(r);
return Task.CompletedTask;
});
await dialog.LoadAsync();
Assert.True(dialog.CanEmpty);
Assert.Equal(Loc.Plural("Archive.Trash.Entries", 1) + Loc.Separator + Formatting.Bytes(3), dialog.SummaryText);
// Kept: the confirmation was dismissed, nothing is queued.
dialog.EmptyCommand.Execute(null);
await UntilAsync(() => asked is not null && !dialog.IsBusy);
Assert.Equal("1", asked!.TypedConfirmation);
Assert.False(queued.Task.IsCompleted);
Assert.False(closed);
answer = true;
dialog.EmptyCommand.Execute(null);
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
Assert.Equal(JobKind.EmptyTrash, request.Kind);
Assert.SequenceEqual([archive.Id], request.Targets);
Assert.Contains(id.ToString("N"), request.ParametersJson);
await UntilAsync(() => closed);
Assert.Count(1, await archives.ListTrashAsync(archive.Id), "the job erases, not the dialog");
}
private static async Task UntilAsync(Func<bool> condition)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (!condition())
{
Assert.True(DateTime.UtcNow < until, "timed out");
await Task.Delay(20);
}
}
}