feat: owner review 2 phase 3: Library on the web panel, photo trash and web upload (#11)
CI / Build and test (push) Successful in 7m25s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
CI / PostgreSQL 16 integration (push) Successful in 5m20s
CI / PostgreSQL 17 integration (push) Successful in 5m22s
CI / Docker image (push) Successful in 50s
Release / Build, test and publish (push) Successful in 12m1s
Release / Server image (push) Successful in 1m26s

- Web panel Library: browse, view, delete sequences and photos, mass operations (analyse, proxies, thumbnails, verify, retag, delete, CSV). It never edits the video.
- Photo trash with tombstones (migration 0008): crash-safe delete and restore, hash-checked restore with reasons, and emptying only by an explicit fingerprinted job. Sync and uploads keep deleted photos deleted; an explicit "Upload again" brings one back.
- Upload from the web panel: in-house SHA-256 in a worker with a fail-closed self-test, capture time from EXIF, chunked, resumable; no folders.
- Desktop trash dialog with photo entries and Empty.
- Admin files are revalidated (no-cache + ETag).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #11.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 15:08:39 +01:00
1 parent af9eeaab9b
commit 9aa818ed47
283 files changed
+24922 -293

No files matched your search

@@ -0,0 +1,662 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary>
/// The library the admin panel manages (owner review 2, R6): sequence thumbnails, photos deleted into the trash, the trash
/// listed, restored and emptied, and bulk operations, against the real archive engine.
/// </summary>
[Category("server")]
public sealed class LibraryTests(TestContext context)
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
[Test]
public async Task PhotosAreDeletedIntoTheTrashAndRestoredThroughTheApi()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (other, _, _) = await server.UserAsync("giulia", "editor");
var admin = await server.AdminAsync();
var photos = Enumerable.Range(0, 3).Select(Photo).ToList();
Guid? id = null;
for (var i = 0; i < photos.Count; i++) id = (await Uploads.UploadAsync(editor, photos[i], $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
await UntilIdleAsync(server);
var sequence = (await server.Database.Sequences.GetAsync(id!.Value))!;
var frames = await server.Database.Frames.ListBySequenceAsync(sequence.Id);
var url = $"/api/v1/sequences/{sequence.Id}/frames/delete";
using (var forbidden = await other.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], null, false), ProtocolJson.Default.FrameDeleteRequest))
await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var none = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([], null, false), ProtocolJson.Default.FrameDeleteRequest))
await none.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
using (var stale = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], sequence.FramesVersion - 1, false),
ProtocolJson.Default.FrameDeleteRequest))
Assert.Equal(sequence.FramesVersion.ToString(System.Globalization.CultureInfo.InvariantCulture),
(await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "frames_conflict")).Details);
using (var all = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([.. frames.Select(f => f.Id)], null, false), ProtocolJson.Default.FrameDeleteRequest))
await all.ExpectErrorAsync(HttpStatusCode.Conflict, "would_empty");
using (var dry = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], sequence.FramesVersion, true), ProtocolJson.Default.FrameDeleteRequest))
{
var plan = await dry.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto);
Assert.True(plan.DryRun);
Assert.Equal((1, frames[1].Size, 3), (plan.Photos, plan.Bytes, plan.FrameCount));
Assert.Null(plan.TrashEntry);
}
Assert.Count(3, await server.Database.Frames.ListBySequenceAsync(sequence.Id));
FrameDeleteResultDto done;
using (var deleted = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], sequence.FramesVersion, false),
ProtocolJson.Default.FrameDeleteRequest))
done = await deleted.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto);
Assert.False(done.DryRun);
Assert.Equal((2, sequence.FramesVersion + 1), (done.FrameCount, done.FramesVersion));
var name = Assert.NotNull(done.TrashEntry);
Assert.FileMissing(Path.Combine(server.Options.ArchivePath, frames[1].RelativePath));
// The manifest names the deleted photo, so clients do not send it back; an upload of it is answered as already there.
using (var manifest = await editor.GetAsync($"/api/v1/sequences/{sequence.Id}/manifest"))
Assert.SequenceEqual([Uploads.Sha(photos[1])], Assert.NotNull((await manifest.ReadAsync(ProtocolJson.Default.SequenceManifest)).Removed).Select(r => r.Sha256));
var again = await Uploads.StartAsync(editor, photos[1], "IMG_0002.JPG", sequence.Id, expected: HttpStatusCode.OK);
Assert.True(again.AlreadyExists);
Assert.Null(again.FrameId);
Assert.Count(2, await server.Database.Frames.ListBySequenceAsync(sequence.Id));
using (var notAdmin = await editor.GetAsync("/api/v1/archive/trash")) await notAdmin.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var list = await admin.GetAsync("/api/v1/archive/trash"))
{
var trash = await list.ReadAsync(ProtocolJson.Default.TrashListDto);
var entry = Assert.Contains(trash.Entries, e => e.Name == name);
Assert.Equal(("photos", 1, sequence.Id, "alberto"), (entry.Kind, entry.Photos, entry.SequenceId, entry.DeletedBy));
Assert.Equal(frames[1].Size, trash.Bytes);
}
await UntilIdleAsync(server);
using (var restored = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null))
{
var result = await restored.ReadAsync(ProtocolJson.Default.TrashRestoreDto);
Assert.Equal(("photos", sequence.Id, 1, false), (result.Kind, result.SequenceId, result.Photos, result.NewSequence));
Assert.Empty(result.Kept);
}
Assert.SequenceEqual(frames.Select(f => f.Id), (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
using (var gone = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null)) await gone.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var bad = await admin.PostAsync("/api/v1/archive/trash/..%2F..%2Fsecret/restore", null)) Assert.Equal(HttpStatusCode.NotFound, bad.StatusCode);
}
[Test]
public async Task TheTrashIsEmptiedByAJobAfterADryRunAndItsFingerprint()
{
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(10), "a.jpg", sessionKey: "a")).SequenceId;
Guid b = default;
for (var i = 0; i < 2; i++) b = (await Uploads.UploadAsync(editor, Photo(20 + i), $"b{i}.jpg", sessionKey: "b")).SequenceId;
await UntilIdleAsync(server);
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{a}")) await deleted.ExpectAsync(HttpStatusCode.OK);
var frames = await server.Database.Frames.ListBySequenceAsync(b);
using (var photo = await editor.PostAsJsonAsync($"/api/v1/sequences/{b}/frames/delete", new FrameDeleteRequest([frames[0].Id], null, false),
ProtocolJson.Default.FrameDeleteRequest))
await photo.ExpectAsync(HttpStatusCode.OK);
await UntilIdleAsync(server);
TrashEmptyPlanDto plan;
using (var dry = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, true, null), ProtocolJson.Default.TrashEmptyRequest))
plan = await dry.ReadAsync(ProtocolJson.Default.TrashEmptyPlanDto);
Assert.Equal(2, plan.Entries.Count);
Assert.SequenceEqual(["photos", "sequence"], plan.Entries.Select(e => e.Kind).Order());
Assert.Equal(2, plan.Photos);
using (var noPrint = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, null), ProtocolJson.Default.TrashEmptyRequest))
await noPrint.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
using (var wrong = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, "0123"), ProtocolJson.Default.TrashEmptyRequest))
Assert.Equal(plan.Fingerprint, (await wrong.ExpectErrorAsync(HttpStatusCode.Conflict, "trash_changed")).Details);
using (var names = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(["../x"], true, null), ProtocolJson.Default.TrashEmptyRequest))
await names.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
JobDto job;
using (var empty = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, plan.Fingerprint),
ProtocolJson.Default.TrashEmptyRequest))
{
await empty.ExpectAsync(HttpStatusCode.Accepted);
job = await empty.ReadAsync(ProtocolJson.Default.JobDto);
}
Assert.Equal("empty-trash", job.Kind);
// The audit log records the request: the job checks the plan again when it runs and may erase nothing.
var requests = (await server.Database.Audit.ListAsync(null, "trash_empty_requested", 50, null, context.Cancellation)).Items;
Assert.Count(1, requests);
Assert.Equal(("job", job.Id.ToString()), (requests[0].TargetKind, requests[0].TargetId));
Assert.True(requests[0].Details?.StartsWith($"2 · {plan.Bytes} · ", StringComparison.Ordinal) == true, requests[0].Details);
Assert.Empty((await server.Database.Audit.ListAsync(null, "trash_emptied", 50, null, context.Cancellation)).Items);
await UntilJobAsync(admin, job.Id, "done");
using (var list = await admin.GetAsync("/api/v1/archive/trash")) Assert.Empty((await list.ReadAsync(ProtocolJson.Default.TrashListDto)).Entries);
Assert.Empty(Directory.EnumerateFiles(server.Options.TrashPath, "*", SearchOption.AllDirectories));
Assert.Count(1, await server.Database.Frames.ListBySequenceAsync(b));
}
[Test]
public async Task EmptyingNamedEntriesErasesOnlyThose()
{
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(50), "a.jpg", sessionKey: "a")).SequenceId;
Guid b = default;
for (var i = 0; i < 2; i++) b = (await Uploads.UploadAsync(editor, Photo(51 + i), $"b{i}.jpg", sessionKey: "b")).SequenceId;
await UntilIdleAsync(server);
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{a}")) await deleted.ExpectAsync(HttpStatusCode.OK);
var photo = await DeletePhotoAsync(editor, b, (await server.Database.Frames.ListBySequenceAsync(b))[0].Id);
await UntilIdleAsync(server);
TrashEmptyPlanDto plan;
using (var dry = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest([photo], true, null), ProtocolJson.Default.TrashEmptyRequest))
plan = await dry.ReadAsync(ProtocolJson.Default.TrashEmptyPlanDto);
Assert.SequenceEqual([photo], plan.Entries.Select(e => e.Name));
using (var empty = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest([photo], false, plan.Fingerprint),
ProtocolJson.Default.TrashEmptyRequest))
await UntilJobAsync(admin, (await empty.ReadAsync(ProtocolJson.Default.JobDto)).Id, "done");
// Only the named entry went: the deleted sequence is still listed, its folder still there.
using (var list = await admin.GetAsync("/api/v1/archive/trash"))
Assert.SequenceEqual([a.ToString("N")], (await list.ReadAsync(ProtocolJson.Default.TrashListDto)).Entries.Select(e => e.Name));
Assert.True(Directory.Exists(Path.Combine(server.Options.TrashPath, a.ToString("N"))));
Assert.False(Directory.Exists(PhotoEntryFolder(server, photo)));
}
[Test]
public async Task TheDeletedSequenceComesBackAndASecondCopyIsRefused()
{
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 < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(60 + i), $"IMG_{i + 1:0000}.JPG", sessionKey: "s")).SequenceId;
await UntilIdleAsync(server);
var row = (await server.Database.Sequences.GetAsync(id))!;
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{id}")) await deleted.ExpectAsync(HttpStatusCode.OK);
var name = id.ToString("N");
// The index holds that sequence again (scanned back, or restored elsewhere): this copy cannot come back over it.
await server.Database.Sequences.UpsertAsync(row);
using (var twice = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null)) await twice.ExpectErrorAsync(HttpStatusCode.Conflict, "sequence_in_library");
Assert.True(Directory.Exists(Path.Combine(server.Options.TrashPath, name)));
await server.Database.Sequences.DeleteAsync(id);
using (var restored = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null))
{
var result = await restored.ReadAsync(ProtocolJson.Default.TrashRestoreDto);
Assert.Equal(("sequence", id, 2, false), (result.Kind, result.SequenceId, result.Photos, result.NewSequence));
}
Assert.Count(2, await server.Database.Frames.ListBySequenceAsync(id));
Assert.False(Directory.Exists(Path.Combine(server.Options.TrashPath, name)));
}
[Test]
public async Task PhotosOfADeletedSequenceComeBackAsANewOne()
{
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(70 + i), $"IMG_{i + 1:0000}.JPG", sessionKey: "gone")).SequenceId;
await UntilIdleAsync(server);
var frames = await server.Database.Frames.ListBySequenceAsync(id);
var name = await DeletePhotoAsync(editor, id, frames[1].Id);
await UntilIdleAsync(server);
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{id}")) await deleted.ExpectAsync(HttpStatusCode.OK);
TrashRestoreDto result;
using (var restored = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null)) result = await restored.ReadAsync(ProtocolJson.Default.TrashRestoreDto);
Assert.Equal(("photos", 1, true), (result.Kind, result.Photos, result.NewSequence));
Assert.NotEqual(id, result.SequenceId);
Assert.SequenceEqual([frames[1].Sha256], (await server.Database.Frames.ListBySequenceAsync(result.SequenceId)).Select(f => f.Sha256));
}
[Test]
public async Task ADamagedSidecarOrEntryIsAnsweredWithItsOwnCode()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var photos = Enumerable.Range(0, 3).Select(i => Photo(80 + i)).ToList();
Guid s = default;
for (var i = 0; i < photos.Count; i++) s = (await Uploads.UploadAsync(editor, photos[i], $"IMG_{i + 1:0000}.JPG", sessionKey: "s")).SequenceId;
var t = (await Uploads.UploadAsync(editor, Photo(90), "other.jpg", sessionKey: "t")).SequenceId;
await UntilIdleAsync(server);
var frames = await server.Database.Frames.ListBySequenceAsync(s);
var name = await DeletePhotoAsync(editor, s, frames[1].Id);
await UntilIdleAsync(server);
var archive = new Chronos.Core.Archiving.ArchivePaths(server.Options.ArchivePath);
var sidecar = archive.Sequence((await server.Database.Sequences.GetAsync(s))!.Folder).ManifestPath;
var other = archive.Sequence((await server.Database.Sequences.GetAsync(t))!.Folder).ManifestPath;
var own = await File.ReadAllBytesAsync(sidecar, context.Cancellation);
// The sequence's folder holds another sequence's sidecar: said as such, not as a damaged trash entry or a server error.
File.Copy(other, sidecar, overwrite: true);
try
{
using (var restore = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null)) await restore.ExpectErrorAsync(HttpStatusCode.Conflict, "sidecar_mismatch");
using (var delete = await editor.PostAsJsonAsync($"/api/v1/sequences/{s}/frames/delete", new FrameDeleteRequest([frames[0].Id], null, false),
ProtocolJson.Default.FrameDeleteRequest))
await delete.ExpectErrorAsync(HttpStatusCode.Conflict, "sidecar_mismatch");
}
finally
{
await File.WriteAllBytesAsync(sidecar, own, context.Cancellation);
}
Assert.Count(2, await server.Database.Frames.ListBySequenceAsync(s));
Assert.FileExists(Path.Combine(server.Options.ArchivePath, frames[0].RelativePath));
// The entry's own file no longer matches its record: that is the trash mismatch, and the entry stays.
var trashed = Path.Combine(PhotoEntryFolder(server, name), "originals", Path.GetFileName(frames[1].RelativePath));
var bytes = await File.ReadAllBytesAsync(trashed, context.Cancellation);
bytes[^10] ^= 0x01;
await File.WriteAllBytesAsync(trashed, bytes, context.Cancellation);
using (var mismatch = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null))
await mismatch.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "trash_mismatch");
Assert.FileExists(trashed);
// A deleted sequence whose own sidecar names another sequence does not match its record either; its folder stays in the trash.
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{t}")) await deleted.ExpectAsync(HttpStatusCode.OK);
var entry = t.ToString("N");
File.Copy(sidecar, archive.Sequence(".chronos/trash/" + entry).ManifestPath, overwrite: true);
using (var foreign = await admin.PostAsync($"/api/v1/archive/trash/{entry}/restore", null))
await foreign.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "trash_mismatch");
Assert.True(Directory.Exists(Path.Combine(server.Options.TrashPath, entry)));
Assert.Null(await server.Database.Sequences.GetAsync(t));
}
[Test]
public async Task ARestoreSaysWhichPhotosStayedAndWhy()
{
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 < 4; i++) id = (await Uploads.UploadAsync(editor, Photo(120 + i), $"IMG_{i + 1:0000}.JPG", sessionKey: "kept")).SequenceId;
await UntilIdleAsync(server);
var frames = await server.Database.Frames.ListBySequenceAsync(id);
string name;
using (var deleted = await editor.PostAsJsonAsync($"/api/v1/sequences/{id}/frames/delete", new FrameDeleteRequest([frames[1].Id, frames[2].Id], null, false),
ProtocolJson.Default.FrameDeleteRequest))
name = Assert.NotNull((await deleted.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
await UntilIdleAsync(server);
var trashed = Path.Combine(PhotoEntryFolder(server, name), "originals", Path.GetFileName(frames[2].RelativePath));
var bytes = await File.ReadAllBytesAsync(trashed, context.Cancellation);
bytes[^10] ^= 0x01;
await File.WriteAllBytesAsync(trashed, bytes, context.Cancellation);
using var restored = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null);
var result = await restored.ReadAsync(ProtocolJson.Default.TrashRestoreDto);
Assert.Equal(1, result.Photos);
Assert.SequenceEqual([frames[2].OriginalFileName!], result.Kept);
Assert.SequenceEqual(["mismatch"], Assert.NotNull(result.KeptReasons));
Assert.Equal(KeptPhoto.Sentence(KeptReason.Mismatch, 1, System.Globalization.CultureInfo.GetCultureInfo("en")), result.Message);
}
[Test]
[WindowsOnly]
public async Task APhotoNeverHashedIsDeletedUnlessItCannotBeRead()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
// Photos copied into the archive by hand and scanned: adopted, never hashed.
var shoot = Path.Combine(server.Options.ArchivePath, "Shoot");
Directory.CreateDirectory(shoot);
for (var i = 0; i < 3; i++) await File.WriteAllBytesAsync(Path.Combine(shoot, $"IMG_{i + 1:0000}.JPG"), Photo(130 + i), context.Cancellation);
var archives = server.Services.GetRequiredService<ArchiveService>();
await archives.Indexer.ScanAsync(server.Services.GetRequiredService<ServerArchive>().Current, ScanMode.Incremental, null, _ => ValueTask.CompletedTask,
context.Cancellation);
await UntilIdleAsync(server);
var id = (await server.Database.Sequences.ListLocationsAsync(server.Services.GetRequiredService<ServerArchive>().Id)).Single(l => l.Folder == "Shoot").Id;
var frames = await server.Database.Frames.ListBySequenceAsync(id);
Assert.True(frames.All(f => f.Sha256 is null), "adopted, not verified");
var url = $"/api/v1/sequences/{id}/frames/delete";
// Another program holds one: it cannot be hashed for its tombstone, and the answer names it (no frames_conflict loop).
var held = Path.Combine(server.Options.ArchivePath, frames[1].RelativePath);
using (new FileStream(held, FileMode.Open, FileAccess.Read, FileShare.None))
{
using var refused = await admin.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], null, false), ProtocolJson.Default.FrameDeleteRequest);
var error = await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "photo_unreadable");
Assert.Equal("1", error.Details);
Assert.Contains("IMG_0002.JPG", error.Message);
}
Assert.FileExists(held);
// One whose original is gone has nothing left to hash: it goes, without a tombstone.
File.Delete(Path.Combine(server.Options.ArchivePath, frames[2].RelativePath));
using (var gone = await admin.PostAsJsonAsync(url, new FrameDeleteRequest([frames[2].Id], null, false), ProtocolJson.Default.FrameDeleteRequest))
Assert.NotNull((await gone.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
Assert.Empty(await server.Database.FrameRemovals.ListBySequenceAsync(id));
Assert.SequenceEqual([frames[0].Id, frames[1].Id], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.Id));
}
[Test]
public async Task APhotoDeleteTakesAsManyIdsAsItsLimit()
{
// 100,000 ids are about 3.9 MB of JSON, above the server's 1 MiB for other bodies: the route has its own limit.
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var id = (await Uploads.UploadAsync(editor, Photo(100), "IMG_0001.JPG", sessionKey: "many")).SequenceId;
await Uploads.UploadAsync(editor, Photo(101), "IMG_0002.JPG", sessionKey: "many");
await UntilIdleAsync(server);
var url = $"/api/v1/sequences/{id}/frames/delete";
var ids = Enumerable.Range(0, Chronos.Server.Api.LibraryEndpoints.MaxFrameIds).Select(_ => Guid.CreateVersion7()).ToList();
// Read whole and planned: those ids are not the sequence's photos.
using (var most = await editor.PostAsJsonAsync(url, new FrameDeleteRequest(ids, null, true), ProtocolJson.Default.FrameDeleteRequest))
await most.ExpectErrorAsync(HttpStatusCode.Conflict, "frames_conflict");
ids.Add(Guid.CreateVersion7());
using (var tooMany = await editor.PostAsJsonAsync(url, new FrameDeleteRequest(ids, null, true), ProtocolJson.Default.FrameDeleteRequest))
Assert.Equal("frameIds", (await tooMany.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
Assert.Count(2, await server.Database.Frames.ListBySequenceAsync(id));
}
[Test]
public async Task WithTheArchiveOfflineTheTrashAndDeletesAnswerArchiveOffline()
{
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 < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(110 + i), $"IMG_{i + 1:0000}.JPG", sessionKey: "off")).SequenceId;
await UntilIdleAsync(server);
var frames = await server.Database.Frames.ListBySequenceAsync(id);
var name = await DeletePhotoAsync(editor, id, frames[0].Id);
await UntilIdleAsync(server);
// The archive drive is gone: the trash is not empty, it cannot be read.
var manifest = new Chronos.Core.Archiving.ArchivePaths(server.Options.ArchivePath).ManifestPath;
File.Move(manifest, manifest + ".away");
try
{
using (var list = await admin.GetAsync("/api/v1/archive/trash")) await list.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
using (var dry = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, true, null), ProtocolJson.Default.TrashEmptyRequest))
await dry.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
using (var empty = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, "0123"), ProtocolJson.Default.TrashEmptyRequest))
await empty.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
using (var restore = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null))
await restore.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
using (var delete = await editor.PostAsJsonAsync($"/api/v1/sequences/{id}/frames/delete", new FrameDeleteRequest([frames[1].Id], null, true),
ProtocolJson.Default.FrameDeleteRequest))
await delete.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
using (var bulk = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/delete", new BulkDeleteRequest([id], false), ProtocolJson.Default.BulkDeleteRequest))
{
var items = (await bulk.ReadAsync(ProtocolJson.Default.BulkResultDto)).Items;
Assert.Count(1, items);
Assert.Equal(("skipped", "archive_offline"), (items[0].Outcome, items[0].Reason));
}
}
finally
{
File.Move(manifest + ".away", manifest);
}
Assert.Empty((await server.Database.Jobs.ListAsync(JobState.Queued)).Items.Where(j => j.Kind == JobKind.EmptyTrash));
using (var back = await admin.GetAsync("/api/v1/archive/trash"))
Assert.SequenceEqual([name], (await back.ReadAsync(ProtocolJson.Default.TrashListDto)).Entries.Select(e => e.Name));
Assert.NotNull(await server.Database.Sequences.GetAsync(id));
}
[Test]
public async Task OnlyTheirOwnersAndAdminsChangeSequencesInBulk()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (viewer, _, _) = await server.UserAsync("vera", "viewer");
var admin = await server.AdminAsync();
Guid a = default;
for (var i = 0; i < 2; i++) a = (await Uploads.UploadAsync(editor, Photo(120 + i), $"IMG_{i + 1:0000}.JPG", sessionKey: "a")).SequenceId;
var b = (await Uploads.UploadAsync(editor, Photo(130), "b.jpg", sessionKey: "b")).SequenceId;
await UntilIdleAsync(server);
using (var delete = await viewer.PostAsJsonAsync("/api/v1/sequences/bulk/delete", new BulkDeleteRequest([b], true), ProtocolJson.Default.BulkDeleteRequest))
await delete.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var retag = await viewer.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([b], ["x"], null), ProtocolJson.Default.BulkRetagRequest))
await retag.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var jobs = await viewer.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([b], "thumbnails"), ProtocolJson.Default.BulkJobsRequest))
await jobs.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var photos = await viewer.PostAsJsonAsync($"/api/v1/sequences/{a}/frames/delete",
new FrameDeleteRequest([(await server.Database.Frames.ListBySequenceAsync(a))[0].Id], null, true), ProtocolJson.Default.FrameDeleteRequest))
await photos.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
// An admin deletes photos and sequences of any user.
var frame = (await server.Database.Frames.ListBySequenceAsync(a))[0].Id;
using (var photo = await admin.PostAsJsonAsync($"/api/v1/sequences/{a}/frames/delete", new FrameDeleteRequest([frame], null, false),
ProtocolJson.Default.FrameDeleteRequest))
Assert.NotNull((await photo.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
await UntilIdleAsync(server);
using (var bulk = await admin.PostAsJsonAsync("/api/v1/sequences/bulk/delete", new BulkDeleteRequest([b], false), ProtocolJson.Default.BulkDeleteRequest))
Assert.SequenceEqual(["ok"], (await bulk.ReadAsync(ProtocolJson.Default.BulkResultDto)).Items.Select(i => i.Outcome));
Assert.Null(await server.Database.Sequences.GetAsync(b));
Assert.Count(1, await server.Database.Frames.ListBySequenceAsync(a));
}
[Test]
public async Task BulkOperationsAnswerForEachSequence()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (other, _, _) = await server.UserAsync("giulia", "editor");
var a = (await Uploads.UploadAsync(editor, Photo(30), "a.jpg", sessionKey: "a")).SequenceId;
var b = (await Uploads.UploadAsync(editor, Photo(31), "b.jpg", sessionKey: "b")).SequenceId;
var c = (await Uploads.UploadAsync(other, Photo(32), "c.jpg", sessionKey: "c")).SequenceId;
var unknown = Guid.CreateVersion7();
await UntilIdleAsync(server);
using (var retag = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([a, b, unknown], ["Night", "roof"], null),
ProtocolJson.Default.BulkRetagRequest))
{
var result = await retag.ReadAsync(ProtocolJson.Default.BulkResultDto);
Assert.Equal((2, 1), (result.Ok, result.Skipped));
Assert.Equal("not_found", result.Items.Single(i => i.Id == unknown).Reason);
}
using (var untag = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([a], ["sky"], ["NIGHT"]),
ProtocolJson.Default.BulkRetagRequest))
await untag.ExpectAsync(HttpStatusCode.OK);
Assert.SequenceEqual(["roof", "sky"], (await server.Database.Sequences.GetAsync(a))!.Tags.Order());
Assert.SequenceEqual(["Night", "roof"], (await server.Database.Sequences.GetAsync(b))!.Tags.Order());
using (var noTags = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([a], null, null), ProtocolJson.Default.BulkRetagRequest))
await noTags.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
// A verify of sequences targets their archive (it once targeted the sequences, which its handler cannot read).
using (var verify = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([a, b, unknown], "verify"),
ProtocolJson.Default.BulkJobsRequest))
{
await verify.ExpectAsync(HttpStatusCode.Accepted);
var result = await verify.ReadAsync(ProtocolJson.Default.BulkResultDto);
var job = Assert.NotNull(result.Job);
Assert.Equal(("verify", 2, 1), (job.Kind, result.Ok, result.Skipped));
Assert.SequenceEqual([archive.Id], job.TargetIds);
await UntilJobAsync(editor, job.Id, "done");
}
using (var single = await editor.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("verify", [a], null), ProtocolJson.Default.CreateJobRequest))
{
var job = await single.ReadAsync(ProtocolJson.Default.JobDto);
Assert.SequenceEqual([archive.Id], job.TargetIds);
await UntilJobAsync(editor, job.Id, "done");
}
using (var thumbs = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([a, b], "thumbnails"), ProtocolJson.Default.BulkJobsRequest))
{
var job = Assert.NotNull((await thumbs.ReadAsync(ProtocolJson.Default.BulkResultDto)).Job);
Assert.Equal("thumbs", job.Kind);
Assert.SequenceEqual([a, b], job.TargetIds);
}
using (var bogus = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([a], "render"), ProtocolJson.Default.BulkJobsRequest))
await bogus.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_job_kind");
await UntilIdleAsync(server);
using (var dry = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/delete", new BulkDeleteRequest([a, c, unknown], true), ProtocolJson.Default.BulkDeleteRequest))
{
var result = await dry.ReadAsync(ProtocolJson.Default.BulkResultDto);
Assert.True(result.DryRun);
Assert.Equal(".chronos/trash/" + a.ToString("N"), result.Items[0].TrashFolder);
Assert.SequenceEqual(["ok", "skipped", "skipped"], result.Items.Select(i => i.Outcome));
Assert.SequenceEqual<string?>([null, "forbidden", "not_found"], result.Items.Select(i => i.Reason));
Assert.Equal(1, result.Photos);
}
Assert.NotNull(await server.Database.Sequences.GetAsync(a));
using (var deleted = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/delete", new BulkDeleteRequest([a, b], false), ProtocolJson.Default.BulkDeleteRequest))
Assert.Equal(2, (await deleted.ReadAsync(ProtocolJson.Default.BulkResultDto)).Ok);
Assert.Null(await server.Database.Sequences.GetAsync(a));
Assert.Null(await server.Database.Sequences.GetAsync(b));
Assert.NotNull(await server.Database.Sequences.GetAsync(c));
}
[Test]
public async Task ASequenceThumbnailIsItsHeroFramesOrItsFirst()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Photo(40), "IMG_0001.JPG", sessionKey: "t");
var second = await Uploads.UploadAsync(editor, Photo(41), "IMG_0002.JPG", sessionKey: "t");
var id = first.SequenceId;
var thumbs = new Dictionary<Guid, byte[]>();
foreach (var frame in new[] { first.FrameId, second.FrameId }) thumbs[frame] = await ThumbnailAsync(editor, $"/api/v1/frames/{frame}/thumb");
using (var cover = await editor.GetAsync($"/api/v1/sequences/{id}/thumb"))
{
await cover.ExpectAsync(HttpStatusCode.OK);
var bytes = await cover.Content.ReadAsByteArrayAsync();
Assert.BytesEqual(thumbs[first.FrameId], bytes);
var etag = Assert.NotNull(cover.Headers.ETag);
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/sequences/{id}/thumb");
request.Headers.IfNoneMatch.Add(etag);
using var cached = await editor.SendAsync(request);
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
}
using (var hero = await editor.PatchAsJsonAsync($"/api/v1/sequences/{id}", new UpdateSequenceRequest(null, null, null, null, null, null, second.FrameId),
ProtocolJson.Default.UpdateSequenceRequest))
await hero.ExpectAsync(HttpStatusCode.OK);
var heroThumb = await ThumbnailAsync(editor, $"/api/v1/sequences/{id}/thumb");
Assert.BytesEqual(thumbs[second.FrameId], heroThumb);
using var created = await editor.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest("Empty", null), ProtocolJson.Default.CreateSequenceRequest);
var empty = await created.ReadAsync(ProtocolJson.Default.SequenceDto);
using (var none = await editor.GetAsync($"/api/v1/sequences/{empty.Id}/thumb")) await none.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var unknown = await editor.GetAsync($"/api/v1/sequences/{Guid.CreateVersion7()}/thumb")) await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
[Test]
public async Task TheLibraryFiltersOfferTheArchivesYearsCamerasAndTags()
{
// The panel's Year, Camera and Tag menus list what the archive has, each with its count, in the values the listing takes.
await using var server = await TestServer.StartAsync(context);
var archive = server.Services.GetRequiredService<ServerArchive>();
var (viewer, _, _) = await server.UserAsync("vera", "viewer");
Sequence Seq(DateTime? first, string? make, string? model, params string[] tags) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = archive.Id,
Folder = $"2026/{Guid.NewGuid():N}",
CameraMake = make,
CameraModel = model,
FirstCapture = first,
LastCapture = first?.AddHours(1),
Tags = tags,
UpdatedAt = DateTimeOffset.UtcNow,
};
var sony = Seq(new DateTime(2025, 3, 4), "SONY", "ILCE-7M4") with { RenderedCount = 2 };
foreach (var s in new[]
{
Seq(new DateTime(2024, 5, 1), "Canon", "Canon EOS R5", "Night", "roof"), Seq(new DateTime(2025, 1, 2), "Canon", "Canon EOS R5", "night"), sony,
Seq(new DateTime(2023, 8, 9), "NIKON CORPORATION", "NIKON Z 8"), Seq(null, null, null),
})
await server.Database.Sequences.UpsertAsync(s);
LibraryFacetsDto facets;
using (var response = await viewer.GetAsync("/api/v1/sequences/facets")) facets = await response.ReadAsync(ProtocolJson.Default.LibraryFacetsDto);
Assert.SequenceEqual([new FacetDto("2025", 2), new FacetDto("2024", 1), new FacetDto("2023", 1)], facets.Years);
// Labelled as the desktop names cameras: the brand once.
Assert.SequenceEqual([new FacetDto("Canon EOS R5", 2, "Canon EOS R5"), new FacetDto("ILCE-7M4", 1, "SONY ILCE-7M4"), new FacetDto("NIKON Z 8", 1, "Nikon Z 8")],
facets.Cameras);
Assert.SequenceEqual([new FacetDto("Night", 2), new FacetDto("roof", 1)], facets.Tags);
async Task<int> CountAsync(string query)
{
using var page = await viewer.GetAsync($"/api/v1/sequences?{query}");
return (await page.ReadAsync(ProtocolJson.Default.PageSequenceDto)).Items.Count;
}
Assert.Equal(2, await CountAsync("year=2025"));
Assert.Equal(1, await CountAsync("camera=ILCE-7M4"));
Assert.Equal(2, await CountAsync("tag=night"));
// The Status menu's Rendered and Not rendered.
Assert.Equal(1, await CountAsync("rendered=true"));
Assert.Equal(4, await CountAsync("rendered=false"));
using var unknown = await viewer.GetAsync("/api/v1/sequences/facets/x");
Assert.Equal(HttpStatusCode.NotFound, unknown.StatusCode);
}
/// <summary>Deletes one photo of a sequence into the trash; returns the entry's name.</summary>
private static async Task<string> DeletePhotoAsync(HttpClient client, Guid sequenceId, Guid frameId)
{
using var response = await client.PostAsJsonAsync($"/api/v1/sequences/{sequenceId}/frames/delete", new FrameDeleteRequest([frameId], null, false),
ProtocolJson.Default.FrameDeleteRequest);
return Assert.NotNull((await response.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
}
/// <summary>The folder of a photo entry in the archive's trash.</summary>
private static string PhotoEntryFolder(TestServer server, string name) =>
Path.Combine(server.Options.TrashPath, Chronos.Data.Archiving.FrameTrash.FolderName, name[Chronos.Data.Archiving.FrameTrash.EntryPrefix.Length..]);
/// <summary>A thumbnail once its pass has drawn it (404 until then).</summary>
private static async Task<byte[]> ThumbnailAsync(HttpClient client, string url)
{
var until = DateTime.UtcNow + Wait;
while (true)
{
using var response = await client.GetAsync(url);
if (response.StatusCode == HttpStatusCode.OK) return await response.Content.ReadAsByteArrayAsync();
Assert.True(DateTime.UtcNow < until, $"{url}: {(int)response.StatusCode}");
await Task.Delay(50);
}
}
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 });
}
}
@@ -1,5 +1,7 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Hosting.Server;
@@ -12,7 +14,7 @@ using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
[Category("server")]
public sealed class SystemEndpointTests(TestContext context)
public sealed partial class SystemEndpointTests(TestContext context)
{
[Test]
public async Task HealthReportsOk()
@@ -93,6 +95,44 @@ public sealed class SystemEndpointTests(TestContext context)
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
}
[Test]
public async Task AdminPanelFilesAreRevalidatedSoAnUpgradeNeverMixesOldAndNewModules()
{
// A browser that kept app.js from before an upgrade must not run it next to a new ui.js: every file is kept but
// asked for again before each use, and its ETag follows its content, so only what the upgrade changed is sent.
await using var server = await TestServer.StartAsync(context);
foreach (var path in new[] { "/admin/", "/admin/app.js", "/admin/ui.js", "/admin/admin.css", "/admin/icons.js", "/admin/pages/library.js", "/admin/upload.js" })
{
using var response = await server.Client.GetAsync(path);
Assert.Equal(HttpStatusCode.OK, response.StatusCode, path);
var cache = Assert.NotNull(response.Headers.CacheControl);
Assert.True(cache.NoCache && cache.MaxAge is null && !cache.Public, $"{path}: {cache}");
var etag = Assert.NotNull(response.Headers.ETag);
Assert.False(etag.IsWeak, path);
var bytes = await response.Content.ReadAsByteArrayAsync();
Assert.Equal($"\"{Convert.ToHexString(SHA256.HashData(bytes).AsSpan(0, 12))}\"", etag.Tag, path);
foreach (var sent in new[] { etag, new EntityTagHeaderValue(etag.Tag, isWeak: true), EntityTagHeaderValue.Any })
{
using var again = new HttpRequestMessage(HttpMethod.Get, path);
again.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"0123\""));
again.Headers.IfNoneMatch.Add(sent);
using var notModified = await server.Client.SendAsync(again);
Assert.Equal(HttpStatusCode.NotModified, notModified.StatusCode, $"{path} with {sent}");
Assert.Equal(etag, notModified.Headers.ETag, path);
Assert.True(Assert.NotNull(notModified.Headers.CacheControl).NoCache, path);
}
// A file the browser holds from another build has another ETag: the new content comes back.
using var stale = new HttpRequestMessage(HttpMethod.Get, path);
stale.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"0123456789ABCDEF01234567\""));
using var fresh = await server.Client.SendAsync(stale);
Assert.Equal(HttpStatusCode.OK, fresh.StatusCode, path);
var resent = await fresh.Content.ReadAsByteArrayAsync();
Assert.BytesEqual(bytes, resent, path);
}
}
[Test]
public async Task PlainHttpFromAnotherMachineGoesToThePublicHttpsPort()
{
@@ -141,21 +181,416 @@ public sealed class SystemEndpointTests(TestContext context)
var index = await server.Client.GetStringAsync("/admin/");
// The page container is not a live region: only toasts and form errors announce themselves.
Assert.True(!index.Contains("aria-live", StringComparison.Ordinal), index);
var seen = await ModulesAsync(server);
Assert.True(seen.Count >= 20, string.Join(", ", seen.Keys));
// The Library's views (owner review 2, R6) are modules of their own under pages/library; the web upload (R3) is the
// dialog, its hash worker and the in-house SHA-256 the worker imports.
foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js", "upload.js", "hash-worker.js", "sha256.js" })
Assert.True(seen.ContainsKey(module), module);
}
[Test]
public async Task AdminPanelListsTheLibraryAndImportsTheWebUploadOnlyDynamically()
{
// Owner review 2, R6: the Library comes right after the Dashboard. The web upload (R3) is a module of its own that
// only the Library list and a sequence import, and only dynamically (never statically): the other pages never load
// it, and the Library still works, without Upload and Add photos, when the module does not load.
await using var server = await TestServer.StartAsync(context);
var app = await server.Client.GetStringAsync("/admin/app.js");
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("app.js"));
var seen = new HashSet<string>(StringComparer.Ordinal);
var top = MenuPages(app)[0];
Assert.SequenceEqual(["dashboard", "library"], top.Take(2));
var icons = await server.Client.GetStringAsync("/admin/icons.js");
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
foreach (var page in MenuPages(app).SelectMany(group => group))
{
Assert.Contains($" {page}: `<svg", icons);
var name = $"Admin.Nav.{char.ToUpperInvariant(page[0])}{page[1..]}";
Assert.True(strings.ContainsKey(name) && strings.ContainsKey(name + ".Tip"), name);
}
var modules = await ModulesAsync(server);
Assert.Contains(@"import(""../upload.js"")", modules["pages/library.js"]);
foreach (var (module, source) in modules)
{
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in StaticImport().Matches(source))
Assert.True(Resolve(folder, import.Groups[1].Value) != "upload.js", $"{module} imports upload.js statically");
}
// The module the dynamic import names is there (no 404 in the browser) and exports what the Library calls.
Assert.Equal("upload.js", Resolve("pages/", "../upload.js"));
Assert.True(Regex.IsMatch(modules["upload.js"], @"export (?:async )?function openUpload\(\{ api, sequence, onDone \}"), "upload.js exports openUpload({ api, sequence, onDone })");
Assert.Contains("openUpload({ api, onDone: ", modules["pages/library.js"]);
Assert.Contains("openUpload({ api, sequence: seq, onDone: ", modules["pages/library/sequence.js"]);
}
[Test]
public async Task TheTrashPageSeesAnEmptyingThatEndedBeforeItsPostAnswered()
{
// The worker claims an emptying as soon as it is queued and can end it before the browser has read the 202: the page
// keeps the last state of the jobs that ended and looks its own job up there before it starts following it.
await using var server = await TestServer.StartAsync(context);
var trash = await server.Client.GetStringAsync("/admin/pages/library/trash.js");
Assert.Contains("ended.set(e.jobId, e)", trash);
var lookedUp = trash.IndexOf("ended.get(job.id)", StringComparison.Ordinal);
var followed = trash.IndexOf("emptyJob = job.id", StringComparison.Ordinal);
Assert.True(lookedUp > 0 && followed > lookedUp, "the queued job is looked up among the ended ones before it is followed");
// An emptying started elsewhere sends no sequenceChanged: any job that ends shows the trash again, and a restore
// of an entry that is gone (404) does too.
Assert.True(Regex.IsMatch(trash, @"e\.type === ""jobState"" && JOB_ENDED\.has\(e\.state\)"), "every ended job is seen");
Assert.True(Regex.IsMatch(trash, @"if \(err\.status === 404\) await load\(\);"), "a restore of a gone entry reloads the trash");
}
[Test]
public async Task ASequencePageRefreshesAfterJobsAndAsksAgainForMissingThumbnails()
{
// Thumbnail, proxy, verify and analysis jobs send no sequenceChanged: when any job ends, the sequence page reads the
// sequence again (facts, status chips) and asks again, past the browser's first answer, for the images that failed.
await using var server = await TestServer.StartAsync(context);
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
var shared = await server.Client.GetStringAsync("/admin/pages/library/shared.js");
Assert.True(Regex.IsMatch(sequence, @"e\.type === ""jobState""\) \{\s+(//[^\n]*\s+)*if \(JOB_ENDED\.has\(e\.state\) && jobTimer === null\) jobTimer = setTimeout\(afterJob"),
"an ended job schedules one refresh, not pushed back by the next");
Assert.True(Regex.IsMatch(sequence, @"async function afterJob\(\) \{[^}]*const changed = await reload\(false\);[^}]*retryImages\(root, changed\);", RegexOptions.Singleline),
"the refresh reads the sequence again, then retries the cover and the photos, all of them again once the sequence changed");
Assert.Contains(@"export const JOB_ENDED = new Set([""done"", ""failed"", ""cancelled""]);", shared);
// A thumbnail that never comes (its original is missing) is not asked for after every job for as long as the page
// stays open: each retry waits twice as long as the last, and an image stops after RETRY_TRIES.
Assert.True(Regex.IsMatch(shared, @"export function retryImages\(root, fresh = false\) \{[^}]*root\.querySelectorAll\(""img\.failed""\)[^}]*" +
@"if \(tries >= RETRY_TRIES \|\| \(!fresh && now < Number\(img\.dataset\.retryAt \?\? 0\)\)\) return;[^}]*" +
@"Math\.min\(RETRY_FIRST_MS \* 2 \*\* tries, RETRY_LONGEST_MS\)[^}]*searchParams\.set\(""retry"",", RegexOptions.Singleline),
"a retried image waits longer each time, stops, and gets an address the browser has not tried");
Assert.True(Regex.IsMatch(shared, @"const RETRY_TRIES = \d+;"), "RETRY_TRIES");
// The Library list also counts a cancelled job as ended.
var library = await server.Client.GetStringAsync("/admin/pages/library.js");
Assert.Contains(@"e.type === ""jobState"" && JOB_ENDED.has(e.state)", library);
}
[Test]
public async Task ASequencePageRefreshDrawsOnlyWhatChangedAndKeepsTheFocus()
{
// The refresh after every ended job must not drop a keyboard user on the body: the header is drawn again only when
// the sequence read differs from the one shown, the renders only when their list does, and every redraw of the
// stars, the tags and the renders puts the focus back on the same control.
await using var server = await TestServer.StartAsync(context);
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
Assert.True(Regex.IsMatch(sequence, @"async function reload\(withFrames\) \{[^}]*const changed = JSON\.stringify\(seq\) !== JSON\.stringify\(shown\);\s+if \(changed\) drawHeader\(\);", RegexOptions.Singleline),
"the header is drawn again only when the sequence changed");
foreach (var host in new[] { "tags", "rating" })
{
Assert.True(Regex.IsMatch(sequence, $@"redraw\({host}, \(\) => \{{\s+{host}\.innerHTML = "), $"#{host} is drawn keeping the focus");
Assert.Count(1, Regex.Matches(sequence, $@"\b{host}\.innerHTML = "));
}
Assert.True(Regex.IsMatch(sequence, @"if \(key === rendersShown \|\| !root\.isConnected\) return;\s+rendersShown = key;\s+renders = list;\s+const host = root\.querySelector\(""#renders""\);\s+redraw\(host, \(\) => drawRenders\(host\)\);"),
"the renders are drawn again only when they changed, keeping the focus");
Assert.Count(2, Regex.Matches(sequence, @"\bdrawRenders\("));
// A control without a name (a tag's remove button) is found again by its place, not as the first unnamed one.
var ui = await server.Client.GetStringAsync("/admin/ui.js");
Assert.Contains("const same = place.control ? controls.find((c) => controlKey(c) === place.control) : undefined;", ui);
}
[Test]
public async Task TheTrashPageReadsItsEmptyingAgainAndKeepsARestoreDisabledUntilItAnswers()
{
// The end of an emptying can be lost while the events are not connected: whenever the page reads the trash (and
// after the socket connects again) it reads the job it follows, so Empty never stays disabled.
await using var server = await TestServer.StartAsync(context);
var trash = await server.Client.GetStringAsync("/admin/pages/library/trash.js");
Assert.True(Regex.IsMatch(trash, @"async function load\(\) \{\s+if \(emptyJob !== null\) await checkEmptyJob\(\);"), "load reads the emptying first");
Assert.True(Regex.IsMatch(trash, @"async function checkEmptyJob\(\) \{[^}]*api\.get\(`/api/v1/jobs/\$\{encodeURIComponent\(id\)\}`\);.*?if \(err\.status === 404 && emptyJob === id\) emptyJob = null;.*?" +
@"if \(emptyJob === id && JOB_ENDED\.has\(job\.state\)\) emptyEnded\(job\);", RegexOptions.Singleline), "the job read ends the emptying, and a job gone too");
Assert.True(Regex.IsMatch(trash, @"e\.type === ""reconnected""\) \{\s+(//[^\n]*\s+)*if \(root\.isConnected\) load\(\);"), "a reconnect reads the trash again");
var api = await server.Client.GetStringAsync("/admin/api.js");
Assert.True(Regex.IsMatch(api, @"socket\.onopen = \(\) => \{\s+delay = 1000;\s+if \(opened\) \{\s+try \{\s+onEvent\(\{ type: ""reconnected"" \}\);"), "the socket says when it connected again");
// A redraw while a restore is on its way (a job ended, a sequence changed) keeps its button disabled, so the same
// entry is not sent twice.
Assert.Contains(@"${restoring.has(e.name) ? ""disabled"" : """"}", trash);
Assert.True(Regex.IsMatch(trash, @"if \(!entry \|\| restoring\.has\(entry\.name\)\) return;\s+restoring\.add\(entry\.name\);"), "a restore marks its entry");
Assert.True(Regex.IsMatch(trash, @"catch \(err\) \{\s+restoring\.delete\(entry\.name\);"), "a refused restore frees its button");
Assert.True(Regex.IsMatch(trash, @"await load\(\);\s+restoring\.delete\(entry\.name\);\s+\}"), "a restore frees its entry once the trash is read again");
}
[Test]
public async Task AdminModulesCallTheApiOnlyWhereTheyHaveIt()
{
// upload.js once called api from a top-level helper while api was only openUpload's parameter: every completion
// threw a ReferenceError that string checks never saw. A module that neither declares api (api.js) nor imports it
// (app.js) takes it as a parameter in each top-level function that uses it, and uses it nowhere else.
await using var server = await TestServer.StartAsync(context);
var modules = await ModulesAsync(server);
var checkedUses = 0;
foreach (var (module, source) in modules)
{
var code = JsCode(source);
if (HasApi().IsMatch(code)) continue;
foreach (var (name, parameters, body) in TopLevel(code))
{
if (!ApiName().IsMatch(body)) continue;
checkedUses++;
Assert.True(ApiName().IsMatch(parameters), $"{module}: {name} uses api but does not take it");
}
}
Assert.Greater(checkedUses, 5);
Assert.Contains("complete(api, item.uploadId, restore, signal)", modules["upload.js"]);
// The check sees the mistake it is here for, and is not fooled by strings, comments, templates or regular expressions.
const string broken = """
import { ApiFailure } from "./api.js";
// api.get in a comment
export function openUpload({ api, sequence } = {}) {
return complete(1, /api\//.test("x"));
}
async function complete(id) {
const url = `/api/v1/uploads/${id}/complete${id ? `?api=${"api"}` : ""}`;
return api.post(url);
}
function retry(call) {
return call("api");
}
""";
var flagged = TopLevel(JsCode(broken)).Where(s => ApiName().IsMatch(s.Body) && !ApiName().IsMatch(s.Parameters)).Select(s => s.Name);
Assert.SequenceEqual(["complete"], flagged);
}
/// <summary>
/// A module's code with its comments, string and regular expression literals and the text of its template literals
/// blanked (their expressions kept), each character where it was: what is left are names, keywords and punctuation.
/// </summary>
private static string JsCode(string source)
{
var code = source.ToCharArray();
// The brace depth at which each template expression open ends and its template's text goes on.
var templates = new Stack<int>();
var depth = 0;
var i = 0;
void Blank(int from, int to)
{
for (var k = from; k < Math.Min(to, code.Length); k++)
if (code[k] != '\n') code[k] = ' ';
}
// From the text of a template literal: true at its closing backtick, false at an expression; i past either.
bool TemplateText()
{
var start = i;
while (i < code.Length)
{
if (code[i] == '\\') i += 2;
else if (code[i] == '`')
{
Blank(start, i++);
return true;
}
else if (code[i] == '$' && i + 1 < code.Length && code[i + 1] == '{')
{
Blank(start, i);
i += 2;
return false;
}
else i++;
}
Blank(start, i);
return true;
}
while (i < code.Length)
{
var c = code[i];
var next = i + 1 < code.Length ? code[i + 1] : '\0';
if (c == '/' && next is '/' or '*')
{
var end = next == '/' ? source.IndexOf('\n', i) : source.IndexOf("*/", i + 2, StringComparison.Ordinal);
end = end < 0 ? code.Length : next == '/' ? end : end + 2;
Blank(i, end);
i = end;
}
else if (c is '"' or '\'' || (c == '/' && RegexMayStart(code, i)))
{
var start = i++;
var inClass = false;
while (i < code.Length && code[i] != '\n' && (code[i] != c || inClass))
{
if (code[i] == '\\') i++;
else if (c == '/' && code[i] == '[') inClass = true;
else if (c == '/' && code[i] == ']') inClass = false;
i++;
}
Blank(start + 1, i++);
}
else if (c == '`')
{
i++;
if (!TemplateText()) templates.Push(++depth);
}
else if (c == '}' && templates.Count > 0 && templates.Peek() == depth)
{
templates.Pop();
depth--;
i++;
if (!TemplateText()) templates.Push(++depth);
}
else
{
if (c == '{') depth++;
else if (c == '}') depth--;
i++;
}
}
return new string(code);
}
/// <summary>Whether the slash at <paramref name="at"/> starts a regular expression (after an operator or a keyword), not a division.</summary>
private static bool RegexMayStart(char[] code, int at)
{
var p = at - 1;
while (p >= 0 && char.IsWhiteSpace(code[p])) p--;
if (p < 0 || "(,=:[!&|?{};+-*%<>~^".Contains(code[p], StringComparison.Ordinal)) return true;
if (!(char.IsLetterOrDigit(code[p]) || code[p] is '_' or '$')) return false;
var end = p + 1;
while (p >= 0 && (char.IsLetterOrDigit(code[p]) || code[p] is '_' or '$')) p--;
return new string(code, p + 1, end - p - 1) is "return" or "typeof" or "case" or "in" or "of" or "delete" or "void" or "throw" or "new";
}
/// <summary>
/// The top-level statements of blanked code (each starts at the beginning of a line): a function's name, parameters and
/// body, or another statement's first line, no parameters and its text.
/// </summary>
private static IEnumerable<(string Name, string Parameters, string Body)> TopLevel(string code)
{
var starts = TopLevelStart().Matches(code).Select(m => m.Index).Append(code.Length).ToList();
for (var s = 0; s + 1 < starts.Count; s++)
{
var text = code[starts[s]..starts[s + 1]];
var head = FunctionHead().Match(text);
if (!head.Success)
{
yield return (text.Split('\n')[0].Trim(), string.Empty, text);
continue;
}
var open = head.Index + head.Length - 1;
var close = open;
for (var level = 0; close < text.Length; close++)
{
if (text[close] == '(') level++;
else if (text[close] == ')' && --level == 0) break;
}
yield return (head.Groups[1].Value, text[(open + 1)..close], text[(close + 1)..]);
}
}
[GeneratedRegex(@"^[A-Za-z_$]", RegexOptions.Multiline)]
private static partial Regex TopLevelStart();
[GeneratedRegex(@"^(?:export\s+)?(?:async\s+)?function\s*\*?\s*([\w$]*)\s*\(")]
private static partial Regex FunctionHead();
/// <summary>The name api, not a member (x.api) nor part of a longer name.</summary>
[GeneratedRegex(@"(?<![\w$.])api(?![\w$])")]
private static partial Regex ApiName();
/// <summary>A module that imports api or declares it at its top level.</summary>
[GeneratedRegex(@"^(?:import \{[^}]*(?<![\w$])api(?![\w$])[^}]*\} from|(?:export )?(?:const|let|var) api(?![\w$]))", RegexOptions.Multiline)]
private static partial Regex HasApi();
[Test]
public async Task TheTrashsRestoreTooltipsSayWhatIsChecked()
{
// A photo entry is hashed against its record before it goes back; a sequence entry is moved back as a folder and
// nothing is hashed (SequenceTrash.RestoreAsync), so its tooltip must not promise a check.
await using var server = await TestServer.StartAsync(context);
foreach (var (culture, verify) in new[] { ("en", "Verify"), ("it", "Verifica") })
{
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync($"/api/v1/i18n/{culture}", ProtocolJson.Default.DictionaryStringString));
Assert.Contains("SHA-256", strings["Admin.Trash.RestorePhotos.Tip"]);
var sequence = strings["Admin.Trash.RestoreSequence.Tip"];
Assert.False(sequence.Contains("SHA-256", StringComparison.Ordinal), $"{culture}: {sequence}");
// The check it does not make is named, with the job that makes it.
Assert.Contains(verify, sequence);
}
}
[Test]
public async Task TheLibraryListDropsSelectAllWhenNoUnloadedSequenceStaysSelectedAndCapsItsDeleteList()
{
await using var server = await TestServer.StartAsync(context);
var library = await server.Client.GetStringAsync("/admin/pages/library.js");
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
var shared = await server.Client.GetStringAsync("/admin/pages/library/shared.js");
// Esc and Ctrl+A in the grid change the selection through onChange: once no selected sequence lies beyond the loaded
// rows, "Select all" no longer holds, so its button comes back and a live refresh prunes the selection again.
Assert.True(Regex.IsMatch(library, @"onChange: \(\) => \{.*?if \(matching\) \{.*?\[\.\.\.selection\.ids\]\.every\(\(id\) => loaded\.has\(id\)\)\) matching = null;.*?syncSelection\(\);", RegexOptions.Singleline),
"the grid's onChange drops matching");
Assert.True(Regex.IsMatch(library, @"function clearFilters\(\) \{(?:(?!\n \}).)*selection\.clear\(\);\s+matching = null;", RegexOptions.Singleline),
"clearing the filters clears the selection as setFilter does");
// A delete of thousands of sequences or photos lists at most LISTED names (the dialog's title counts them all); the
// sequences that stay come first, with their reasons.
Assert.True(Regex.IsMatch(shared, @"export const LISTED = 500;"), "LISTED");
Assert.True(Regex.IsMatch(library, @"list: listed\(\[\.\.\.blocked\.map\("), "the sequences' delete list is capped, blocked first");
Assert.Contains("list: listed(names),", sequence);
Assert.False(Regex.IsMatch(library + sequence, @"list: \[\.\.\."), "an uncapped delete list");
}
/// <summary>The admin panel's modules from app.js and the menu's pages along their static imports, with their source.</summary>
private static async Task<Dictionary<string, string>> ModulesAsync(TestServer server)
{
var app = await server.Client.GetStringAsync("/admin/app.js");
// The upload dialog is a module the Library imports dynamically (owner review 2, R3); its hash worker is named by a URL.
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("upload.js").Prepend("app.js"));
var seen = new Dictionary<string, string>(StringComparer.Ordinal);
while (pending.TryDequeue(out var module))
{
if (!seen.Add(module)) continue;
if (seen.ContainsKey(module)) continue;
using var response = await server.Client.GetAsync("/admin/" + module);
Assert.Equal(HttpStatusCode.OK, response.StatusCode, module);
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType, module);
var source = await response.Content.ReadAsStringAsync();
seen[module] = source;
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in Regex.Matches(await response.Content.ReadAsStringAsync(), @"from ""(\.{1,2}/[^""]+)"""))
foreach (Match import in ModuleReference().Matches(source))
pending.Enqueue(Resolve(folder, import.Groups[1].Value));
}
Assert.True(seen.Count >= 13, string.Join(", ", seen));
return seen;
}
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
private static partial Regex StaticImport();
/// <summary>A module's static imports and the module workers it starts (<c>new URL("./…", import.meta.url)</c>).</summary>
[GeneratedRegex(@"(?:from |new URL\()""(\.{1,2}/[^""]+)""")]
private static partial Regex ModuleReference();
[Test]
public async Task TheUploadDialogsHashWorkerRunsUnderThePanelPolicy()
{
await using var server = await TestServer.StartAsync(context);
using var page = await server.Client.GetAsync("/admin/");
// CSP 3: a worker is allowed by worker-src, else child-src, else script-src, else default-src.
var policy = Directives(page);
var workers = new[] { "worker-src", "child-src", "script-src", "default-src" }.Select(d => policy.GetValueOrDefault(d)).First(v => v is not null);
Assert.SequenceEqual(["'self'"], Assert.NotNull(workers));
using var worker = await server.Client.GetAsync("/admin/hash-worker.js");
Assert.Equal(HttpStatusCode.OK, worker.StatusCode);
Assert.Equal("text/javascript", worker.Content.Headers.ContentType?.MediaType);
Assert.Equal("nosniff", worker.Headers.GetValues("X-Content-Type-Options").First());
// The worker runs under its own response's policy, which lets it import the hash from the same origin.
Assert.SequenceEqual(["'self'"], Assert.NotNull(Directives(worker).GetValueOrDefault("script-src")));
Assert.Contains(@"from ""./sha256.js""", await worker.Content.ReadAsStringAsync());
var upload = await server.Client.GetStringAsync("/admin/upload.js");
Assert.Contains(@"new Worker(new URL(""./hash-worker.js"", import.meta.url), { type: ""module"" })", upload);
Assert.Contains("api.putBytes(", upload);
// No folder picking on the web: importing a whole folder is a desktop feature (owner review 2, R9).
foreach (var picker in new[] { "webkitdirectory", "showDirectoryPicker", "mozdirectory" })
Assert.True(!upload.Contains(picker, StringComparison.OrdinalIgnoreCase), picker);
// The panel has no inline handlers for the policy to block (and none to allow).
Assert.True(!Regex.IsMatch(upload, @"\son[a-z]+="""), "inline handler");
}
/// <summary>The directives of a response's Content-Security-Policy, each with its sources.</summary>
private static Dictionary<string, string[]> Directives(HttpResponseMessage response) =>
string.Join(';', response.Headers.GetValues("Content-Security-Policy"))
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(d => d.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(d => d[0], d => d[1..], StringComparer.OrdinalIgnoreCase);
[Test]
public async Task AdminPanelDocksSettingsAtTheFootAndFoldsAboutIntoIt()
{
@@ -1,4 +1,5 @@
using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
@@ -208,6 +209,36 @@ public sealed class ArchiveModuleTests(TestContext context)
Assert.True(Assert.NotNull(await server.Database.Sequences.GetAsync(roof.Id)).Status.HasFlag(SequenceStatus.ThumbsBuilt), "built");
}
[Test]
public async Task AThumbnailOfAnotherPhotoAtAFramesIndexIsNotServedEvenBeforeAVerify()
{
await using var server = await TestServer.StartAsync(context, options =>
{
Directory.CreateDirectory(Path.Combine(options.ArchivePath, "roof"));
File.WriteAllBytes(Path.Combine(options.ArchivePath, "roof", "IMG_0001.JPG"), Photo());
File.WriteAllBytes(Path.Combine(options.ArchivePath, "roof", "IMG_0002.JPG"), Photo(seed: 3));
}, ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
await UntilIndexedAsync(server, archive.Id, "roof");
await UntilScannedAsync(server);
await UntilImagesAsync(server, editor, archive.Id, "roof");
await UntilIdleAsync(server);
var roof = (await server.Database.Sequences.ListLocationsAsync(archive.Id)).Single(l => l.Folder == "roof");
var frames = await server.Database.Frames.ListBySequenceAsync(roof.Id);
Assert.True(frames.All(f => f.Sha256 is null), "adopted, not verified");
// The pack holds each photo's thumbnail at the other's index (a renumbering it did not follow).
using (var pack = ThumbPackWriter.Open(new ArchivePaths(server.Options.ArchivePath).Sequence("roof").ThumbsPackPath))
pack.Rekey(new Dictionary<int, int> { [0] = 1, [1] = 0 });
foreach (var frame in frames)
{
using var thumb = await editor.GetAsync($"/api/v1/frames/{frame.Id}/thumb");
Assert.Equal(HttpStatusCode.NotFound, thumb.StatusCode);
}
}
[Test]
public async Task SettingsADesktopChangedInArchiveJsonReachUploadsAndTheAdminPanel()
{
@@ -389,6 +420,59 @@ public sealed class ArchiveModuleTests(TestContext context)
Assert.Equal(photo.Length, (await me.ReadAsync(ProtocolJson.Default.UserDto)).UsedBytes);
}
[Test]
public async Task TheProtocolClientTakesAPhotoDeletedWhileOnItsWayAsNotSent()
{
// Owner review 2, R6: a repair upload whose photo the Library deletes meanwhile is refused at its completion
// (photo_removed, nothing filed); the protocol client reports it like a photo deleted before: null, not a failure.
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var path = Path.Combine(context.CreateTempDirectory("source"), "IMG_0001.JPG");
var photo = Photo(5);
await File.WriteAllBytesAsync(path, photo);
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "Chronos Uploader (tests)") { Token = token };
var sequence = await client.CreateSequenceAsync(new CreateSequenceRequest("Roof", null), context.Cancellation);
// A sequence keeps one photo at least: the other is the one deleted.
var keeper = Path.Combine(Path.GetDirectoryName(path)!, "IMG_0000.JPG");
await File.WriteAllBytesAsync(keeper, Photo(6));
var kept = Assert.NotNull(await client.UploadFileAsync(keeper, sequence.Id, null, ct: context.Cancellation));
var first = Assert.NotNull(await client.UploadFileAsync(path, sequence.Id, null, ct: context.Cancellation));
await UntilIdleAsync(server);
File.Delete(Path.Combine(server.Options.ArchivePath, Assert.NotNull(await server.Database.Frames.GetAsync(first.FrameId)).RelativePath));
using var deleting = new BeforeCompletion(async () =>
{
await UntilIdleAsync(server);
var current = Assert.NotNull(await server.Database.Sequences.GetAsync(sequence.Id));
using var delete = await admin.PostAsJsonAsync($"/api/v1/sequences/{sequence.Id}/frames/delete",
new FrameDeleteRequest([first.FrameId], current.FramesVersion, false), ProtocolJson.Default.FrameDeleteRequest);
await delete.ExpectAsync(HttpStatusCode.OK);
});
using var racing = new ChronosClient(server.HttpBase, new CertificatePinning([]), "Chronos Uploader (tests)", deleting) { Token = token };
Assert.Null(await racing.UploadFileAsync(path, sequence.Id, null, ct: context.Cancellation));
Assert.True(deleting.Ran, "the completion was reached");
Assert.SequenceEqual([kept.FrameId], (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
Assert.True(await server.Database.FrameRemovals.IsRemovedAsync(sequence.Id, Convert.ToHexStringLower(SHA256.HashData(photo))), "the tombstone stays");
}
/// <summary>Runs a step on the server before the first upload completion goes through, then sends it on.</summary>
private sealed class BeforeCompletion(Func<Task> step) : DelegatingHandler(new SocketsHttpHandler())
{
public bool Ran { get; private set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!Ran && request.Method == HttpMethod.Post && request.RequestUri?.AbsolutePath.EndsWith("/complete", StringComparison.Ordinal) == true)
{
Ran = true;
await step();
}
return await base.SendAsync(request, cancellationToken);
}
}
[Test]
public async Task AnIntactCopyElsewhereDoesNotStandForTheDamagedOneOfTheTargetSequence()
{
@@ -0,0 +1,500 @@
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Storage;
/// <summary>
/// The admin panel's upload dialog (owner review 2, R3; <c>Admin/web/upload.js</c>) speaks the upload API through the
/// cookie session: requests shaped like <c>api.js</c> sends them (JSON bodies written as the page writes them, the
/// page's language, the CSRF header on every unsafe call, chunks as octet-stream), against the real archive engine.
/// </summary>
[Category("server")]
public sealed class BrowserUploadTests(TestContext context)
{
private const int Chunk = 64 * 1024;
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
[Test]
public async Task TheUploadDialogFilesPhotosThroughTheCookieSession()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, ArchiveModule.Register);
var browser = await Browser.SignInAsync(server);
// What the dialog offers and checks before it hashes anything.
ServerInfo info;
using (var response = await browser.SendAsync(HttpMethod.Get, "/api/v1/server/info"))
info = await response.ReadAsync(ProtocolJson.Default.ServerInfo);
var extensions = Assert.NotNull(info.Extensions);
foreach (var extension in new[] { "jpg", "jpeg", "tif", "dng", "cr3", "nef", "heic" }) Assert.Contains(extension, extensions);
Assert.True(extensions.All(e => e.Length > 0 && e == e.ToLowerInvariant() && !e.StartsWith('.')), string.Join(",", extensions));
// New sequence: the title as typed, no camera hint.
SequenceDto sequence;
using (var created = await browser.SendAsync(HttpMethod.Post, "/api/v1/sequences", Json("""{"title":"Roof","cameraHint":null}""")))
{
await created.ExpectAsync(HttpStatusCode.Created);
sequence = await created.ReadAsync(ProtocolJson.Default.SequenceDto);
}
var photos = new[] { Photo(1), Photo(2) };
var frames = new List<CompleteUploadResponse>();
for (var i = 0; i < photos.Length; i++)
{
var photo = photos[i];
var start = await StartAsync(browser, sequence.Id, $"IMG_{i + 1:0000}.JPG", photo, HttpStatusCode.Created);
var id = Assert.NotNull(start.UploadId);
Assert.Equal(Chunk, start.ChunkSize);
var count = (photo.Length + Chunk - 1) / Chunk;
Assert.True(count >= 2, $"{photo.Length} bytes make one chunk");
// putBytes sends the session's headers: a chunk without the CSRF header is refused like any other change.
using (var refused = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{id}/chunks/0", Bytes(photo, 0), csrf: false))
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "csrf_failed");
// Two chunks in flight, finishing in any order.
for (var last = count - 1; last >= 0; last -= 2)
{
var pair = new[] { last, last - 1 }.Where(n => n >= 0).Select(async n =>
{
using var put = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{id}/chunks/{n}", Bytes(photo, n));
return await put.ReadAsync(ProtocolJson.Default.ChunkReceived);
});
foreach (var received in await Task.WhenAll(pair)) Assert.Contains(received.Index, received.Received);
}
using var complete = await browser.SendAsync(HttpMethod.Post, $"/api/v1/uploads/{id}/complete", Json("{}"));
var frame = await complete.ReadAsync(ProtocolJson.Default.CompleteUploadResponse);
Assert.Equal(sequence.Id, frame.SequenceId);
frames.Add(frame);
}
var stored = await server.Database.Frames.ListBySequenceAsync(sequence.Id);
Assert.SequenceEqual(frames.Select(f => f.FrameId).Order(), stored.Select(f => f.Id).Order());
for (var i = 0; i < photos.Length; i++)
{
var file = Path.Combine(server.Options.ArchivePath, stored.Single(f => f.Id == frames[i].FrameId).RelativePath);
await Http.BytesEqualAsync(photos[i], File.ReadAllBytesAsync(file));
}
// Picked again: already there, with its frame.
var again = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photos[0], HttpStatusCode.OK);
Assert.True(again.AlreadyExists);
Assert.Equal(frames[0].FrameId, again.FrameId);
// Deleted from the sequence: also answered as there, without a frame ("deleted before": restore it from the trash, or
// upload it again).
await DeleteAsync(server, browser, sequence.Id, frames[1].FrameId);
var deleted = await StartAsync(browser, sequence.Id, "IMG_0002.JPG", photos[1], HttpStatusCode.OK);
Assert.True(deleted.AlreadyExists);
Assert.Null(deleted.UploadId);
Assert.Null(deleted.FrameId);
// Cancel: an upload the dialog started is discarded on the server.
var cancelled = Photo(3);
var started = await StartAsync(browser, sequence.Id, "IMG_0003.JPG", cancelled, HttpStatusCode.Created);
var cancelledId = Assert.NotNull(started.UploadId);
using (var put = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{cancelledId}/chunks/0", Bytes(cancelled, 0)))
await put.ExpectAsync(HttpStatusCode.OK);
using (var discard = await browser.SendAsync(HttpMethod.Delete, $"/api/v1/uploads/{cancelledId}"))
await discard.ExpectAsync(HttpStatusCode.NoContent);
using (var state = await browser.SendAsync(HttpMethod.Get, $"/api/v1/uploads/{cancelledId}"))
Assert.Equal("cancelled", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
using (var late = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{cancelledId}/chunks/1", Bytes(cancelled, 1)))
await late.ExpectErrorAsync(HttpStatusCode.Conflict, "upload_state");
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(cancelledId), "the partial file is gone");
}
[Test]
public async Task AQuotaRefusalCarriesTheMessageTheDialogShows()
{
// A quota or space refusal stops the dialog's run with the server's message, in the page's language.
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var browser = await Browser.SignInAsync(server);
Guid me;
using (var response = await browser.SendAsync(HttpMethod.Get, "/api/v1/auth/me")) me = (await response.ReadAsync(ProtocolJson.Default.UserDto)).Id;
using (var quota = await browser.SendAsync(HttpMethod.Patch, $"/api/v1/users/{me}", Json("""{"quotaBytes":1000}""")))
await quota.ExpectAsync(HttpStatusCode.OK);
using var start = await browser.SendAsync(HttpMethod.Post, "/api/v1/uploads", StartBody(null, "IMG_0001.JPG", Uploads.Photo(Chunk + 10, 7)));
var error = await start.ExpectErrorAsync(HttpStatusCode.Forbidden, "quota_exceeded");
Assert.Equal(Loc.Get("Server.Error.QuotaExceeded", CultureInfo.GetCultureInfo("it")), error.Message);
}
[Test]
public async Task UploadAgainBringsBackAPhotoDeletedBeforeEvenAfterTheTrashIsEmptied()
{
// Owner review 2, R6 and R3: a tombstone outlives the trash and keeps sync and old clients from filing the photo
// again, but the user who picks it in the dialog and chooses Upload again gets it back into the sequence.
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, ArchiveModule.Register);
var browser = await Browser.SignInAsync(server);
var sequence = await CreateAsync(browser, "Roof");
var photo = Photo(11);
var sha = Uploads.Sha(photo);
// A sequence keeps one photo at least: the other is the one deleted.
var keeper = await UploadAsync(browser, sequence.Id, "IMG_0000.JPG", Photo(10));
var first = await UploadAsync(browser, sequence.Id, "IMG_0001.JPG", photo);
await DeleteAsync(server, browser, sequence.Id, first.FrameId);
await EmptyTrashAsync(server, browser);
Assert.True(await server.Database.FrameRemovals.IsRemovedAsync(sequence.Id, sha), "the tombstone outlives the trash");
// Picked again: deleted before, nothing started.
var refused = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photo, HttpStatusCode.OK);
Assert.True(refused is { AlreadyExists: true, UploadId: null, FrameId: null }, "answered as deleted before");
// Upload again whose completion does not repeat the restore (an older page): refused at the end, the upload dropped.
var started = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photo, HttpStatusCode.Created, restore: true);
var dropped = Assert.NotNull(started.UploadId);
await SendChunksAsync(browser, dropped, photo);
using (var complete = await CompleteAsync(browser, dropped))
{
var error = await complete.ExpectErrorAsync(HttpStatusCode.Conflict, UploadErrors.PhotoRemoved);
Assert.Equal(Loc.Get("Server.Error.PhotoRemoved", CultureInfo.GetCultureInfo("it")), error.Message);
}
using (var state = await browser.SendAsync(HttpMethod.Get, $"/api/v1/uploads/{dropped}"))
Assert.Equal("cancelled", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(dropped), "the partial file is gone");
Assert.True(await server.Database.FrameRemovals.IsRemovedAsync(sequence.Id, sha), "still deleted");
// Upload again, start and completion: filed into the sequence, and its tombstone is gone.
var back = await UploadAsync(browser, sequence.Id, "IMG_0001.JPG", photo, restore: true);
Assert.Equal(sequence.Id, back.SequenceId);
var frames = await server.Database.Frames.ListBySequenceAsync(sequence.Id);
Assert.SequenceEqual([keeper.FrameId, back.FrameId], frames.Select(f => f.Id).Order());
Assert.Equal(sha, frames.Single(f => f.Id == back.FrameId).Sha256);
Assert.False(await server.Database.FrameRemovals.IsRemovedAsync(sequence.Id, sha), "the tombstone went with the upload");
var again = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photo, HttpStatusCode.OK);
Assert.Equal(back.FrameId, again.FrameId);
}
[Test]
public async Task UploadAgainFilesThePhotoIntoItsSequenceWhateverOtherSequencesHold()
{
// A copy in another sequence stands for an ordinary upload; one brought back on purpose goes where the user put it.
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, ArchiveModule.Register);
var browser = await Browser.SignInAsync(server);
var roof = await CreateAsync(browser, "Roof");
var yard = await CreateAsync(browser, "Yard");
var photo = Photo(12);
await UploadAsync(browser, roof.Id, "IMG_0000.JPG", Photo(10));
var first = await UploadAsync(browser, roof.Id, "IMG_0001.JPG", photo);
await DeleteAsync(server, browser, roof.Id, first.FrameId);
var elsewhere = await UploadAsync(browser, yard.Id, "IMG_0001.JPG", photo);
var deleted = await StartAsync(browser, roof.Id, "IMG_0001.JPG", photo, HttpStatusCode.OK);
Assert.Null(deleted.FrameId);
var back = await UploadAsync(browser, roof.Id, "IMG_0001.JPG", photo, restore: true);
Assert.Equal(roof.Id, back.SequenceId);
Assert.NotEqual(elsewhere.FrameId, back.FrameId);
Assert.Count(1, await server.Database.Frames.ListBySequenceAsync(yard.Id));
}
[Test]
public async Task AnUploadCompletedAfterItsPhotoWasDeletedDoesNotBringItBack()
{
// Owner review 2, R6: the start checked the tombstones, but the photo can be deleted while its bytes are on the way
// (here a repair of a copy whose original is gone, deleted from the Library meanwhile).
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, ArchiveModule.Register);
var browser = await Browser.SignInAsync(server);
var sequence = await CreateAsync(browser, "Roof");
var photo = Photo(13);
var sha = Uploads.Sha(photo);
var keeper = await UploadAsync(browser, sequence.Id, "IMG_0000.JPG", Photo(10));
var first = await UploadAsync(browser, sequence.Id, "IMG_0001.JPG", photo);
await UntilIdleAsync(server);
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(first.FrameId));
File.Delete(Path.Combine(server.Options.ArchivePath, frame.RelativePath));
var repair = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photo, HttpStatusCode.Created);
var id = Assert.NotNull(repair.UploadId);
await SendChunksAsync(browser, id, photo);
await DeleteAsync(server, browser, sequence.Id, first.FrameId);
using (var complete = await CompleteAsync(browser, id))
await complete.ExpectErrorAsync(HttpStatusCode.Conflict, UploadErrors.PhotoRemoved);
Assert.SequenceEqual([keeper.FrameId], (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
Assert.True(await server.Database.FrameRemovals.IsRemovedAsync(sequence.Id, sha), "the tombstone stays");
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(id), "the partial file is gone");
// Completing again changes nothing: the upload is over.
using (var late = await CompleteAsync(browser, id))
await late.ExpectErrorAsync(HttpStatusCode.Conflict, "upload_state");
Assert.SequenceEqual([keeper.FrameId], (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
}
[Test]
public async Task APhotoDeletedBetweenTheCompletionsCheckAndItsCommitIsNotFiled()
{
// The completion asks the index first; a deletion that lands after that and before the commit is caught by the
// ingest itself, which asks the sidecar's tombstones under the lease the deletion takes.
GatedIngest? gate = null;
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, s =>
{
ArchiveModule.Register(s);
s.AddSingleton<IArchiveIngest>(sp => gate = new GatedIngest(sp.GetRequiredService<ArchiveService>().Ingest));
});
var browser = await Browser.SignInAsync(server);
var sequence = await CreateAsync(browser, "Roof");
var photo = Photo(17);
var sha = Uploads.Sha(photo);
var keeper = await UploadAsync(browser, sequence.Id, "IMG_0000.JPG", Photo(18));
var first = await UploadAsync(browser, sequence.Id, "IMG_0001.JPG", photo);
await UntilIdleAsync(server);
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(first.FrameId));
File.Delete(Path.Combine(server.Options.ArchivePath, frame.RelativePath));
var repair = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photo, HttpStatusCode.Created);
var id = Assert.NotNull(repair.UploadId);
await SendChunksAsync(browser, id, photo);
Assert.NotNull(gate).BeforeCommit = () => DeleteAsync(server, browser, sequence.Id, first.FrameId);
using (var complete = await CompleteAsync(browser, id))
await complete.ExpectErrorAsync(HttpStatusCode.Conflict, UploadErrors.PhotoRemoved);
Assert.SequenceEqual([keeper.FrameId], (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
Assert.True(await server.Database.FrameRemovals.IsRemovedAsync(sequence.Id, sha), "the tombstone stays");
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(id), "the partial file is gone");
Assert.FileMissing(Path.Combine(server.Options.StagingPath, id.ToString("N") + ".jpg"));
using (var late = await CompleteAsync(browser, id))
await late.ExpectErrorAsync(HttpStatusCode.Conflict, "upload_state");
}
[Test]
public async Task AStaleTombstoneBesideAFrameOfTheSameContentRefusesNoRepair()
{
// A tombstone left beside a frame that still holds the content (the other copy of a duplicate, a file put back by
// hand) does not stand for a deletion: the frame's original can still be repaired by uploading it.
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, ArchiveModule.Register);
var browser = await Browser.SignInAsync(server);
var sequence = await CreateAsync(browser, "Roof");
var photo = Photo(14);
var sha = Uploads.Sha(photo);
var first = await UploadAsync(browser, sequence.Id, "IMG_0001.JPG", photo);
await UntilIdleAsync(server);
await server.Database.FrameRemovals.SyncSequenceAsync(sequence.Id, [new FrameRemoval(sequence.Id, sha, null, RemovalReason.Deleted, DateTimeOffset.UtcNow)]);
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(first.FrameId));
var original = Path.Combine(server.Options.ArchivePath, frame.RelativePath);
File.Delete(original);
var repaired = await UploadAsync(browser, sequence.Id, "IMG_0001.JPG", photo);
Assert.Equal(first.FrameId, repaired.FrameId);
await Http.BytesEqualAsync(photo, File.ReadAllBytesAsync(original));
}
[Test]
public async Task TheDialogsCaptureTimeDatesAPhotoThatRecordsNone()
{
// Owner review 2, R3: a photo without Exif (a PNG, a JPEG stripped on export) takes the time the dialog sends, as local
// wall time, not the moment the server staged it; frames sent out of order still end up in capture order.
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, ArchiveModule.Register);
var browser = await Browser.SignInAsync(server);
var sequence = await CreateAsync(browser, "Timelapse");
var later = await UploadAsync(browser, sequence.Id, "frame_0002.jpg", Photo(16), "2025-05-01T06:31:00.000");
var earlier = await UploadAsync(browser, sequence.Id, "frame_0001.jpg", Photo(15), "2025-05-01T06:30:00");
var frames = await server.Database.Frames.ListBySequenceAsync(sequence.Id);
Assert.SequenceEqual([earlier.FrameId, later.FrameId], frames.OrderBy(f => f.Index).Select(f => f.Id));
Assert.Equal(new DateTime(2025, 5, 1, 6, 30, 0), frames.Single(f => f.Id == earlier.FrameId).CapturedAt);
Assert.Equal(new DateTime(2025, 5, 1, 6, 31, 0), frames.Single(f => f.Id == later.FrameId).CapturedAt);
}
[Test]
public async Task HiddenDotFilesAreRefusedLikeTheScannerLeavesThemOut()
{
// The AppleDouble "._" companion a Mac leaves on an exFAT card, and any hidden dot file, is no photo for the scanner:
// the dialog leaves them out, and the server refuses them from any client.
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, ArchiveModule.Register);
var browser = await Browser.SignInAsync(server);
var sequence = await CreateAsync(browser, "Card");
foreach (var name in new[] { "._IMG_0001.JPG", ".IMG_0002.JPG" })
{
using var start = await browser.SendAsync(HttpMethod.Post, "/api/v1/uploads", StartBody(sequence.Id, name, Uploads.Photo(4096, 21)));
await start.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_file_name");
}
var upload = await server.Client.GetStringAsync("/admin/upload.js");
Assert.Contains(@"file.name.startsWith(""."")", upload);
}
[Test]
public async Task TheDialogKeepsItselfOpenAndSettlesWhatAnotherCompletionFiles()
{
// Owner review 2, R3 (upload.js): Esc is stopped at its keydown during a run, since Chromium lets a dialog's cancel be
// prevented only once per user activation, and on the document in the capture phase, since the focus may be on the
// body (a click on the dialog's text), where the dialog never sees the key; a completion refused while another one
// files the upload (409 upload_state) waits for it instead of failing the photo; the same photo picked twice waits
// for its first copy.
await using var server = await TestServer.StartAsync(context);
var upload = await server.Client.GetStringAsync("/admin/upload.js");
Assert.True(Regex.IsMatch(upload, @"const stopEscape = \(e\) => \{\s*if \(e\.key === ""Escape""\) e\.preventDefault\(\);"), "Esc at keydown");
var run = upload[upload.IndexOf("async function run()", StringComparison.Ordinal)..upload.IndexOf("function cancel()", StringComparison.Ordinal)];
Assert.True(Regex.IsMatch(run, @"running = true;(?:(?!finally).)*document\.addEventListener\(""keydown"", stopEscape, true\);", RegexOptions.Singleline),
"a run stops Esc on the document, in the capture phase");
Assert.True(Regex.IsMatch(run, @"finally \{(?:(?!\n \}).)*document\.removeEventListener\(""keydown"", stopEscape, true\);", RegexOptions.Singleline),
"the end of a run lets Esc close the dialog again");
Assert.True(Regex.IsMatch(upload, @"dialog\.addEventListener\(""close"", \(\) => \{(?:(?!\n \}\);).)*document\.removeEventListener\(""keydown"", stopEscape, true\);", RegexOptions.Singleline),
"closing the dialog takes its listener off the document");
Assert.False(upload.Contains(@"dialog.addEventListener(""keydown""", StringComparison.Ordinal), "Esc stopped only on the dialog");
Assert.Contains(@"err.code === ""upload_state""", upload);
Assert.Contains(@"api.get(`/api/v1/uploads/${uploadId}`)", upload);
Assert.Contains("sameContent.get(sha256)", upload);
Assert.Contains(@"?restore=true", upload);
Assert.Contains(@"err.code === ""photo_removed""", upload);
Assert.Contains(@"import { captureTime } from ""./capture-time.js"";", upload);
var capture = await server.Client.GetStringAsync("/admin/capture-time.js");
Assert.Contains("export function exifCaptureTime(bytes)", capture);
}
/// <summary>The bootstrap administrator signed in to the panel (a cookie session over HTTPS), calling as <c>api.js</c> does.</summary>
private sealed class Browser(HttpClient client, string csrfToken)
{
public static async Task<Browser> SignInAsync(TestServer server)
{
await server.AdminAsync();
var cookies = new CookieContainer();
var client = server.NewCookieClient(cookies);
using var login = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true),
ProtocolJson.Default.LoginRequest);
await login.ExpectAsync(HttpStatusCode.OK);
return new Browser(client, Assert.NotNull(cookies.GetCookies(Assert.NotNull(server.HttpsBase))["chronos_csrf"]).Value);
}
/// <summary>JSON accepted, the page's language (Italian here), and the CSRF header on every call but a GET.</summary>
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string url, HttpContent? content = null, bool csrf = true)
{
using var request = new HttpRequestMessage(method, url) { Content = content };
request.Headers.Accept.ParseAdd("application/json");
request.Headers.AcceptLanguage.ParseAdd("it");
if (method != HttpMethod.Get && csrf) request.Headers.Add("X-CSRF-Token", csrfToken);
return await client.SendAsync(request);
}
}
private static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json");
/// <summary>A chunk as <c>putBytes</c> sends a <c>File.slice()</c>: its bytes, octet-stream.</summary>
private static ByteArrayContent Bytes(byte[] data, int index)
{
var content = new ByteArrayContent(Uploads.Chunk(data, Chunk, index).ToArray());
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return content;
}
/// <summary>
/// The start body upload.js writes: the capture time capture-time.js read (local wall time without an offset, or null),
/// no session key, and restore true only after the user chose Upload again on the photo's row.
/// </summary>
private static StringContent StartBody(Guid? sequenceId, string fileName, byte[] data, string? capturedAt = null, bool restore = false) =>
Json($$"""{"sequenceId":{{(sequenceId is { } id ? $"\"{id}\"" : "null")}},"fileName":"{{fileName}}","size":{{data.Length}},"sha256":"{{Uploads.Sha(data)}}","capturedAt":{{(capturedAt is null ? "null" : $"\"{capturedAt}\"")}},"sessionKey":null,"restore":{{(restore ? "true" : "false")}}}""");
private static async Task<StartUploadResponse> StartAsync(Browser browser, Guid sequenceId, string fileName, byte[] data, HttpStatusCode expected,
string? capturedAt = null, bool restore = false)
{
using var response = await browser.SendAsync(HttpMethod.Post, "/api/v1/uploads", StartBody(sequenceId, fileName, data, capturedAt, restore));
await response.ExpectAsync(expected);
return await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
}
/// <summary>A sequence made as the dialog's New sequence makes it.</summary>
private static async Task<SequenceDto> CreateAsync(Browser browser, string title)
{
using var created = await browser.SendAsync(HttpMethod.Post, "/api/v1/sequences", Json($$"""{"title":"{{title}}","cameraHint":null}"""));
await created.ExpectAsync(HttpStatusCode.Created);
return await created.ReadAsync(ProtocolJson.Default.SequenceDto);
}
/// <summary>Every chunk of an upload the dialog started, one after the other.</summary>
private static async Task SendChunksAsync(Browser browser, Guid id, byte[] data)
{
for (var n = 0; n < (data.Length + Chunk - 1) / Chunk; n++)
{
using var put = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{id}/chunks/{n}", Bytes(data, n));
await put.ExpectAsync(HttpStatusCode.OK);
}
}
/// <summary>The dialog's completion: a body of <c>{}</c> (api.post), <c>?restore=true</c> after Upload again.</summary>
private static Task<HttpResponseMessage> CompleteAsync(Browser browser, Guid id, bool restore = false) =>
browser.SendAsync(HttpMethod.Post, $"/api/v1/uploads/{id}/complete{(restore ? "?restore=true" : string.Empty)}", Json("{}"));
/// <summary>Started, sent and completed as the dialog does it; returns the frame.</summary>
private static async Task<CompleteUploadResponse> UploadAsync(Browser browser, Guid sequenceId, string fileName, byte[] data, string? capturedAt = null,
bool restore = false)
{
var start = await StartAsync(browser, sequenceId, fileName, data, HttpStatusCode.Created, capturedAt, restore);
var id = Assert.NotNull(start.UploadId);
await SendChunksAsync(browser, id, data);
using var complete = await CompleteAsync(browser, id, restore);
await complete.ExpectAsync(HttpStatusCode.OK);
return await complete.ReadAsync(ProtocolJson.Default.CompleteUploadResponse);
}
/// <summary>Deletes a photo from its sequence as the Library does, once no job is working on it.</summary>
private static async Task DeleteAsync(TestServer server, Browser browser, Guid sequenceId, Guid frameId)
{
await UntilIdleAsync(server);
var current = Assert.NotNull(await server.Database.Sequences.GetAsync(sequenceId));
using var delete = await browser.SendAsync(HttpMethod.Post, $"/api/v1/sequences/{sequenceId}/frames/delete",
Json($$"""{"frameIds":["{{frameId}}"],"expectedFramesVersion":{{current.FramesVersion}},"dryRun":false}"""));
Assert.NotNull((await delete.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
}
/// <summary>Empties the whole trash as the Trash page does: the dry run, then the job with its fingerprint.</summary>
private static async Task EmptyTrashAsync(TestServer server, Browser browser)
{
TrashEmptyPlanDto plan;
using (var dry = await browser.SendAsync(HttpMethod.Post, "/api/v1/archive/trash/empty", Json("""{"names":null,"dryRun":true,"fingerprint":null}""")))
plan = await dry.ReadAsync(ProtocolJson.Default.TrashEmptyPlanDto);
Assert.True(plan.Entries.Count > 0, "the trash holds the deleted photo");
using (var empty = await browser.SendAsync(HttpMethod.Post, "/api/v1/archive/trash/empty",
Json($$"""{"names":null,"dryRun":false,"fingerprint":"{{plan.Fingerprint}}"}""")))
await empty.ExpectAsync(HttpStatusCode.Accepted);
await UntilIdleAsync(server);
using var listed = await browser.SendAsync(HttpMethod.Get, "/api/v1/archive/trash");
Assert.Empty((await listed.ReadAsync(ProtocolJson.Default.TrashListDto)).Entries);
}
/// <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);
}
}
}
/// <summary>The archive's ingest with a step run once before the next commit (what lands between the completion's checks and it).</summary>
private sealed class GatedIngest(IArchiveIngest inner) : IArchiveIngest
{
public Func<Task>? BeforeCommit { get; set; }
public async Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default)
{
if (BeforeCommit is { } step)
{
BeforeCommit = null;
await step();
}
return await inner.CommitAsync(request, cancellationToken);
}
}
/// <summary>A JPEG of a few chunks: noise does not compress below the chunk size.</summary>
private static byte[] Photo(int seed)
{
const int width = 512, height = 384;
var pixels = new byte[width * height * 3];
new Random(seed).NextBytes(pixels);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 95 });
}
}