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
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:
1 parent
af9eeaab9b
commit
9aa818ed47
283 files changed
+24922
-293
No files matched your search
@@ -0,0 +1,452 @@
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Http.Metadata;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// The library the admin panel manages without editing (owner review 2, R6): a sequence's cover thumbnail, deleting photos
|
||||
/// of a sequence into the archive's trash (<see cref="FrameTrash"/>), and mass operations on many sequences at once —
|
||||
/// delete into the trash, retag, queue analysis, proxies, thumbnails or a verify — each answering per sequence whether it
|
||||
/// was done or skipped, and why.
|
||||
/// </summary>
|
||||
public static class LibraryEndpoints
|
||||
{
|
||||
/// <summary>Sequences one bulk request may name.</summary>
|
||||
public const int MaxBulkIds = 1000;
|
||||
|
||||
/// <summary>Photos one delete request may name.</summary>
|
||||
public const int MaxFrameIds = 100_000;
|
||||
|
||||
/// <summary>
|
||||
/// The body a delete request of <see cref="MaxFrameIds"/> photos may take: 48 bytes an id (36 characters, quotes, a
|
||||
/// comma and some indentation) and 4 KiB for the rest, about 4.8 MB, above the server's 1 MiB for other JSON bodies.
|
||||
/// </summary>
|
||||
public const long FrameDeleteBodyLimit = MaxFrameIds * 48L + 4096;
|
||||
|
||||
private const string Ok = "ok";
|
||||
private const string Skipped = "skipped";
|
||||
private const string Regenerable = "private, max-age=3600";
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var sequences = api.MapGroup("/sequences");
|
||||
sequences.MapGet("/facets", FacetsAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/thumb", ThumbAsync).Requires(Permissions.Read);
|
||||
sequences.MapPost("/{id:guid}/frames/delete", DeleteFramesAsync).Requires(Permissions.Delete).WithMetadata(new FrameDeleteBodyLimitMetadata());
|
||||
sequences.MapPost("/bulk/delete", BulkDeleteAsync).Requires(Permissions.Delete);
|
||||
sequences.MapPost("/bulk/retag", BulkRetagAsync).Requires(Permissions.Edit);
|
||||
sequences.MapPost("/bulk/jobs", BulkJobsAsync).Requires(Permissions.Edit);
|
||||
}
|
||||
|
||||
/// <summary>The archive engine behind these operations: the host's, or one of its own (a test host that replaces the archive module).</summary>
|
||||
internal static ArchiveService Engine(ArchiveService? archives, ChronosDatabase db) =>
|
||||
archives ?? new ArchiveService(db, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, ImagesAfterScan = true });
|
||||
|
||||
/// <summary>
|
||||
/// What the Library's filters offer (the panel's Year, Camera and Tag menus): the years of first capture, the camera
|
||||
/// models and the tags of this archive's sequences, each with its count. A camera's label is the name the desktop
|
||||
/// shows (<see cref="PathTemplate.CameraName"/>: brand and model, the brand once).
|
||||
/// </summary>
|
||||
private static async Task<IResult> FacetsAsync(HttpContext context, ChronosDatabase db, ServerArchive archive)
|
||||
{
|
||||
var facets = await db.Sequences.GetFacetsAsync(archive.Id, context.RequestAborted);
|
||||
return Results.Json(new LibraryFacetsDto(
|
||||
[.. facets.Years.Select(y => new FacetDto(y.Value, y.Sequences))],
|
||||
[.. facets.Cameras.Select(c => new FacetDto(c.Value, c.Sequences, PathTemplate.CameraName(c.Make, c.Value)))],
|
||||
[.. facets.Tags.Select(t => new FacetDto(t.Value, t.Sequences))]), ProtocolJson.Default.LibraryFacetsDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The thumbnail of the sequence's hero frame, else of its first frame, streamed like <c>/frames/{id}/thumb</c> with an
|
||||
/// ETag (304 when unchanged); 404 <c>not_found</c> (<c>thumbnail</c>) when the sequence has no frame or that thumbnail
|
||||
/// is not built yet.
|
||||
/// </summary>
|
||||
private static async Task<IResult> ThumbAsync(HttpContext context, Guid id, ChronosDatabase db, ServerArchive archive, IFrameAssetLocator locator)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
var frame = sequence.HeroFrameId is { } hero && await db.Frames.GetAsync(hero, ct) is { } chosen && chosen.SequenceId == id
|
||||
? chosen
|
||||
: (await db.Frames.ListBySequenceAsync(id, limit: 1, cancellationToken: ct)).FirstOrDefault();
|
||||
if (frame is null) return ApiErrors.NotFound(context, "thumbnail");
|
||||
var location = await locator.LocateAsync(archive.Current, sequence, frame, FrameAsset.Thumbnail, ct);
|
||||
if (location is null || !ArchivePathGuard.IsInside(archive.Root, location.Path)) return ApiErrors.NotFound(context, "thumbnail");
|
||||
var file = new FileInfo(location.Path);
|
||||
if (!file.Exists || file.LinkTarget is not null) return ApiErrors.NotFound(context, "thumbnail");
|
||||
var etag = string.Create(CultureInfo.InvariantCulture, $"s-{frame.Id:N}-{file.LastWriteTimeUtc.Ticks}-{location.Offset}");
|
||||
return FileResponses.Serve(context, file, location.Offset, location.Length, location.ContentType, Regenerable, etag)
|
||||
?? ApiErrors.NotFound(context, "thumbnail");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves photos of a sequence into the archive's trash (<see cref="FrameTrash"/>; BRIEF §0.2 rule 8: nothing is erased),
|
||||
/// or with <c>dryRun</c> says what would go. Owners and admins only, like deleting the sequence. 400 <c>bad_request</c>
|
||||
/// (<c>frameIds</c>: none, or more than <see cref="MaxFrameIds"/>); 404 <c>not_found</c> (<c>sequence</c>, also when it
|
||||
/// left the index meanwhile); 409 <c>frames_conflict</c> (the frames changed since <c>expectedFramesVersion</c>, or a
|
||||
/// photo named is not the sequence's; details: the frames version now), <c>sequence_busy</c>, <c>would_empty</c> (every
|
||||
/// photo would go: delete the sequence instead), <c>photo_unreadable</c> (a photo never hashed cannot be read, so its
|
||||
/// deletion could leave no tombstone; one whose original is missing goes without one), <c>sidecar_mismatch</c> (the
|
||||
/// sidecar in its folder is damaged or another sequence's), <c>folder_in_use</c>; 413 <c>too_large</c> (a body above
|
||||
/// <see cref="FrameDeleteBodyLimit"/>); 503 <c>archive_offline</c>. Publishes <c>sequenceChanged</c> <c>frames</c>; the
|
||||
/// thumbnails, proxies and analyses follow as jobs.
|
||||
/// </summary>
|
||||
private static async Task<IResult> DeleteFramesAsync(HttpContext context, Caller caller, Guid id, FrameDeleteRequest request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (request.FrameIds is not { Count: > 0 and <= MaxFrameIds } ids) return ApiErrors.BadRequest(context, "bad_request", "frameIds");
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context);
|
||||
var engine = Engine(archives, db).FrameTrash;
|
||||
FrameDeletePlan plan;
|
||||
try
|
||||
{
|
||||
plan = await engine.PlanDeleteAsync(id, ids, request.ExpectedFramesVersion, ct);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
}
|
||||
if (plan.Blocked.Count > 0) return Refused(context, plan);
|
||||
if (request.DryRun)
|
||||
return Results.Json(new FrameDeleteResultDto(id, plan.Frames.Count, plan.Bytes, plan.Sequence.FramesVersion, plan.Sequence.FrameCount, null, true),
|
||||
ProtocolJson.Default.FrameDeleteResultDto);
|
||||
|
||||
FrameDeleteResult result;
|
||||
try
|
||||
{
|
||||
// Once confirmed the deletion runs to the end even if the client goes away meanwhile.
|
||||
result = await engine.DeleteAsync(plan, caller.User.Username, host.Engine, lifetime.ApplicationStopping);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return Refused(context, plan with { Blocked = [FrameDeleteBlock.Offline] });
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// The sequence left the index since the plan.
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
}
|
||||
catch (Exception ex) when (ex is StaleDeletePlanException or LeaseUnavailableException)
|
||||
{
|
||||
return await RefusedAgainAsync(context, engine, id, ids, plan.Sequence.FramesVersion,
|
||||
ex is LeaseUnavailableException ? FrameDeleteBlock.Busy : FrameDeleteBlock.FramesChanged, ct);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// The sidecar in the sequence's folder is damaged or another sequence's: nothing moved.
|
||||
return ApiErrors.Conflict(context, "sidecar_mismatch");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A photo is open in another program: nothing moved.
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "frames_deleted", "sequence", id.ToString(), $"{plan.Frames.Count} · {result.Entry.Name}");
|
||||
events.Publish(new SequenceChangedEvent(id, "frames", result.Sequence.FramesVersion, result.Sequence.SettingsVersion));
|
||||
return Results.Json(new FrameDeleteResultDto(id, plan.Frames.Count, plan.Bytes, result.Sequence.FramesVersion, result.Sequence.FrameCount,
|
||||
result.Entry.Name, false), ProtocolJson.Default.FrameDeleteResultDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A plan's first block, each with its own code: 503 <c>archive_offline</c>; 409 <c>sequence_busy</c>,
|
||||
/// <c>frames_conflict</c> (details: the frames version now), <c>would_empty</c>, <c>photo_unreadable</c> (a photo never
|
||||
/// hashed cannot be read, so it could leave no tombstone; the message names the first, details: how many).
|
||||
/// </summary>
|
||||
private static IResult Refused(HttpContext context, FrameDeletePlan plan) => plan.Blocked[0] switch
|
||||
{
|
||||
FrameDeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"),
|
||||
FrameDeleteBlock.Busy => ApiErrors.Conflict(context, "sequence_busy"),
|
||||
FrameDeleteBlock.FramesChanged => ApiErrors.Conflict(context, "frames_conflict", plan.Sequence.FramesVersion.ToString(CultureInfo.InvariantCulture)),
|
||||
FrameDeleteBlock.WouldEmpty => ApiErrors.Conflict(context, "would_empty"),
|
||||
FrameDeleteBlock.Unhashable => ApiErrors.Result(context, StatusCodes.Status409Conflict, "photo_unreadable",
|
||||
plan.Unhashable.Count.ToString(CultureInfo.InvariantCulture), plan.Unhashable.Count > 0 ? Path.GetFileName(plan.Unhashable[0].RelativePath) : "?"),
|
||||
var other => throw new ArgumentOutOfRangeException(nameof(plan), other, "A block without an error code."),
|
||||
};
|
||||
|
||||
/// <summary>A deletion refused under the lease, said as the plan is now (<paramref name="otherwise"/> when nothing blocks it); 404 when the sequence is gone.</summary>
|
||||
private static async Task<IResult> RefusedAgainAsync(HttpContext context, FrameTrash engine, Guid id, IReadOnlyList<Guid> ids, int framesVersion,
|
||||
FrameDeleteBlock otherwise, CancellationToken ct)
|
||||
{
|
||||
FrameDeletePlan again;
|
||||
try
|
||||
{
|
||||
again = await engine.PlanDeleteAsync(id, ids, framesVersion, ct);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
}
|
||||
return Refused(context, again.Blocked.Count > 0 ? again : again with { Blocked = [otherwise] });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves many sequences into the trash as <c>DELETE /sequences/{id}</c> does each (or, with <c>dryRun</c>, plans them):
|
||||
/// one item per id, <c>ok</c> with the trash folder, or <c>skipped</c> with the code that says why (<c>not_found</c>,
|
||||
/// <c>forbidden</c> for a sequence of another user, <c>sequence_busy</c>, <c>archive_root</c>, <c>contains_sequences</c>,
|
||||
/// <c>sidecar_mismatch</c>, <c>folder_missing</c>, <c>archive_offline</c>, <c>folder_in_use</c>). Each sequence moves whole
|
||||
/// or not at all. 400 <c>bad_request</c> (<c>ids</c>).
|
||||
/// </summary>
|
||||
private static async Task<IResult> BulkDeleteAsync(HttpContext context, Caller caller, BulkDeleteRequest request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
var trash = Engine(archives, db).Trash;
|
||||
var items = new Dictionary<Guid, BulkItemResult>();
|
||||
var allowed = new List<Sequence>();
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) items[id] = Skip(context, id, "not_found");
|
||||
else if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) items[id] = Skip(context, id, "forbidden");
|
||||
else allowed.Add(sequence);
|
||||
}
|
||||
var steps = new List<DeleteStep>();
|
||||
foreach (var (sequence, reason, step) in await PlanEachAsync(trash, allowed, ct))
|
||||
{
|
||||
if (step is not null) steps.Add(step);
|
||||
else items[sequence.Id] = Skip(context, sequence.Id, reason!);
|
||||
}
|
||||
var photos = 0;
|
||||
long bytes = 0;
|
||||
foreach (var step in steps)
|
||||
{
|
||||
var sequence = step.Sequence;
|
||||
if (!request.DryRun)
|
||||
{
|
||||
try
|
||||
{
|
||||
await trash.DeleteAsync(new DeletePlan([step], []), caller.User.Username, null, lifetime.ApplicationStopping);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
items[sequence.Id] = Skip(context, sequence.Id, "archive_offline");
|
||||
continue;
|
||||
}
|
||||
catch (Exception ex) when (ex is StaleDeletePlanException or LeaseUnavailableException)
|
||||
{
|
||||
items[sequence.Id] = Skip(context, sequence.Id, "sequence_busy");
|
||||
continue;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// An interrupted journal could not be settled first: its sidecar is damaged (a scan rebuilds it).
|
||||
items[sequence.Id] = Skip(context, sequence.Id, "sidecar_mismatch");
|
||||
continue;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
items[sequence.Id] = Skip(context, sequence.Id, "folder_in_use");
|
||||
continue;
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", sequence.Id.ToString(), sequence.DisplayTitle);
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "deleted", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
}
|
||||
items[sequence.Id] = new BulkItemResult(sequence.Id, Ok, TrashFolder: step.TrashFolder);
|
||||
photos += sequence.FrameCount;
|
||||
bytes += step.Bytes;
|
||||
}
|
||||
return Results.Json(Result(ids, items, request.DryRun, photos, bytes), ProtocolJson.Default.BulkResultDto);
|
||||
}
|
||||
|
||||
/// <summary>Each sequence's delete plan: its step, or the code of why it cannot go.</summary>
|
||||
private static async Task<List<(Sequence Sequence, string? Reason, DeleteStep? Step)>> PlanEachAsync(SequenceTrash trash, List<Sequence> sequences,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var planned = new List<(Sequence, string?, DeleteStep?)>();
|
||||
if (sequences.Count == 0) return planned;
|
||||
DeletePlan plan;
|
||||
try
|
||||
{
|
||||
plan = await trash.PlanAsync([.. sequences.Select(s => s.Id)], null, ct);
|
||||
}
|
||||
catch (ArgumentException) when (sequences.Count == 1)
|
||||
{
|
||||
return [(sequences[0], "not_found", null)];
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// One left the index meanwhile: planned one by one, so the others still go.
|
||||
foreach (var sequence in sequences) planned.AddRange(await PlanEachAsync(trash, [sequence], ct));
|
||||
return planned;
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return [.. sequences.Select(s => (s, (string?)"archive_offline", (DeleteStep?)null))];
|
||||
}
|
||||
foreach (var step in plan.Steps) planned.Add((step.Sequence, null, step));
|
||||
foreach (var blocked in plan.Blocked) planned.Add((blocked.Sequence, BlockCode(blocked.Reason), null));
|
||||
return planned;
|
||||
}
|
||||
|
||||
/// <summary>The error code of a sequence that cannot go to the trash, as <c>DELETE /sequences/{id}</c> answers it.</summary>
|
||||
internal static string BlockCode(DeleteBlock reason) => reason switch
|
||||
{
|
||||
DeleteBlock.Offline => "archive_offline",
|
||||
DeleteBlock.Busy => "sequence_busy",
|
||||
DeleteBlock.ArchiveRoot => "archive_root",
|
||||
DeleteBlock.ContainsSequences => "contains_sequences",
|
||||
DeleteBlock.ForeignSidecar => "sidecar_mismatch",
|
||||
_ => "folder_missing",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Adds and removes tags on many sequences, each with the same edit as a PATCH of its tags (case-insensitive, the first
|
||||
/// spelling kept; settings version + 1 when they change). Skipped: <c>not_found</c>, <c>bad_request</c> (more than 50
|
||||
/// tags then). 400 <c>bad_request</c> (<c>ids</c>, <c>tags</c>). Publishes <c>sequenceChanged</c> <c>settings</c>.
|
||||
/// </summary>
|
||||
private static async Task<IResult> BulkRetagAsync(HttpContext context, Caller caller, BulkRetagRequest request, ChronosDatabase db, AuditLog audit,
|
||||
EventHub events)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
if (Tags(request.Add) is not { } add || Tags(request.Remove) is not { } remove || add.Count + remove.Count == 0)
|
||||
return ApiErrors.BadRequest(context, "bad_request", "tags");
|
||||
var items = new Dictionary<Guid, BulkItemResult>();
|
||||
foreach (var id in ids)
|
||||
{
|
||||
items[id] = await RetagAsync(context, caller, db, audit, events, id, add, remove, ct);
|
||||
}
|
||||
return Results.Json(Result(ids, items, false, 0, 0), ProtocolJson.Default.BulkResultDto);
|
||||
}
|
||||
|
||||
private static async Task<BulkItemResult> RetagAsync(HttpContext context, Caller caller, ChronosDatabase db, AuditLog audit, EventHub events, Guid id,
|
||||
IReadOnlyList<string> add, IReadOnlyList<string> remove, CancellationToken ct)
|
||||
{
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return Skip(context, id, "not_found");
|
||||
var tags = sequence.Tags.Where(t => !remove.Contains(t, StringComparer.OrdinalIgnoreCase)).ToList();
|
||||
tags.AddRange(add.Where(t => !tags.Contains(t, StringComparer.OrdinalIgnoreCase)));
|
||||
if (tags.Count > SequenceEndpoints.MaxTags) return Skip(context, id, "bad_request");
|
||||
if (tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(sequence.Tags)) return new BulkItemResult(id, Ok);
|
||||
var result = await db.Sequences.EditAsync(id, new SequenceEdit { Tags = tags }, sequence.SettingsVersion, ct);
|
||||
if (result.Outcome == SequenceEditOutcome.NotFound) return Skip(context, id, "not_found");
|
||||
// Edited meanwhile: the tags apply again on top of that edit.
|
||||
if (result.Outcome == SequenceEditOutcome.Conflict) continue;
|
||||
var updated = result.Sequence!;
|
||||
await audit.WriteAsync(caller, context, "sequence_updated", "sequence", id.ToString(), "tags");
|
||||
events.Publish(new SequenceChangedEvent(id, "settings", updated.FramesVersion, updated.SettingsVersion));
|
||||
return new BulkItemResult(id, Ok);
|
||||
}
|
||||
return Skip(context, id, "settings_conflict");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues one job over many sequences: <c>analyse</c> (light analysis), <c>deep</c> (deep analysis), <c>proxies</c>,
|
||||
/// <c>thumbnails</c> or <c>verify</c> (a verify of those sequences in their archive), at user priority. Sequences not in
|
||||
/// the index are skipped (<c>not_found</c>). 202 with the job when one was queued; 400 <c>invalid_job_kind</c>,
|
||||
/// <c>bad_request</c> (<c>ids</c>); 409 <c>job_unavailable</c> when this server cannot run that kind.
|
||||
/// </summary>
|
||||
private static async Task<IResult> BulkJobsAsync(HttpContext context, Caller caller, BulkJobsRequest request, ChronosDatabase db, ServerArchive archive,
|
||||
JobEngineHost host, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
if (BulkKind(request.Kind) is not { } kind) return ApiErrors.BadRequest(context, "invalid_job_kind");
|
||||
if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind));
|
||||
var items = new Dictionary<Guid, BulkItemResult>();
|
||||
var found = new List<Sequence>();
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is { } sequence && sequence.ArchiveId == archive.Id)
|
||||
{
|
||||
found.Add(sequence);
|
||||
items[id] = new BulkItemResult(id, Ok);
|
||||
}
|
||||
else
|
||||
{
|
||||
items[id] = Skip(context, id, "not_found");
|
||||
}
|
||||
}
|
||||
if (found.Count == 0) return Results.Json(Result(ids, items, false, 0, 0), ProtocolJson.Default.BulkResultDto);
|
||||
var targets = found.Select(s => s.Id).ToList();
|
||||
var label = Label(found);
|
||||
var job = await host.Engine.EnqueueAsync(SequenceJob(kind, archive.Current, targets, label) with { Priority = JobPriority.User }, caller.Id, ct);
|
||||
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {label}");
|
||||
return Results.Json(Result(ids, items, false, 0, 0) with { Job = Dto.Job(job) }, ProtocolJson.Default.BulkResultDto,
|
||||
statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>The kinds a bulk job request names.</summary>
|
||||
private static JobKind? BulkKind(string? kind) => kind?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"analyse" => JobKind.LightAnalyse,
|
||||
"deep" => JobKind.DeepAnalyse,
|
||||
"proxies" => JobKind.Proxies,
|
||||
"thumbnails" => JobKind.Thumbs,
|
||||
"verify" => JobKind.Verify,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The job of a sequence kind over <paramref name="sequenceIds"/>. A verify targets the archive and names the sequences
|
||||
/// in its parameters (<see cref="ArchiveJobs.Verify"/>), as its handler reads it.
|
||||
/// </summary>
|
||||
internal static ArchiveJobRequest SequenceJob(JobKind kind, Archive archive, IReadOnlyList<Guid> sequenceIds, string label) => kind switch
|
||||
{
|
||||
JobKind.Verify => ArchiveJobs.Verify(archive, sequenceIds) with { Label = label },
|
||||
JobKind.LightAnalyse => ProcessingJobs.LightAnalysis(sequenceIds, label),
|
||||
JobKind.DeepAnalyse => ProcessingJobs.DeepAnalysis(sequenceIds, label),
|
||||
JobKind.Proxies => ArchiveJobs.Proxies(sequenceIds, label),
|
||||
JobKind.Thumbs => ArchiveJobs.Thumbnails(sequenceIds, label),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Not a sequence job."),
|
||||
};
|
||||
|
||||
/// <summary>"Harbour sunset", or the first three titles and "…".</summary>
|
||||
internal static string Label(IReadOnlyList<Sequence> sequences) =>
|
||||
sequences.Count == 1 ? sequences[0].DisplayTitle
|
||||
: string.Join(", ", sequences.Take(3).Select(s => s.DisplayTitle)) + (sequences.Count > 3 ? " …" : string.Empty);
|
||||
|
||||
/// <summary>The ids of a bulk request, once each in their order; null when there are none or too many.</summary>
|
||||
private static List<Guid>? Ids(IReadOnlyList<Guid>? ids) =>
|
||||
ids is { Count: > 0 and <= MaxBulkIds } ? [.. ids.Distinct()] : null;
|
||||
|
||||
/// <summary>Tags as a request names them, trimmed, once each; null when one is blank or too long.</summary>
|
||||
private static List<string>? Tags(IReadOnlyList<string>? tags)
|
||||
{
|
||||
if (tags is null) return [];
|
||||
var list = new List<string>();
|
||||
foreach (var tag in tags)
|
||||
{
|
||||
var trimmed = tag?.Trim();
|
||||
if (string.IsNullOrEmpty(trimmed) || trimmed.Length > TagRepository.MaxLength) return null;
|
||||
if (!list.Contains(trimmed, StringComparer.OrdinalIgnoreCase)) list.Add(trimmed);
|
||||
}
|
||||
return list.Count > SequenceEndpoints.MaxTags ? null : list;
|
||||
}
|
||||
|
||||
private static BulkItemResult Skip(HttpContext context, Guid id, string code) => new(id, Skipped, code, ApiErrors.Message(context, code));
|
||||
|
||||
private static BulkResultDto Result(List<Guid> ids, Dictionary<Guid, BulkItemResult> items, bool dryRun, int photos, long bytes)
|
||||
{
|
||||
var ordered = ids.Select(id => items[id]).ToList();
|
||||
var ok = ordered.Count(i => i.Outcome == Ok);
|
||||
return new BulkResultDto(ordered, ok, ordered.Count - ok, dryRun, photos, bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The photo delete route's body limit (<see cref="FrameDeleteBodyLimit"/>), applied by routing as it selects the
|
||||
/// endpoint, as for proxies (<see cref="FileEndpoints"/>): the server's 1 MiB stops at about 26,900 ids.
|
||||
/// </summary>
|
||||
private sealed class FrameDeleteBodyLimitMetadata : IRequestSizeLimitMetadata
|
||||
{
|
||||
public long? MaxRequestBodySize => FrameDeleteBodyLimit;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user