Reorganize with the archive's own templates planned renames and moves for
photos just filed, and some templates could strip extensions, hide sequences
from scans or stall a dry run. Owner review 2, phase 4a findings.
- Filing and Reorganize share one context: uploads and imports name every
photo with the sequence's camera and lens (its first photo's, or the
creator's hint), an upload's folder from its first frame in the new
sequence, and a missing capture time from the sequence start instead of
the current time. The planner expands folder and title templates from the
first frame in the sidecar ({name}, {ext}, {iso}...), never today's date.
- Titles expand as text (ExpandText): "Paris: night" stays as typed.
- A sequence whose sidecar cannot be read (torn, another sequence's) keeps
its folder, title and names, listed with why, and so does every folder
around it; the dry run reads every sidecar, nested ones included.
- Kept never gives one folder to two sequences of a plan whatever the case,
and a case-only move onto another folder is refused instead of taken as
done.
- Shared template rules (TemplateRules) for the server's Reorganize and
archive settings and the desktop's fields: a file template must keep the
photo's extension ("{n}{ext}" refused) and tell a session's photos apart;
a folder template may not write a level scans skip (a leading dot,
originals, proxies, exports). Levels a title gives are escaped with "_".
- {ext} comes from the file, or from the original name when the file lost
a photo's extension, so a Reorganize can put it back.
- Unique names cost linear time (UniqueNames) with the same names as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 6c734777e01476881a3f34b3188571cc3f7150ab)
200 lines
12 KiB
C#
200 lines
12 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Chronos.Core.Codecs.Jpeg;
|
|
using Chronos.Core.Model;
|
|
using Chronos.Protocol;
|
|
using Chronos.Server.Events;
|
|
using Chronos.Server.Storage;
|
|
using Chronos.Testing;
|
|
|
|
namespace Chronos.Server.Tests.Api;
|
|
|
|
/// <summary>
|
|
/// Reorganize on the server (owner review 2, R7): <c>POST /api/v1/archive/reorganize</c>, its dry run, the <c>move</c> job that
|
|
/// applies the confirmed plan, and what the request may not do, against the real archive engine.
|
|
/// </summary>
|
|
[Category("server")]
|
|
public sealed class ReorganizeTests(TestContext context)
|
|
{
|
|
private const string Url = "/api/v1/archive/reorganize";
|
|
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
|
|
|
|
[Test]
|
|
public async Task AReorganizeIsDryRunThenAppliedByAJob()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
|
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
|
var admin = await server.AdminAsync();
|
|
Guid id = default;
|
|
for (var i = 0; i < 3; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
|
await UntilIdleAsync(server);
|
|
var before = await server.Database.Frames.ListBySequenceAsync(id);
|
|
|
|
var request = new ReorganizeRequest([id], false, "reorganized/{title}", "{title}_{n:000}", "Roof", DryRun: true);
|
|
ReorganizePlanDto plan;
|
|
using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest))
|
|
plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
|
Assert.Equal((1, 3, 0), (plan.Sequences, plan.Files, plan.Kept));
|
|
var step = plan.Steps.Single();
|
|
Assert.Equal((id, "reorganized/Roof", "Roof", 3), (step.SequenceId, step.ToFolder, step.ToTitle, step.FileChanges));
|
|
Assert.SequenceEqual(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], step.FileSamples.Select(f => f.To));
|
|
Assert.Equal(64, plan.Fingerprint.Length);
|
|
Assert.SequenceEqual(before.Select(f => f.RelativePath), (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.RelativePath));
|
|
|
|
using (var missing = await admin.PostAsJsonAsync(Url, request with { DryRun = false }, ProtocolJson.Default.ReorganizeRequest))
|
|
Assert.Equal("fingerprint", (await missing.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
|
|
using (var wrong = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = "0123" }, ProtocolJson.Default.ReorganizeRequest))
|
|
Assert.Equal(plan.Fingerprint, (await wrong.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
|
|
|
|
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
|
|
JobDto job;
|
|
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
|
|
{
|
|
await applied.ExpectAsync(HttpStatusCode.Accepted);
|
|
job = await applied.ReadAsync(ProtocolJson.Default.JobDto);
|
|
}
|
|
Assert.Equal("move", job.Kind);
|
|
await UntilJobAsync(admin, job.Id, "done");
|
|
|
|
var sequence = (await server.Database.Sequences.GetAsync(id))!;
|
|
Assert.Equal(("reorganized/Roof", "Roof"), (sequence.Folder, sequence.Title));
|
|
var after = await server.Database.Frames.ListBySequenceAsync(id);
|
|
Assert.SequenceEqual(before.Select(f => f.Id), after.Select(f => f.Id));
|
|
Assert.SequenceEqual(["reorganized/Roof/originals/Roof_001.JPG", "reorganized/Roof/originals/Roof_002.JPG", "reorganized/Roof/originals/Roof_003.JPG"],
|
|
after.Select(f => f.RelativePath));
|
|
foreach (var (was, now) in before.Zip(after))
|
|
Assert.Equal(was.Sha256, Uploads.Sha(File.ReadAllBytes(Path.Combine(server.Options.ArchivePath, now.RelativePath))));
|
|
Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "archive_reorganized", 10, null)).Items);
|
|
|
|
var until = DateTime.UtcNow + Wait;
|
|
while (true)
|
|
{
|
|
using var timeout = new CancellationTokenSource(until - DateTime.UtcNow);
|
|
var e = await events.Reader.ReadAsync(timeout.Token);
|
|
if (e is SequenceChangedEvent { Change: "reorganized" } changed && changed.SequenceId == id)
|
|
{
|
|
Assert.Equal(sequence.FramesVersion, changed.FramesVersion);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
public async Task AReorganizeAsksForTheArchiveAndAValidRequest()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
|
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
|
var admin = await server.AdminAsync();
|
|
var a = (await Uploads.UploadAsync(editor, Photo(1), "a.jpg", sessionKey: "a")).SequenceId;
|
|
var b = (await Uploads.UploadAsync(editor, Photo(2), "b.jpg", sessionKey: "b")).SequenceId;
|
|
await UntilIdleAsync(server);
|
|
var valid = new ReorganizeRequest([a], false, null, "{n:000}", null, DryRun: true);
|
|
|
|
using (var forbidden = await editor.PostAsJsonAsync(Url, valid, ProtocolJson.Default.ReorganizeRequest))
|
|
await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
|
foreach (var (bad, details) in new[]
|
|
{
|
|
(valid with { All = true }, "sequenceIds"),
|
|
(valid with { SequenceIds = null }, "sequenceIds"),
|
|
(valid with { SequenceIds = [] }, "sequenceIds"),
|
|
(valid with { FileTemplate = null }, "templates"),
|
|
})
|
|
{
|
|
using var response = await admin.PostAsJsonAsync(Url, bad, ProtocolJson.Default.ReorganizeRequest);
|
|
Assert.Equal(details, (await response.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
|
|
}
|
|
using (var template = await admin.PostAsJsonAsync(Url, valid with { FileTemplate = "{nope}" }, ProtocolJson.Default.ReorganizeRequest))
|
|
Assert.Equal("fileTemplate", (await template.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
|
|
// The desktop's rules: no lost extension, names that tell the photos apart, no folder scans skip.
|
|
foreach (var (bad, field) in new[]
|
|
{
|
|
(valid with { FileTemplate = "{n}{ext}" }, "fileTemplate"),
|
|
(valid with { FileTemplate = "{title}" }, "fileTemplate"),
|
|
(valid with { FolderTemplate = "Exports/{title}" }, "folderTemplate"),
|
|
(valid with { FolderTemplate = ".hidden/{date}" }, "folderTemplate"),
|
|
})
|
|
{
|
|
using var refused = await admin.PostAsJsonAsync(Url, bad, ProtocolJson.Default.ReorganizeRequest);
|
|
Assert.Equal(field, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
|
|
}
|
|
using (var blank = await admin.PostAsJsonAsync(Url, valid with { FolderTemplate = " " }, ProtocolJson.Default.ReorganizeRequest))
|
|
Assert.Equal("folderTemplate", (await blank.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
|
|
using (var unknown = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = [Guid.NewGuid()] }, ProtocolJson.Default.ReorganizeRequest))
|
|
await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
|
|
|
|
// One sequence's new folder inside the other's: refused, nothing planned.
|
|
var host = (await server.Database.Sequences.GetAsync(a))!.Folder;
|
|
using (var nested = await admin.PostAsJsonAsync(Url, new ReorganizeRequest([b], false, host + "/inside", null, null, DryRun: true),
|
|
ProtocolJson.Default.ReorganizeRequest))
|
|
Assert.Equal(host + "/inside", (await nested.ExpectErrorAsync(HttpStatusCode.Conflict, "nested_target")).Details);
|
|
|
|
using (var all = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = null, All = true }, ProtocolJson.Default.ReorganizeRequest))
|
|
{
|
|
var plan = await all.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
|
Assert.Equal((2, 2), (plan.Sequences, plan.Files));
|
|
Assert.SequenceEqual(new[] { a, b }.Order(), plan.Steps.Select(s => s.SequenceId).Order());
|
|
}
|
|
Assert.Empty((await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Move)).Items);
|
|
}
|
|
|
|
[Test]
|
|
public async Task PhotosThatKeepTheirNamesAreToldWhy()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
|
var admin = await server.AdminAsync();
|
|
// Photos copied into the archive by hand and found by a scan stay where they are.
|
|
var folder = Path.Combine(server.Options.ArchivePath, "trips");
|
|
Directory.CreateDirectory(folder);
|
|
for (var i = 0; i < 2; i++) await File.WriteAllBytesAsync(Path.Combine(folder, $"IMG_{i:0000}.JPG"), Photo(i));
|
|
using (var scan = await admin.PostAsync("/api/v1/archive/scan", null)) await scan.ExpectAsync(HttpStatusCode.Accepted);
|
|
await UntilIdleAsync(server);
|
|
var id = (await server.Database.Sequences.ListLocationsAsync((await server.Database.Archives.ListAsync()).Single().Id)).Single().Id;
|
|
|
|
var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true);
|
|
admin.DefaultRequestHeaders.AcceptLanguage.ParseAdd("it");
|
|
using var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest);
|
|
var plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
|
Assert.Equal((0, 0, 2), (plan.Sequences, plan.Files, plan.Kept));
|
|
var blocked = plan.Steps.Single().Blocked.Single();
|
|
Assert.Equal(("in_place", 2), (blocked.Reason, blocked.Photos));
|
|
Assert.Equal(Chronos.Core.Localization.Loc.Get("Archive.Reorganize.Blocked.InPlace", System.Globalization.CultureInfo.GetCultureInfo("it")), blocked.Message);
|
|
}
|
|
|
|
private static async Task UntilJobAsync(HttpClient client, Guid id, string state)
|
|
{
|
|
var until = DateTime.UtcNow + Wait;
|
|
while (true)
|
|
{
|
|
using var response = await client.GetAsync($"/api/v1/jobs/{id}");
|
|
var job = await response.ReadAsync(ProtocolJson.Default.JobDto);
|
|
if (job.State == state) return;
|
|
if (job.State is "failed" or "cancelled") Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
|
|
Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State}");
|
|
await Task.Delay(50);
|
|
}
|
|
}
|
|
|
|
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
|
|
private static async Task UntilIdleAsync(TestServer server)
|
|
{
|
|
var until = DateTime.UtcNow + Wait;
|
|
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
|
|
{
|
|
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
|
|
{
|
|
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
|
|
await Task.Delay(50);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static byte[] Photo(int seed)
|
|
{
|
|
const int width = 96, height = 64;
|
|
var pixels = new byte[width * height * 3];
|
|
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
|
|
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
|
|
}
|
|
}
|