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; /// /// 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 (), 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. /// public static class LibraryEndpoints { /// Sequences one bulk request may name. public const int MaxBulkIds = 1000; /// Photos one delete request may name. 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); } /// The archive engine behind these operations: the host's, or one of its own (a test host that replaces the archive module). internal static ArchiveService Engine(ArchiveService? archives, ChronosDatabase db) => archives ?? new ArchiveService(db, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, ImagesAfterScan = true }); /// /// 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 (: brand and model, the brand once). /// private static async Task 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); } /// /// The thumbnail of the sequence's hero frame, else of its first frame, streamed like /frames/{id}/thumb with an /// ETag (304 when unchanged); 404 not_found (thumbnail) when the sequence has no frame or that thumbnail /// is not built yet. /// private static async Task 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"); } /// /// Moves photos of a sequence into the archive's trash (; BRIEF §0.2 rule 8: nothing is erased), /// or with dryRun says what would go. Owners and admins only, like deleting the sequence. 400 bad_request /// (frameIds); 409 frames_conflict (the frames changed since expectedFramesVersion, or a photo named /// is not the sequence's; details: the frames version now), sequence_busy, would_empty (every photo would /// go: delete the sequence instead), folder_in_use; 503 archive_offline. Publishes sequenceChanged /// frames; the thumbnails, proxies and analyses follow as jobs. /// private static async Task 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)), }; /// /// Moves many sequences into the trash as DELETE /sequences/{id} does each (or, with dryRun, plans them): /// one item per id, ok with the trash folder, or skipped with the code that says why (not_found, /// forbidden for a sequence of another user, sequence_busy, archive_root, contains_sequences, /// sidecar_mismatch, folder_missing, archive_offline, folder_in_use). Each sequence moves whole /// or not at all. 400 bad_request (ids). /// private static async Task 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(); var allowed = new List(); 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(); 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); } /// Each sequence's delete plan: its step, or the code of why it cannot go. private static async Task> PlanEachAsync(SequenceTrash trash, List 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; } /// The error code of a sequence that cannot go to the trash, as DELETE /sequences/{id} answers it. 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", }; /// /// 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: not_found, bad_request (more than 50 /// tags then). 400 bad_request (ids, tags). Publishes sequenceChanged settings. /// private static async Task 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(); 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 RetagAsync(HttpContext context, Caller caller, ChronosDatabase db, AuditLog audit, EventHub events, Guid id, IReadOnlyList add, IReadOnlyList 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"); } /// /// Queues one job over many sequences: analyse (light analysis), deep (deep analysis), proxies, /// thumbnails or verify (a verify of those sequences in their archive), at user priority. Sequences not in /// the index are skipped (not_found). 202 with the job when one was queued; 400 invalid_job_kind, /// bad_request (ids); 409 job_unavailable when this server cannot run that kind. /// private static async Task 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(); var found = new List(); 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); } /// The kinds a bulk job request names. 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, }; /// /// The job of a sequence kind over . A verify targets the archive and names the sequences /// in its parameters (), as its handler reads it. /// internal static ArchiveJobRequest SequenceJob(JobKind kind, Archive archive, IReadOnlyList 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."), }; /// "Harbour sunset", or the first three titles and "…". internal static string Label(IReadOnlyList sequences) => sequences.Count == 1 ? sequences[0].DisplayTitle : string.Join(", ", sequences.Take(3).Select(s => s.DisplayTitle)) + (sequences.Count > 3 ? " …" : string.Empty); /// The ids of a bulk request, once each in their order; null when there are none or too many. private static List? Ids(IReadOnlyList? ids) => ids is { Count: > 0 and <= MaxBulkIds } ? [.. ids.Distinct()] : null; /// Tags as a request names them, trimmed, once each; null when one is blank or too long. private static List? Tags(IReadOnlyList? tags) { if (tags is null) return []; var list = new List(); 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 ids, Dictionary 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); } }