The web panel now manages the library without editing it: the owner can browse and view sequences and photos, delete sequences and photos into the archive's trash, restore or empty the trash and run mass operations, as R6 asks, on top of the engine endpoints of the previous commit. - Library page right after the Dashboard: search, Year/Camera/Status/Tag filters fed by a new GET /api/v1/sequences/facets, sort, cards or list (remembered per browser), lazy cover thumbnails, Load more by cursor, multi-select with Shift ranges and "Select all N" of the filter, and a sticky bar for the selection: Analyse, Proxies, Thumbnails, Verify, Tags (add/remove), Export CSV (client-side) and Delete (dry run, list of what moves to the trash, then the move). Filters live in the address, so Back from a sequence finds them again. - Sequence view (#/library?id=): inline title, tags, rating and notes, facts, photos in pages of 500 with content-visibility, a photo viewer (proxy, arrows, Esc, Exif facts), Set cover, Download original, Delete photos (typing the count above 20 photos), Delete sequence, renders to download. No video editing controls. - Trash view (#/library?view=trash, also linked from Archive): entries, Restore, and Empty (dry run, list, the localised word typed, the plan's fingerprint sent back, the job followed to its end). - Live updates from sequenceChanged and jobState; keyboard grid (one tab stop, arrows, Space, Shift+Space, Enter, Ctrl+A, Esc); RTL, dark theme. - GET /sequences takes rendered=true|false for the Status filter. - ui.js: confirmDialog's typed confirmation by name, word or count, with a list of what the action concerns; formDialog. api.js: putBytes for the web upload, which the Library imports on demand (upload.js, optional). - New web icons from icons.py (Image for the Library, trash, grid/list, arrows, stars, cover); directional glyphs mirror in right-to-left pages. - Strings in en and it; tests for the facets (both dialects), the rendered filter, the menu, the modules and the on-demand upload import. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 029cf334f66cb6fa1265b96a6f8faff2964c11ea)
394 lines
22 KiB
C#
394 lines
22 KiB
C#
using System.Globalization;
|
|
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;
|
|
|
|
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);
|
|
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>); 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>folder_in_use</c>; 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.Blocked[0], plan.Sequence);
|
|
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, FrameDeleteBlock.Offline, plan.Sequence);
|
|
}
|
|
catch (Exception ex) when (ex is StaleDeletePlanException or LeaseUnavailableException)
|
|
{
|
|
var again = await engine.PlanDeleteAsync(id, ids, plan.Sequence.FramesVersion, ct);
|
|
return Refused(context, again.Blocked.Count > 0 ? again.Blocked[0] : ex is LeaseUnavailableException ? FrameDeleteBlock.Busy : FrameDeleteBlock.FramesChanged,
|
|
again.Sequence);
|
|
}
|
|
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);
|
|
}
|
|
|
|
private static IResult Refused(HttpContext context, FrameDeleteBlock reason, Sequence sequence) => reason switch
|
|
{
|
|
FrameDeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"),
|
|
FrameDeleteBlock.Busy => ApiErrors.Conflict(context, "sequence_busy"),
|
|
FrameDeleteBlock.WouldEmpty => ApiErrors.Conflict(context, "would_empty"),
|
|
_ => ApiErrors.Conflict(context, "frames_conflict", sequence.FramesVersion.ToString(CultureInfo.InvariantCulture)),
|
|
};
|
|
|
|
/// <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 (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);
|
|
}
|
|
}
|