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

+160
View File
@@ -0,0 +1,160 @@
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Server.Events;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
using Chronos.Server.Storage;
namespace Chronos.Server.Api;
/// <summary>
/// <c>/api/v1/archive/trash</c> (owner review 2, R6; administrators of the archive): the entries of the archive's trash —
/// deleted sequences and photos deleted from sequences —, restoring one, and emptying it: a dry run that measures the
/// entries and fingerprints them, then an <c>empty-trash</c> job that erases exactly those entries and refuses when the
/// trash changed since (BRIEF §0.2 rule 8: the only erase of user files, always an explicit, confirmed action).
/// </summary>
public static partial class TrashEndpoints
{
public static void Map(RouteGroupBuilder api)
{
var trash = api.MapGroup("/archive/trash").Requires(Permissions.ManageArchive);
trash.MapGet("", ListAsync);
trash.MapPost("/{name}/restore", RestoreAsync);
trash.MapPost("/empty", EmptyAsync);
}
/// <summary>Whether <paramref name="name"/> has the shape of an entry name (a sequence id, a time, <c>photos-</c>): never a path.</summary>
public static bool IsEntryName(string? name) => name is not null && EntryName().IsMatch(name);
public static TrashEntryDto Entry(TrashEntry e) =>
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt);
/// <summary>The entries newest first with their total size (a read-only archive lists them too); 503 <c>archive_offline</c>.</summary>
private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, ServerArchive archive, [FromServices] ArchiveService? archives)
{
// An archive that cannot be reached shows no trash folder, which is not an empty trash.
if (Availability(archive) == ArchiveAvailability.Offline) return Offline(context);
var entries = await LibraryEndpoints.Engine(archives, db).Trash.ListAsync(archive.Current, context.RequestAborted);
return Results.Json(new TrashListDto([.. entries.Select(Entry)], entries.Sum(e => e.Bytes)), ProtocolJson.Default.TrashListDto);
}
/// <summary>
/// Brings an entry back: a sequence into its folder and the library, photos into their sequence (a new one when it is
/// gone), each photo re-hashed against its record first. 404 <c>not_found</c> (<c>trash_entry</c>); 409
/// <c>sequence_in_library</c> (that sequence is in the library already), <c>sequence_busy</c>, <c>sidecar_mismatch</c>
/// (the sidecar of the sequence the photos go back into is damaged or another sequence's), <c>folder_in_use</c>; 422
/// <c>trash_mismatch</c> (no file matches its record any more, or a deleted sequence's own sidecar no longer names it);
/// 503 <c>archive_offline</c>. The answer names the photos that stayed in the trash, why each did and one sentence per
/// reason in the request's language (<see cref="TrashRestoreDto"/>). Publishes <c>sequenceChanged</c>: <c>created</c> for
/// a sequence, <c>frames</c> for photos.
/// </summary>
private static async Task<IResult> RestoreAsync(HttpContext context, Caller caller, string name, ChronosDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
{
if (!IsEntryName(name)) return ApiErrors.NotFound(context, "trash_entry");
TrashRestoreResult result;
try
{
result = await LibraryEndpoints.Engine(archives, db).RestoreEntryAsync(archive.Id, name, host.Engine, lifetime.ApplicationStopping);
}
catch (DirectoryNotFoundException)
{
return ApiErrors.NotFound(context, "trash_entry");
}
catch (SequenceInLibraryException)
{
return ApiErrors.Conflict(context, "sequence_in_library");
}
catch (ArchiveOfflineException)
{
return Offline(context);
}
catch (LeaseUnavailableException)
{
return ApiErrors.Conflict(context, "sequence_busy");
}
catch (TrashMismatchException)
{
return Mismatch(context);
}
catch (InvalidDataException) when (!FrameTrash.IsPhotoEntry(name))
{
// A deleted sequence's own sidecar is damaged or names another sequence: the entry is not what its record says.
return Mismatch(context);
}
catch (InvalidDataException)
{
// The sidecar of the sequence the photos go back into is damaged or another sequence's: nothing moved.
return ApiErrors.Conflict(context, "sidecar_mismatch");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return ApiErrors.Conflict(context, "folder_in_use");
}
var sequence = result.Sequence;
await audit.WriteAsync(caller, context, "trash_restored", "sequence", sequence.Id.ToString(), $"{name} · {sequence.DisplayTitle}");
events.Publish(new SequenceChangedEvent(sequence.Id, result.Kind == TrashKind.Sequence || result.NewSequence ? "created" : "frames",
sequence.FramesVersion, sequence.SettingsVersion));
var culture = RequestCulture.Of(context);
return Results.Json(new TrashRestoreDto(name, result.Kind.ToString().ToLowerInvariant(), sequence.Id, result.Kind == TrashKind.Sequence ? sequence.FrameCount : result.Photos,
[.. result.Kept.Select(k => k.Name)], result.NewSequence, [.. result.Kept.Select(k => ReasonCode(k.Reason))],
result.Kept.Count == 0 ? null : string.Join(" ", KeptPhoto.Sentences(result.Kept, culture))), ProtocolJson.Default.TrashRestoreDto);
}
/// <summary>The code of why a photo stayed in the trash (<see cref="TrashRestoreDto.KeptReasons"/>).</summary>
private static string ReasonCode(KeptReason reason) => reason switch
{
KeptReason.Mismatch => "mismatch",
KeptReason.NotMoved => "not_moved",
KeptReason.InSequence => "in_sequence",
_ => "no_file",
};
/// <summary>
/// Empties the trash, or the entries <c>names</c> names. With <c>dryRun</c> the plan: the entries measured on disk, their
/// totals and a fingerprint, nothing touched. Otherwise the request carries that fingerprint, and the server queues an
/// <c>empty-trash</c> job (202) that erases exactly those entries; the job fails, erasing nothing, when the trash changed
/// before it ran. The audit log records the request (<c>trash_empty_requested</c>: the entries planned, their size and
/// the job); what the job erased is in its log. 400 <c>bad_request</c> (<c>names</c>, <c>fingerprint</c>); 409
/// <c>trash_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503 <c>archive_offline</c> (offline,
/// or read-only for the erase itself).
/// </summary>
private static async Task<IResult> EmptyAsync(HttpContext context, Caller caller, TrashEmptyRequest request, ChronosDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit)
{
var ct = context.RequestAborted;
if (request.Names is { } names && (names.Count == 0 || names.Any(n => !IsEntryName(n)))) return ApiErrors.BadRequest(context, "bad_request", "names");
// Offline, the trash cannot be measured (it would plan as empty); read-only, it can be measured but not erased.
var availability = Availability(archive);
if (availability == ArchiveAvailability.Offline || (!request.DryRun && availability != ArchiveAvailability.Online)) return Offline(context);
var plan = await LibraryEndpoints.Engine(archives, db).PlanEmptyTrashAsync(archive.Id, request.Names, ct);
if (request.DryRun)
{
return Results.Json(new TrashEmptyPlanDto([.. plan.Entries.Select(Entry)], plan.Photos, plan.Files, plan.Bytes, plan.Fingerprint, plan.Unknown),
ProtocolJson.Default.TrashEmptyPlanDto);
}
if (string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
if (plan.Fingerprint != request.Fingerprint || plan.Unknown.Count > 0) return ApiErrors.Conflict(context, "trash_changed", plan.Fingerprint);
if (!host.CanRun(JobKind.EmptyTrash)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.EmptyTrash));
var job = await host.Engine.EnqueueAsync(ArchiveJobs.EmptyTrash(archive.Current, plan), caller.Id, ct);
// A request, not an outcome: the job still checks the plan when it runs and erases nothing if the trash changed.
await audit.WriteAsync(caller, context, "trash_empty_requested", "job", job.Id.ToString(),
$"{plan.Entries.Count} · {plan.Bytes} · {string.Join(", ", plan.Entries.Take(5).Select(e => e.Name))}");
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
}
private static ArchiveAvailability Availability(ServerArchive archive) => ArchiveVolume.Probe(new ArchivePaths(archive.Root));
private static IResult Offline(HttpContext context) => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
private static IResult Mismatch(HttpContext context) => ApiErrors.Result(context, StatusCodes.Status422UnprocessableEntity, "trash_mismatch");
[GeneratedRegex("^(photos-)?[0-9a-f]{32}(-[0-9]{14}(-[0-9]{1,6})?)?$", RegexOptions.CultureInvariant)]
private static partial Regex EntryName();
}