using Microsoft.AspNetCore.Mvc;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Naming;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Repositories;
using Chronos.Protocol;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
using Chronos.Server.Storage;
namespace Chronos.Server.Api;
///
/// /api/v1/archive (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics, and
/// Reorganize (owner review 2, R7): new templates applied to sequences already in the archive.
///
public static class ArchiveEndpoints
{
public static void Map(RouteGroupBuilder api)
{
var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive);
archive.MapPost("/reorganize", ReorganizeAsync);
// The form saves every field: it starts from what archive.json holds now, also a desktop's change since the last poll.
archive.MapGet("/settings", async (HttpContext c, ServerArchive a, ChronosDatabase db, [FromServices] ArchiveService? archives) =>
Results.Json(Settings(archives is null ? a.Current : await a.RefreshAsync(archives, db, c.RequestAborted)), ProtocolJson.Default.ArchiveSettingsDto));
archive.MapPut("/settings", UpdateAsync);
archive.MapGet("/stats", async (HttpContext c, ChronosDatabase db, ServerArchive a, VolumeSpace volumes) =>
Results.Json(await StatsAsync(db, a, volumes, c.RequestAborted), ProtocolJson.Default.ArchiveStatsDto));
foreach (var (path, kind) in new[] { ("scan", JobKind.Scan), ("rebuild", JobKind.Rebuild), ("verify", JobKind.Verify), ("maintenance", JobKind.Maintenance) })
{
archive.MapPost("/" + path, (HttpContext c, Caller caller, ServerArchive a, JobEngineHost host, AuditLog audit) => EnqueueAsync(c, caller, a, host, audit, kind));
}
}
///
/// Totals, distributions, free space and health of the archive (also shown on the dashboard). The free space is the
/// space volume's (), with the archive's own volume apart when they differ; an offline
/// volume reports no figures (0).
///
public static async Task StatsAsync(ChronosDatabase db, ServerArchive archive, VolumeSpace volumes, CancellationToken cancellationToken)
{
var stats = await db.Sequences.GetStatsAsync(archive.Id, cancellationToken);
var withoutProxies = await db.Sequences.CountAsync(
new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = SequenceStatus.ProxiesBuilt }, cancellationToken);
var storage = volumes.Report(archive.Root);
return new ArchiveStatsDto(
stats.Sequences,
stats.Photos,
stats.Bytes,
storage.Space?.FreeBytes ?? 0,
storage.Space?.TotalBytes ?? 0,
stats.ByCamera.Count(c => c.Model is not null),
stats.ByYear.Count > 0 ? stats.ByYear[0].Year : null,
stats.ByYear.Count > 0 ? stats.ByYear[^1].Year : null,
[.. stats.ByYear.Select(y => new KeyValueCount(y.Year.ToString(System.Globalization.CultureInfo.InvariantCulture), y.Photos, y.Bytes))],
[.. stats.ByMonth.Select(m => new KeyValueCount($"{m.Year:D4}-{m.Month:D2}", m.Photos, 0))],
[.. stats.ByCamera.Select(c => new KeyValueCount(string.Join(' ', new[] { c.Make, c.Model }.Where(v => !string.IsNullOrEmpty(v))), c.Photos, c.Bytes))],
[.. stats.ByFormat.Select(f => new KeyValueCount(f.Format.ToString().ToLowerInvariant(), f.Photos, f.Bytes))],
withoutProxies,
stats.Health.Unverified,
storage.Write?.FreeBytes,
storage.Write?.TotalBytes,
storage.FileSystem,
storage.FromSpacePath);
}
///
/// Writes the name, templates and proxy policy into the archive's archive.json through the archive engine (so a
/// restart and the proxy jobs see them), then into the index. 400 bad_request (details name,
/// proxyLongEdge), 400 invalid_template (: folderTemplate or
/// fileTemplate, with the rule it breaks); 503 archive_offline while the archive cannot be
/// written; 409 archive_busy while another process holds its settings; 409 archive_manifest when its
/// archive.json is damaged, written by a newer Chronos or of another archive; 409 archive_policy when it holds a
/// thumbnail or proxy setting this API cannot set and Chronos cannot use (details: thumbnailPolicy or
/// proxyPolicy, the property to correct in the file). Nothing is written.
///
private static async Task UpdateAsync(HttpContext context, Caller caller, ArchiveSettingsDto request, ChronosDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, AuditLog audit)
{
var name = request.Name?.Trim();
if (string.IsNullOrEmpty(name) || name.Length > ArchiveSettings.MaxNameLength) return ApiErrors.BadRequest(context, "bad_request", "name");
if (string.IsNullOrWhiteSpace(request.FolderTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "folderTemplate");
if (string.IsNullOrWhiteSpace(request.FileTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "fileTemplate");
// The rules Reorganize checks: a folder scans never enter, a lost extension or names that repeat are refused alike.
if (new RenameTemplates(request.FolderTemplate, request.FileTemplate).Check() is { } problem) return InvalidTemplate(context, problem);
if (!ProxyPolicy.IsValidLongEdge(request.ProxyLongEdge)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge");
var engine = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
Archive updated;
try
{
updated = await engine.UpdateSettingsAsync(archive.Id, s => s with
{
Name = name,
Templates = s.Templates with { Folder = request.FolderTemplate, File = request.FileTemplate },
Proxies = s.Proxies with { LongEdge = request.ProxyLongEdge },
}, context.RequestAborted);
}
catch (LeaseUnavailableException)
{
return ApiErrors.Conflict(context, "archive_busy");
}
catch (Exception ex) when (ex is InvalidDataException or NewerFormatException)
{
return ApiErrors.Conflict(context, "archive_manifest");
}
catch (ArgumentException ex)
{
// The request's fields were checked above: what fails is a value read from archive.json (a thumbnail size, or a
// proxy quality, written by hand or by another tool), which the admin corrects in the file, not in this form.
return ApiErrors.Conflict(context, "archive_policy", ex.ParamName switch
{
"thumbnailLongEdge" => "thumbnailPolicy",
"proxyLongEdge" => "proxyPolicy",
var other => other,
});
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// ArchiveOfflineException included: nothing was written.
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
}
archive.Current = updated;
await audit.WriteAsync(caller, context, "archive_settings", "archive", updated.Id.ToString(), $"{updated.FolderTemplate} · {updated.FileTemplate}");
return Results.Json(Settings(updated), ProtocolJson.Default.ArchiveSettingsDto);
}
///
/// Reorganize: folder, file and title templates applied to sequenceIds or, with all, to every sequence of the
/// archive (BRIEF §12.5). With dryRun the plan, nothing touched: per sequence its folder and title before and after,
/// the photos renamed with the first of them, and the photos that keep their names and why. Otherwise the request carries
/// that plan's fingerprint and the server queues a move job (202) that applies exactly that plan, refused when the
/// archive changed before it ran. 400 bad_request (details sequenceIds: neither or both of them, none, or
/// more than ; templates: none; fingerprint), 400
/// invalid_template (: folderTemplate, fileTemplate or
/// titleTemplate, with the rule it breaks); 404
/// not_found (sequence: not in the archive); 409 nested_target (details: the folder that would lie
/// inside a sequence's folder), plan_changed (details: the fingerprint now), job_unavailable; 503
/// archive_offline. Audited; the job tells each sequence it changes as sequenceChanged (reorganized)
/// once that sequence's step is journaled (a step that failed half-way, when its retry completes it; a plan the server
/// completes as it starts, no one: no client is connected yet). Photos a sequence receives between the dry run and the
/// confirmation under the names the plan leaves them keep the fingerprint as it was. A dry run's plan is kept a few
/// minutes while the index stays as it was (): the same dry run again, and its
/// confirmation, take it instead of planning again.
///
private static async Task ReorganizeAsync(HttpContext context, Caller caller, ReorganizeRequest request, ChronosDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, ReorganizePlanCache plans)
{
var ct = context.RequestAborted;
if (request.All == (request.SequenceIds is not null) || request.SequenceIds is { Count: 0 or > LibraryEndpoints.MaxBulkIds })
return ApiErrors.BadRequest(context, "bad_request", "sequenceIds");
var templates = new RenameTemplates(request.FolderTemplate, request.FileTemplate, request.TitleTemplate);
if (templates.IsEmpty) return ApiErrors.BadRequest(context, "bad_request", "templates");
if (templates.Check() is { } problem) return InvalidTemplate(context, problem);
if (!request.DryRun && string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
if (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online)
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
var sequences = request.All ? null : request.SequenceIds;
// Stamped before planning: a change committed while the plan is made gives the next request another key.
var key = ReorganizePlanCache.Key.Of(archive.Id, await db.Sequences.GetStampAsync(archive.Id, ct), sequences, templates);
RenamePlan plan;
try
{
plan = await plans.GetOrPlanAsync(key, () => LibraryEndpoints.Engine(archives, db).PlanReorganizeAsync(archive.Id, sequences, templates, ct));
}
catch (NestedRenameException ex)
{
return ApiErrors.Conflict(context, "nested_target", ex.Target);
}
catch (ArgumentException)
{
return ApiErrors.NotFound(context, "sequence");
}
var fingerprint = plan.Fingerprint();
if (request.DryRun) return Results.Json(Plan(context, plan, fingerprint), ProtocolJson.Default.ReorganizePlanDto);
if (!string.Equals(fingerprint, request.Fingerprint, StringComparison.Ordinal)) return ApiErrors.Conflict(context, "plan_changed", fingerprint);
if (!host.CanRun(JobKind.Move)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.Move));
var job = await host.Engine.EnqueueAsync(ArchiveJobs.Reorganize(archive.Current, plan, templates), caller.Id, ct);
plans.Forget(key);
await audit.WriteAsync(caller, context, "archive_reorganized", "job", job.Id.ToString(),
$"{plan.Steps.Count(s => s.Changes)} · {plan.Steps.Sum(s => s.FileChanges)} · {templates.Folder} · {templates.File} · {templates.Title}");
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
}
///
/// 400 invalid_template for a template that cannot be used. The details name its field (fileTemplate); when
/// it parses but breaks a rule of the archive's templates (), the rule follows after a colon
/// (folderTemplate:reserved_folder, fileTemplate:file_separator, fileTemplate:extension,
/// fileTemplate:not_unique) and the message says why in the request's language, as the desktop's fields do
/// (Errors.Template.<Rule>); otherwise the message is that the template is not valid.
///
private static IResult InvalidTemplate(HttpContext context, TemplateProblem problem)
{
if (problem.Rule is not { } rule) return ApiErrors.BadRequest(context, "invalid_template", problem.Field);
var message = Loc.Get("Errors.Template." + rule, RequestCulture.Of(context)) ?? ApiErrors.Message(context, "invalid_template");
var wire = string.Concat(rule.Select((c, i) => char.IsUpper(c) ? (i > 0 ? "_" : string.Empty) + char.ToLowerInvariant(c) : c.ToString()));
return Results.Json(new ApiError("invalid_template", message, $"{problem.Field}:{wire}"), ProtocolJson.Default.ApiError,
statusCode: StatusCodes.Status400BadRequest);
}
/// The dry run as the API answers it, with each reason something stays as it is in the request's language.
private static ReorganizePlanDto Plan(HttpContext context, RenamePlan plan, string fingerprint)
{
var culture = RequestCulture.Of(context);
return new ReorganizePlanDto(
[.. plan.Steps.Select(s => new ReorganizeStepDto(s.SequenceId, s.FromFolder, s.ToFolder, s.FromTitle, s.ToTitle, s.Carried, s.FramesVersion,
s.FileChanges, [.. s.FileSamples.Select(f => new ReorganizeFileDto(f.From, f.To))],
[.. s.Blocked.Select(b => new ReorganizeBlockedDto(Wire(b.Reason), b.Frames, Loc.Get("Archive.Reorganize.Blocked." + b.Reason, culture) ?? Wire(b.Reason)))]))],
plan.Steps.Count(s => s.Changes),
plan.Steps.Sum(s => s.FileChanges),
plan.Steps.Sum(s => s.Blocked.Sum(b => b.Frames)),
fingerprint);
}
///
/// Wire name of a reason something stays as it is: photos that keep their names (in_place, unhashed,
/// missing), or the whole sequence (unreadable).
///
public static string Wire(RenameBlock reason) => reason switch
{
RenameBlock.InPlace => "in_place",
RenameBlock.Unhashed => "unhashed",
RenameBlock.Missing => "missing",
_ => "unreadable",
};
private static async Task EnqueueAsync(HttpContext context, Caller caller, ServerArchive archive, JobEngineHost host, AuditLog audit, JobKind kind)
{
if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind));
var job = await host.Engine.EnqueueAsync(kind, [archive.Id], archive.Current.Name, priority: JobPriority.User, createdBy: caller.Id,
cancellationToken: context.RequestAborted);
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), JobWire.Kind(kind));
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
}
private static ArchiveSettingsDto Settings(Archive a) => new(a.Id, a.Name, a.RootPath, a.FolderTemplate, a.FileTemplate, a.ProxyLongEdge);
}