fix(sync,upload): keep tombstones honest and let an explicit upload bring a photo back

Sync:
- A server frame that has not been hashed is known by content only once it is
  downloaded: one this PC deleted (or holds as its replacement) is now deleted
  from staging instead of filed again, which also dropped its tombstone.
- An unhashed local original that turns out to be a photo the server deleted
  is not uploaded, and the archive verify then writes the hashes into the
  index, so the row settles instead of offering Upload for good.
- A tombstone leaves a photo out of the comparison only when its side no longer
  holds that content, so a tombstone left beside a held copy does not keep the
  other side's copy missing forever.

Uploads:
- StartUploadRequest.Restore (optional, never sent by sync or older clients)
  lets an explicit user upload file a photo deleted from the sequence again,
  also after the trash was emptied; the completion repeats it with
  ?restore=true and the ingest drops the tombstone.
- The completion checks the tombstone again: a photo deleted while its bytes
  were on the way is not filed (409 photo_removed, upload cancelled); the
  protocol client reports that as not sent.
- A tombstone of content a frame of the target still holds refuses no repair.
- Hidden dot names (AppleDouble "._" files) are refused, as the archive
  scanner leaves them out.

Web upload dialog:
- Upload again on rows marked Deleted before; the tooltip no longer promises
  a trash restore that may be impossible.
- Sends a capture time: the Exif DateTimeOriginal of a JPEG or TIFF-based file
  (minimal in-house reader, capture-time.js), else the file's time, so photos
  without Exif keep their order.
- Esc is stopped at keydown during a run (Chromium allows one prevented cancel
  per activation); hidden dot files are left out; a completion refused while
  another one files the upload waits for it; the same photo picked under two
  names waits for its first copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit d051bcfc351f5a08500ca864a6508576a95492a4)
This commit is contained in:
Alby96 committed 2026-10-27 12:45:33 +01:00
1 parent eb607d47aa
commit 316c182b19
18 files changed
+753 -63

No files matched your search

