using Microsoft.AspNetCore.Mvc;
using Titano.Core.Archiving;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Repositories;
using Titano.Protocol;
using Titano.Server.Jobs;
using Titano.Server.Security;
using Titano.Server.Storage;
namespace Titano.Server.Api;
/// /api/v1/archive (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics.
public static class ArchiveEndpoints
{
public static void Map(RouteGroupBuilder api)
{
var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive);
archive.MapGet("/settings", (ServerArchive a) => Results.Json(Settings(a.Current), ProtocolJson.Default.ArchiveSettingsDto));
archive.MapPut("/settings", UpdateAsync);
archive.MapGet("/stats", async (HttpContext c, TitanoDatabase db, ServerArchive a) =>
Results.Json(await StatsAsync(db, a, 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).
public static async Task StatsAsync(TitanoDatabase db, ServerArchive archive, 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);
long free = 0, capacity = 0;
try
{
var drive = new DriveInfo(archive.Root);
free = drive.AvailableFreeSpace;
capacity = drive.TotalSize;
}
catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
{
// An offline archive volume reports no space figures.
}
return new ArchiveStatsDto(
stats.Sequences,
stats.Photos,
stats.Bytes,
free,
capacity,
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);
}
///
/// 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. 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 Titano or of another archive; 409 archive_policy when it holds a
/// thumbnail or proxy setting this API cannot set and Titano 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, TitanoDatabase 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");
foreach (var (field, template) in new[] { ("folderTemplate", request.FolderTemplate), ("fileTemplate", request.FileTemplate) })
{
if (string.IsNullOrWhiteSpace(template) || !PathTemplate.Parse(template).IsValid) return ApiErrors.BadRequest(context, "invalid_template", field);
}
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);
}
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);
}