@@ -97,6 +97,27 @@ public sealed class SyncRulesTests
new FrameRemoval(localId, "bb", "b2", RemovalReason.Replaced, at)]).Select(r => r.Reason));
}
[Test]
public void ATombstoneBesideAPhotoItsSideStillHoldsHidesNothing()
{
var time = new DateTime(2026, 9, 28, 18, 0, 0);
var at = new DateTimeOffset(2026, 10, 27, 10, 0, 0, TimeSpan.Zero);
FramePhoto Photo(string sha, int second = 0) => new(sha, 100 + second, time.AddSeconds(second));
// The server tombstoned "xx" and still holds it (it deleted one of two copies, or the file came back by hand): this
// PC's copy is not missing there, and the server's is not missing here.
var server = new SyncTombstones([], [new RemovedPhotoDto("xx", null, "deleted", at)]);
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa"), Photo("xx", 1)], [Photo("aa"), Photo("XX", 1)], server));
// Also when the server has not hashed its copy: it holds it by size and capture time.
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa"), Photo("xx", 1)], [Photo("aa"), Photo("", 1)], server));
// The same on this side.
var here = new SyncTombstones([new FrameRemoval(Guid.CreateVersion7(), "xx", null, RemovalReason.Deleted, at)], null);
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa"), Photo("xx", 1)], [Photo("aa"), Photo("xx", 1)], here));
// A tombstone of a photo its side no longer holds still leaves the other side's copy out.
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa"), Photo("xx", 1)], [Photo("aa")], server));
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa")], [Photo("aa"), Photo("xx", 1)], here));
Assert.Equal((1, 0), SyncRules.CompareOriginals([Photo("aa"), Photo("xx", 1)], [Photo("aa")], SyncTombstones.None));
}
[Test]
public void FramesEitherSideHasNotHashedAreMatchedBySizeAndCaptureTime()
{
@@ -151,6 +151,90 @@ public sealed class SyncTransferTests(TestContext context)
Assert.SequenceEqual(photos[1..].Select(Sha), kept.Select(k => k.Sha256!));
}
[Test]
public async Task APhotoDeletedHereIsNotFetchedAgainFromAServerThatHasNotHashedIt()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
// A folder the server adopted and never verified (its manifest lists no SHA-256), downloaded here.
var remote = f.Remote.Add("Adopted on the server", photos);
remote.Unhashed = true;
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
var first = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Adopted on the server", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(first.Id, JobState.Done);
var local = Assert.NotNull((await f.EntryAsync("Adopted on the server")).Local);
// This PC deletes a photo the server still lists, unhashed: only its content tells it is the one deleted here.
await UntilIdleAsync(f);
var gone = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Single(fr => fr.Sha256 == Sha(photos[0]));
var sequence = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
var plan = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local.Id, [gone.Id], sequence.FramesVersion, f.Ct);
await f.Archive.Service.FrameTrash.DeleteAsync(plan, null, null, f.Ct);
await f.RefreshAsync();
var again = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Adopted on the server", SyncDownloadMode.Originals, null);
var done = await f.Archive.WaitForAsync(again.Id, JobState.Done);
var kept = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.True(kept.Select(k => k.Sha256).ToHashSet().SetEquals(photos[1..].Select(Sha)), "the photo deleted here stays deleted");
Assert.True(await f.Db.FrameRemovals.IsRemovedAsync(local.Id, Sha(photos[0])), "and keeps its tombstone");
Assert.Contains("deleted on this PC, not downloaded", done.LogTail);
Assert.False(Directory.Exists(Path.Combine(f.Archive.Paths.StagingDirectory, "sync-" + remote.Id.ToString("N"))), "staging cleaned up");
}
[Test]
public async Task AnUnverifiedCopyDoesNotSendBackAPhotoTheServerDeleted()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
// An adopted folder (never verified, so no hashes here) that still holds a photo the server has deleted since.
var folder = Path.Combine(f.Archive.Paths.Root, "Adopted");
Directory.CreateDirectory(folder);
for (var i = 0; i < 4; i++) await File.WriteAllBytesAsync(Path.Combine(folder, $"DSC_{i + 1:0000}.JPG"), photos[i], f.Ct);
await f.Archive.ScanAsync();
var local = Assert.Contains((await f.Db.Sequences.ListAsync(new Chronos.Data.Repositories.SequenceQuery(), f.Ct)).Items, s => s.Folder == "Adopted");
var remote = f.Remote.Add("Adopted", photos[..3]);
remote.Removed.Add(new RemovedPhotoDto(Sha(photos[3]), null, "deleted", DateTimeOffset.UtcNow));
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
// Without its hash the photo cannot be told from one the server lacks: the upload finds out.
Assert.Equal(1, (await f.EntryAsync(local.DisplayTitle)).Link!.MissingRemote);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
var done = await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(3, remote.Frames.Count);
Assert.Contains("deleted on the server, not uploaded", done.LogTail);
// Its hash is in the index now: the comparison leaves it out, so the row settles instead of offering Upload for good.
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).All(fr => fr.Sha256 is not null), "hashed by the verify");
var entry = await f.EntryAsync(local.DisplayTitle);
Assert.Equal((SyncStatus.InSync, 0, 0), (entry.Status, entry.Link!.MissingRemote, entry.Link.MissingLocal));
var calls = remote.Frames.Count;
var next = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
var settled = await f.Archive.WaitForAsync(next.Id, JobState.Done);
Assert.Equal((4L, 4L, calls), (settled.ProgressDone, settled.ProgressTotal, remote.Frames.Count));
}
[Test]
public async Task ATombstoneBesideAPhotoTheServerStillHoldsLeavesTheCopiesInSync()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
// The server holds both photos and a tombstone of the second: it deleted one of two copies of it, or the file came
// back by hand. Neither side lacks anything.
var remote = f.Remote.Add("Comet", photos);
remote.Removed.Add(new RemovedPhotoDto(Sha(photos[1]), null, "deleted", DateTimeOffset.UtcNow));
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var entry = await f.EntryAsync("Comet");
Assert.Equal((0, 0), (entry.Link!.MissingRemote, entry.Link.MissingLocal));
Assert.Equal(SyncStatus.InSync, entry.Status);
}
[Test]
public async Task AResumedUploadSendsOnlyWhatTheServerLacks()
{
@@ -634,6 +718,20 @@ public sealed class SyncTransferTests(TestContext context)
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes));
/// <summary>Waits until no job is waiting or running (the thumbnails and analyses a download queues after it).</summary>
private static async Task UntilIdleAsync(SyncFixture f)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
{
while ((await f.Db.Jobs.ListAsync(state, cancellationToken: f.Ct)).Items.Count > 0)
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50, f.Ct);
}
}
}
/// <summary>The photos (SHA-256) the local copy's project excludes, shows as hero, keys the camera on, and waits for.</summary>
private static async Task<(string[] Excluded, string? Hero, string[] Keyframes, string[] Pending)> NamedAsync(SyncFixture f, Guid localId)
{
@@ -1,4 +1,5 @@
using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
@@ -419,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()
{
@@ -3,6 +3,7 @@ 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;
@@ -89,12 +90,9 @@ public sealed class BrowserUploadTests(TestContext context)
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").
await UntilIdleAsync(server);
var current = Assert.NotNull(await server.Database.Sequences.GetAsync(sequence.Id));
using (var delete = await browser.SendAsync(HttpMethod.Post, $"/api/v1/sequences/{sequence.Id}/frames/delete",
Json($$"""{"frameIds":["{{frames[1].FrameId}}"],"expectedFramesVersion":{{current.FramesVersion}},"dryRun":false}""")))
Assert.NotNull((await delete.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
// 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);
@@ -130,6 +128,181 @@ public sealed class BrowserUploadTests(TestContext context)
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 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; 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, @"addEventListener\(""keydown"", \(e\) => \{\s*if \(running && e\.key === ""Escape""\) e\.preventDefault\(\);"), "Esc at keydown");
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)
{
@@ -165,17 +338,80 @@ public sealed class BrowserUploadTests(TestContext context)
return content;
}
/// <summary>The start body upload.js writes: no capture time (the server reads it from the photo), no session key.</summary>
private static StringContent StartBody(Guid? sequenceId, string fileName, byte[] data) =>
Json($$"""{"sequenceId":{{(sequenceId is { } id ? $"\"{id}\"" : "null")}},"fileName":"{{fileName}}","size":{{data.Length}},"sha256":"{{Uploads.Sha(data)}}","capturedAt":null,"sessionKey":null}""");
/// <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)
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));
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)
{