feat(server): API v1 with auth, uploads, sync, jobs, render nodes and events
- Security: PBKDF2-SHA512 (210,000 iterations) hashes, opaque bearer tokens stored as SHA-256 with sliding expiry and revocation, HttpOnly/Secure/ SameSite=Strict admin cookie with a session-bound CSRF token, sign-in rate limit and lockout, role/permission metadata on every endpoint, audit log, first-run administrator bootstrap. - Sequences with keyset paging, ETags and settings_version conflicts; sync manifest; frames, proxies, thumbnails and exports streamed with Range. - Chunked resumable uploads with hash short-circuit, quota and disk checks, staging on the archive volume, SHA-256 verification and IArchiveIngest. - Job engine host, jobs API, render nodes with heartbeat timeout and reassignment, WebSocket events, LAN discovery beacon, upload cleanup. - Windows service host over advapi32 (--service, --install-service, --uninstall-service); fails fast without the archive module services. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
56 files changed
+4726
-108
No files matched your search
@@ -0,0 +1,112 @@
|
||||
using System.Text;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>Administration (BRIEF §14.8): dashboard figures, server settings, log tail and downloads, audit log.</summary>
|
||||
public static class AdminEndpoints
|
||||
{
|
||||
private const int MaxTailLines = 2000;
|
||||
private const int TailWindowBytes = 1 << 20;
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
api.MapGet("/server/dashboard", DashboardAsync).Requires(Permissions.ManageArchive | Permissions.ManageUsers);
|
||||
api.MapGet("/server/settings", (ServerSettingsStore store) => Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto))
|
||||
.Requires(Permissions.ManageArchive);
|
||||
api.MapPut("/server/settings", SaveSettingsAsync).Requires(Permissions.ManageArchive);
|
||||
api.MapGet("/audit", AuditAsync).Requires(Permissions.ManageUsers | Permissions.ManageArchive);
|
||||
|
||||
var logs = api.MapGroup("/logs").Requires(Permissions.ManageArchive);
|
||||
logs.MapGet("", TailAsync);
|
||||
logs.MapGet("/files", (ServerOptions options) => Results.Json(LogFiles(options).Select(f => new LogFileDto(f.Name, f.Length, f.LastWriteTimeUtc)).ToList(),
|
||||
ProtocolJson.Default.ListLogFileDto));
|
||||
logs.MapGet("/files/{name}", (HttpContext context, string name, ServerOptions options) =>
|
||||
{
|
||||
// Only names of existing log files are served: the name never becomes part of a path.
|
||||
if (LogFiles(options).FirstOrDefault(f => f.Name == name) is not { } file) return ApiErrors.NotFound(context, "log");
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
return Results.File(file.FullName, "text/plain; charset=utf-8", file.Name, file.LastWriteTimeUtc, enableRangeProcessing: true);
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<IResult> DashboardAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, ServerOptions options, ServerState state,
|
||||
JobEngineHost jobs, TimeProvider time)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
var now = time.GetUtcNow();
|
||||
var today = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
|
||||
var users = await db.Users.ListAsync(ct);
|
||||
var names = users.ToDictionary(u => u.Id, u => u.Username);
|
||||
var counts = await db.Jobs.CountAsync(today, ct);
|
||||
var running = await db.Jobs.ListAsync(JobState.Running, null, 10, null, ct);
|
||||
var queued = await db.Jobs.ListAsync(JobState.Queued, null, 10, null, ct);
|
||||
var nodes = await db.RenderNodes.ListAsync(ct);
|
||||
var uploads = await db.Uploads.CommittedPerDayAsync(today.AddDays(-29), ct);
|
||||
var activity = await db.Audit.ListAsync(null, null, 12, null, ct);
|
||||
return Results.Json(new DashboardDto(
|
||||
options.ServerName,
|
||||
SystemEndpoints.Version,
|
||||
(long)(now - state.StartedAt).TotalSeconds,
|
||||
state.Database,
|
||||
options.TlsMode.ToString().ToLowerInvariant(),
|
||||
options.Discovery,
|
||||
users.Count,
|
||||
await ArchiveEndpoints.StatsAsync(db, archive, ct),
|
||||
new JobCountsDto(counts.Queued, counts.Running, counts.Paused, counts.DoneSince, counts.FailedSince),
|
||||
jobs.Workers,
|
||||
[.. nodes.Select(n => Dto.Node(n, names.GetValueOrDefault(n.UserId, string.Empty)))],
|
||||
[.. uploads.Select(u => new UploadDayDto(u.Day, u.Count, u.Bytes))],
|
||||
[.. activity.Items.Select(Dto.Audit)],
|
||||
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)]),
|
||||
ProtocolJson.Default.DashboardDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, AuditLog audit)
|
||||
{
|
||||
switch (store.Save(request))
|
||||
{
|
||||
case ("setting_locked", var setting):
|
||||
return ApiErrors.Conflict(context, "setting_locked", setting);
|
||||
case (var code, var setting):
|
||||
return ApiErrors.BadRequest(context, code, setting, setting);
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName);
|
||||
return Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> AuditAsync(HttpContext context, TitanoDatabase db, Guid? user, string? action, string? cursor, int? limit)
|
||||
{
|
||||
var page = await db.Audit.ListAsync(user, string.IsNullOrWhiteSpace(action) ? null : action, limit ?? 100,
|
||||
string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted);
|
||||
return Results.Json(new Page<AuditEntryDto>([.. page.Items.Select(Dto.Audit)], page.NextCursor, null), ProtocolJson.Default.PageAuditEntryDto);
|
||||
}
|
||||
|
||||
/// <summary>The last <c>lines</c> lines (default 300) of the newest server log.</summary>
|
||||
private static async Task<IResult> TailAsync(HttpContext context, ServerOptions options, int? lines)
|
||||
{
|
||||
var take = Math.Clamp(lines ?? 300, 1, MaxTailLines);
|
||||
if (LogFiles(options).FirstOrDefault() is not { } file) return Results.Json(new LogTailDto(string.Empty, []), ProtocolJson.Default.LogTailDto);
|
||||
await using var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
var start = Math.Max(0, stream.Length - TailWindowBytes);
|
||||
stream.Position = start;
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
var text = await reader.ReadToEndAsync(context.RequestAborted);
|
||||
var all = text.Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
||||
// A window that starts mid-file begins with a partial line.
|
||||
var complete = start > 0 && all.Length > 0 ? all[1..] : all;
|
||||
return Results.Json(new LogTailDto(file.Name, [.. complete.TakeLast(take).Select(l => l.TrimEnd('\r'))]), ProtocolJson.Default.LogTailDto);
|
||||
}
|
||||
|
||||
/// <summary>Server log files, newest first.</summary>
|
||||
private static List<FileInfo> LogFiles(ServerOptions options) =>
|
||||
Directory.Exists(options.LogPath)
|
||||
? [.. new DirectoryInfo(options.LogPath).EnumerateFiles("*.log").OrderByDescending(f => f.LastWriteTimeUtc).ThenByDescending(f => f.Name)]
|
||||
: [];
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Error responses of API v1: <c>{ code, message, details }</c> (BRIEF §14.3). <c>code</c> is a stable snake_case
|
||||
/// identifier for programs; <c>message</c> is one localised sentence (resource <c>Server.Error.<Code></c>, language
|
||||
/// from <c>Accept-Language</c>, else the server language); <c>details</c> is optional machine-readable context.
|
||||
/// </summary>
|
||||
public static class ApiErrors
|
||||
{
|
||||
public static IResult Result(HttpContext context, int status, string code, string? details = null, params object?[] args) =>
|
||||
Results.Json(new ApiError(code, Message(context, code, args), details), ProtocolJson.Default.ApiError, statusCode: status);
|
||||
|
||||
public static Task WriteAsync(HttpContext context, int status, string code, string? details = null) =>
|
||||
Result(context, status, code, details).ExecuteAsync(context);
|
||||
|
||||
public static IResult NotFound(HttpContext context, string? what = null) => Result(context, StatusCodes.Status404NotFound, "not_found", what);
|
||||
|
||||
public static IResult BadRequest(HttpContext context, string code, string? details = null, params object?[] args) =>
|
||||
Result(context, StatusCodes.Status400BadRequest, code, details, args);
|
||||
|
||||
public static IResult Conflict(HttpContext context, string code, string? details = null) => Result(context, StatusCodes.Status409Conflict, code, details);
|
||||
|
||||
public static IResult Forbidden(HttpContext context) => Result(context, StatusCodes.Status403Forbidden, "forbidden");
|
||||
|
||||
public static string Message(HttpContext context, string code, params object?[] args)
|
||||
{
|
||||
var culture = RequestCulture.Of(context);
|
||||
var template = Loc.Get("Server.Error." + Pascal(code), culture) ?? code;
|
||||
return args.Length == 0 ? template : string.Format(culture, template, args);
|
||||
}
|
||||
|
||||
private static string Pascal(string code)
|
||||
{
|
||||
var sb = new StringBuilder(code.Length);
|
||||
var upper = true;
|
||||
foreach (var c in code)
|
||||
{
|
||||
if (c == '_')
|
||||
{
|
||||
upper = true;
|
||||
continue;
|
||||
}
|
||||
sb.Append(upper ? char.ToUpperInvariant(c) : c);
|
||||
upper = false;
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The language of a request's messages: the best shipped match of <c>Accept-Language</c>, else the server language.</summary>
|
||||
public static class RequestCulture
|
||||
{
|
||||
public static CultureInfo Of(HttpContext context)
|
||||
{
|
||||
if (context.Items.TryGetValue(typeof(RequestCulture), out var cached) && cached is CultureInfo known) return known;
|
||||
var fallback = context.RequestServices.GetRequiredService<ServerOptions>().Language;
|
||||
var culture = FromHeader(context.Request.Headers.AcceptLanguage.ToString()) ?? Parse(fallback) ?? CultureInfo.GetCultureInfo("en");
|
||||
context.Items[typeof(RequestCulture)] = culture;
|
||||
return culture;
|
||||
}
|
||||
|
||||
private static CultureInfo? FromHeader(string header)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(header) || !StringWithQualityHeaderValue.TryParseList([header], out var values)) return null;
|
||||
foreach (var value in values.OrderByDescending(v => v.Quality ?? 1))
|
||||
{
|
||||
if (value.Value.Value is { } tag && tag != "*" && Parse(tag) is { } culture) return culture;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static CultureInfo? Parse(string tag)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Languages.BestMatch(CultureInfo.GetCultureInfo(tag));
|
||||
}
|
||||
catch (CultureNotFoundException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Naming;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary><c>/api/v1/archive</c> (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics.</summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Totals, distributions, free space and health of the archive (also shown on the dashboard).</summary>
|
||||
public static async Task<ArchiveStatsDto> 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);
|
||||
}
|
||||
|
||||
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, ArchiveSettingsDto request, TitanoDatabase db, ServerArchive archive, AuditLog audit)
|
||||
{
|
||||
var name = request.Name?.Trim();
|
||||
if (string.IsNullOrEmpty(name) || name.Length > 100) 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 (request.ProxyLongEdge is not (-1 or 0) and (< 256 or > 8192)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge");
|
||||
|
||||
var updated = archive.Current with
|
||||
{
|
||||
Name = name,
|
||||
FolderTemplate = request.FolderTemplate,
|
||||
FileTemplate = request.FileTemplate,
|
||||
ProxyLongEdge = request.ProxyLongEdge,
|
||||
};
|
||||
await db.Archives.UpsertAsync(updated, context.RequestAborted);
|
||||
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<IResult> 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);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using System.Globalization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Security;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary><c>/api/v1/auth</c>: sign-in (token or admin cookie), sign-out, password change, current account.</summary>
|
||||
public static class AuthEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
api.MapPost("/auth/login", LoginAsync).AllowAnonymousCaller();
|
||||
api.MapPost("/auth/logout", LogoutAsync).AllowDuringPasswordChange();
|
||||
api.MapPost("/auth/password", ChangePasswordAsync).AllowDuringPasswordChange();
|
||||
api.MapGet("/auth/me", (Caller caller) => Results.Json(Dto.User(caller.User), ProtocolJson.Default.UserDto)).AllowDuringPasswordChange();
|
||||
}
|
||||
|
||||
private static async Task<IResult> LoginAsync(HttpContext context, LoginRequest request, TitanoDatabase db, TokenService tokens, LoginGuard guard,
|
||||
AuditLog audit, TimeProvider time)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (!guard.TryAttempt(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", out var wait)) return TooMany(context, "rate_limited", wait);
|
||||
var account = Accounts.Key(request.Username);
|
||||
if (!Accounts.IsValidUsername(account) || string.IsNullOrEmpty(request.Password))
|
||||
return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials");
|
||||
if (guard.IsLocked(account, out wait)) return TooMany(context, "account_locked", wait);
|
||||
if (request.Cookie && !SessionCookies.IsSecureTransport(context)) return ApiErrors.BadRequest(context, "https_required");
|
||||
|
||||
var user = await db.Users.GetByUsernameAsync(account, ct);
|
||||
bool valid;
|
||||
if (user is null)
|
||||
{
|
||||
PasswordHasher.VerifyDummy(request.Password);
|
||||
valid = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
valid = PasswordHasher.Verify(request.Password, user.PasswordHash) && !user.Disabled;
|
||||
}
|
||||
if (!valid)
|
||||
{
|
||||
guard.RecordFailure(account);
|
||||
await audit.WriteAsync(user?.Id, account, context, "login_failed", "user", user?.Id.ToString());
|
||||
return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials");
|
||||
}
|
||||
|
||||
guard.RecordSuccess(account);
|
||||
var signedIn = user! with { LastLogin = time.GetUtcNow() };
|
||||
if (PasswordHasher.NeedsRehash(signedIn.PasswordHash))
|
||||
{
|
||||
signedIn = signedIn with { PasswordHash = PasswordHasher.Hash(request.Password) };
|
||||
await db.Users.UpdateAsync(signedIn, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
await db.Users.RecordLoginAsync(signedIn.Id, signedIn.LastLogin.Value, ct);
|
||||
}
|
||||
var issued = await tokens.IssueAsync(signedIn, request.ClientName, ct);
|
||||
await audit.WriteAsync(signedIn.Id, signedIn.Username, context, "login", "user", signedIn.Id.ToString(), issued.Stored.ClientName);
|
||||
|
||||
string? secret = issued.Secret;
|
||||
if (request.Cookie)
|
||||
{
|
||||
// The admin panel never sees the token itself; it travels only in the HttpOnly cookie.
|
||||
SessionCookies.Issue(context, issued);
|
||||
secret = null;
|
||||
}
|
||||
return Results.Json(new LoginResponse(secret, Dto.User(signedIn), signedIn.MustChangePassword, issued.Stored.Expires), ProtocolJson.Default.LoginResponse);
|
||||
}
|
||||
|
||||
private static async Task<IResult> LogoutAsync(HttpContext context, Caller caller, TitanoDatabase db)
|
||||
{
|
||||
await db.Tokens.RevokeAsync(caller.TokenHash, context.RequestAborted);
|
||||
if (caller.Source == CredentialSource.Cookie) SessionCookies.Clear(context);
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
private static async Task<IResult> ChangePasswordAsync(HttpContext context, Caller caller, ChangePasswordRequest request, TitanoDatabase db,
|
||||
AuditLog audit, ServerOptions options)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (string.IsNullOrEmpty(request.CurrentPassword) || !PasswordHasher.Verify(request.CurrentPassword, caller.User.PasswordHash))
|
||||
return ApiErrors.BadRequest(context, "wrong_password");
|
||||
if (!PasswordHasher.IsAcceptable(request.NewPassword))
|
||||
return ApiErrors.BadRequest(context, "weak_password", PasswordHasher.MinimumLength.ToString(CultureInfo.InvariantCulture), PasswordHasher.MinimumLength);
|
||||
if (request.NewPassword == request.CurrentPassword) return ApiErrors.BadRequest(context, "same_password");
|
||||
|
||||
var updated = caller.User with { PasswordHash = PasswordHasher.Hash(request.NewPassword), MustChangePassword = false };
|
||||
await db.Users.UpdateAsync(updated, ct);
|
||||
await db.Tokens.RevokeAllExceptAsync(caller.Id, caller.TokenHash, ct);
|
||||
await audit.WriteAsync(caller, context, "password_changed", "user", caller.Id.ToString());
|
||||
if (caller.User.Role == UserRole.Admin) AdminBootstrap.ForgetInitialPassword(options);
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
private static IResult TooMany(HttpContext context, string code, TimeSpan wait)
|
||||
{
|
||||
var seconds = Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds));
|
||||
context.Response.Headers.RetryAfter = seconds.ToString(CultureInfo.InvariantCulture);
|
||||
return ApiErrors.Result(context, StatusCodes.Status429TooManyRequests, code, seconds.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Protocol;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>Domain entities → API v1 contracts.</summary>
|
||||
public static class Dto
|
||||
{
|
||||
public static UserDto User(User u) => new(
|
||||
u.Id, u.Username, u.DisplayName, Role(u.Role), (long)u.Permissions, u.QuotaBytes, u.UsedBytes, u.Disabled, u.MustChangePassword,
|
||||
u.Created, u.LastLogin);
|
||||
|
||||
public static string Role(UserRole role) => role.ToString().ToLowerInvariant();
|
||||
|
||||
public static SequenceDto Sequence(Sequence s) => new(
|
||||
s.Id, s.Title, s.DisplayTitle, s.Folder, s.CameraMake, s.CameraModel, s.Lens, s.FirstCapture, s.LastCapture, s.FrameCount,
|
||||
s.MedianInterval, s.TotalBytes, (long)s.Status, s.RenderedCount, s.HeroFrameId, s.Tags, s.Rating, s.Notes, s.SettingsVersion,
|
||||
s.FramesVersion, s.WarningCount, s.OwnerUserId, s.UpdatedAt);
|
||||
|
||||
public static FrameDto Frame(Frame f) => new(
|
||||
f.Id, f.SequenceId, f.Index, f.FileName, f.Size, f.Sha256, f.CapturedAt, f.UtcOffsetMinutes, f.ExposureTime, f.FNumber, f.Iso,
|
||||
f.FocalLength, f.Orientation, f.Width, f.Height, f.Format.ToString().ToLowerInvariant(), (long)f.Flags);
|
||||
|
||||
public static RenderDto Render(Render r) => new(r.Id, r.PresetName, r.Codec, r.Width, r.Height, r.Fps, r.DurationSeconds, r.Bytes, r.Created, r.ProducedBy);
|
||||
|
||||
public static JobDto Job(Job j) => new(
|
||||
j.Id, JobWire.Kind(j.Kind), j.TargetIds, j.TargetLabel, JobWire.State(j.State), JobWire.Priority(j.Priority), j.ProgressDone,
|
||||
j.ProgressTotal, j.ItemsPerSecond, j.Eta?.TotalSeconds, j.LogTail, j.NodeId, j.Attempts, j.Error, j.Created, j.Started, j.Finished);
|
||||
|
||||
public static AuditEntryDto Audit(AuditEntry a) => new(a.Id, a.At, a.UserId, a.Username, a.Action, a.TargetKind, a.TargetId, a.Details, a.RemoteAddress);
|
||||
|
||||
public static RenderNodeDto Node(RenderNode node, string username) =>
|
||||
new(node.Id, node.ClientName, username, Capabilities(node)?.Encoders ?? [], node.LastHeartbeat, node.State);
|
||||
|
||||
/// <summary>What a node announced at registration (stored as its capabilities JSON).</summary>
|
||||
public static RegisterNodeRequest? Capabilities(RenderNode node)
|
||||
{
|
||||
if (node.CapabilitiesJson is null) return null;
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(node.CapabilitiesJson, ProtocolJson.Default.RegisterNodeRequest);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Wire names of job kinds, states and priorities: kebab-case (<c>deep-analyse</c>) and lower-case (<c>running</c>).</summary>
|
||||
public static class JobWire
|
||||
{
|
||||
public static string Kind(JobKind kind)
|
||||
{
|
||||
var name = kind.ToString();
|
||||
var sb = new StringBuilder(name.Length + 4);
|
||||
for (var i = 0; i < name.Length; i++)
|
||||
{
|
||||
if (i > 0 && char.IsUpper(name[i])) sb.Append('-');
|
||||
sb.Append(char.ToLowerInvariant(name[i]));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static bool TryParseKind(string? text, out JobKind kind) => TryParse(text, Kind, out kind);
|
||||
|
||||
public static string State(JobState state) => state.ToString().ToLowerInvariant();
|
||||
|
||||
public static bool TryParseState(string? text, out JobState state) => TryParse(text, State, out state);
|
||||
|
||||
public static string Priority(JobPriority priority) => priority.ToString().ToLowerInvariant();
|
||||
|
||||
public static bool TryParsePriority(string? text, out JobPriority priority) => TryParse(text, Priority, out priority);
|
||||
|
||||
private static bool TryParse<T>(string? text, Func<T, string> name, out T value) where T : struct, Enum
|
||||
{
|
||||
foreach (var candidate in Enum.GetValues<T>())
|
||||
{
|
||||
if (string.Equals(name(candidate), text, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Globalization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Streamed archive files with Range support (BRIEF §14.3): originals, proxies, thumbnails and exports. Paths come
|
||||
/// from the database by id and are resolved under the archive root only.
|
||||
/// </summary>
|
||||
public static class FileEndpoints
|
||||
{
|
||||
private const string Immutable = "private, max-age=31536000, immutable";
|
||||
private const string Regenerable = "private, max-age=3600";
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
// Originals feed editing clients and render nodes; viewers browse proxies, thumbnails and exports.
|
||||
api.MapGet("/frames/{id:guid}/original", OriginalAsync).Requires(Permissions.Edit | Permissions.RenderNode);
|
||||
api.MapGet("/frames/{id:guid}/proxy", (HttpContext c, Guid id, TitanoDatabase db, ServerArchive a, IFrameAssetLocator l) => AssetAsync(c, id, FrameAsset.Proxy, db, a, l))
|
||||
.Requires(Permissions.Read | Permissions.RenderNode);
|
||||
api.MapGet("/frames/{id:guid}/thumb", (HttpContext c, Guid id, TitanoDatabase db, ServerArchive a, IFrameAssetLocator l) => AssetAsync(c, id, FrameAsset.Thumbnail, db, a, l))
|
||||
.Requires(Permissions.Read);
|
||||
api.MapGet("/renders/{id:guid}/file", RenderAsync).Requires(Permissions.Read);
|
||||
}
|
||||
|
||||
private static async Task<IResult> OriginalAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive)
|
||||
{
|
||||
if (await db.Frames.GetAsync(id, context.RequestAborted) is not { } frame) return ApiErrors.NotFound(context, "frame");
|
||||
if (ArchivePaths.ExistingFile(archive.Root, frame.RelativePath) is not { } file) return ApiErrors.NotFound(context, "file_missing");
|
||||
return FileResponses.Serve(context, file, 0, file.Length, FileResponses.ContentTypeOf(frame.FileName), Immutable, frame.Sha256, frame.FileName)
|
||||
?? ApiErrors.NotFound(context, "file_missing");
|
||||
}
|
||||
|
||||
private static async Task<IResult> AssetAsync(HttpContext context, Guid id, FrameAsset kind, TitanoDatabase db, ServerArchive archive, IFrameAssetLocator locator)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Frames.GetAsync(id, ct) is not { } frame || await db.Sequences.GetAsync(frame.SequenceId, ct) is not { } sequence)
|
||||
return ApiErrors.NotFound(context, "frame");
|
||||
var location = await locator.LocateAsync(archive.Current, sequence, frame, kind, ct);
|
||||
if (location is null || !ArchivePaths.IsInside(archive.Root, location.Path)) return ApiErrors.NotFound(context, "asset_missing");
|
||||
var file = new FileInfo(location.Path);
|
||||
if (!file.Exists || file.LinkTarget is not null) return ApiErrors.NotFound(context, "asset_missing");
|
||||
var etag = string.Create(CultureInfo.InvariantCulture, $"{kind}-{frame.Id:N}-{file.LastWriteTimeUtc.Ticks}-{location.Offset}");
|
||||
return FileResponses.Serve(context, file, location.Offset, location.Length, location.ContentType, Regenerable, etag)
|
||||
?? ApiErrors.NotFound(context, "asset_missing");
|
||||
}
|
||||
|
||||
private static async Task<IResult> RenderAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive)
|
||||
{
|
||||
if (await db.Renders.GetAsync(id, context.RequestAborted) is not { } render) return ApiErrors.NotFound(context, "render");
|
||||
if (ArchivePaths.ExistingFile(archive.Root, render.OutputPath) is not { } file) return ApiErrors.NotFound(context, "file_missing");
|
||||
var etag = string.Create(CultureInfo.InvariantCulture, $"r-{render.Id:N}-{file.Length}-{file.LastWriteTimeUtc.Ticks}");
|
||||
return FileResponses.Serve(context, file, 0, file.Length, FileResponses.ContentTypeOf(file.Name), Immutable, etag, file.Name)
|
||||
?? ApiErrors.NotFound(context, "file_missing");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/jobs</c> (BRIEF §14.6): queue and history, creation, cancel, pause, resume, retry and priority. Changes
|
||||
/// reach WebSocket clients as <c>jobState</c> and <c>jobProgress</c> events.
|
||||
/// </summary>
|
||||
public static class JobEndpoints
|
||||
{
|
||||
/// <summary>Kinds that work on sequences (targets are sequence ids) and need the edit right.</summary>
|
||||
private static readonly HashSet<JobKind> SequenceKinds = [JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Proxies, JobKind.Thumbs, JobKind.Verify];
|
||||
|
||||
/// <summary>Archive-wide maintenance (target: the archive) for administrators.</summary>
|
||||
private static readonly HashSet<JobKind> ArchiveKinds = [JobKind.Scan, JobKind.Rebuild, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans];
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var jobs = api.MapGroup("/jobs").Requires(Permissions.Read);
|
||||
jobs.MapGet("", ListAsync);
|
||||
jobs.MapPost("", CreateAsync);
|
||||
jobs.MapGet("/{id:guid}", async (HttpContext context, Guid id, TitanoDatabase db) =>
|
||||
await db.Jobs.GetAsync(id, context.RequestAborted) is { } job
|
||||
? Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto)
|
||||
: ApiErrors.NotFound(context, "job"));
|
||||
jobs.MapPost("/{id:guid}/cancel", (HttpContext c, Caller caller, Guid id, TitanoDatabase db, JobEngineHost host) =>
|
||||
ActAsync(c, caller, id, db, [JobState.Queued, JobState.Running, JobState.Paused], (job, ct) => host.Engine.CancelAsync(job.Id, ct)));
|
||||
jobs.MapPost("/{id:guid}/pause", (HttpContext c, Caller caller, Guid id, TitanoDatabase db, JobEngineHost host) =>
|
||||
ActAsync(c, caller, id, db, [JobState.Queued, JobState.Running], (job, ct) => host.Engine.PauseAsync(job.Id, ct)));
|
||||
jobs.MapPost("/{id:guid}/resume", (HttpContext c, Caller caller, Guid id, TitanoDatabase db, JobEngineHost host) =>
|
||||
ActAsync(c, caller, id, db, [JobState.Paused], (job, ct) => host.Engine.ResumeAsync(job.Id, ct)));
|
||||
jobs.MapPost("/{id:guid}/retry", (HttpContext c, Caller caller, Guid id, TitanoDatabase db, JobEngineHost host) =>
|
||||
ActAsync(c, caller, id, db, [JobState.Failed, JobState.Cancelled], (job, ct) => host.Engine.ResumeAsync(job.Id, ct)));
|
||||
jobs.MapPost("/{id:guid}/priority", PriorityAsync);
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAsync(HttpContext context, TitanoDatabase db, string? state, string? kind, string? cursor, int? limit)
|
||||
{
|
||||
JobState? stateFilter = null;
|
||||
JobKind? kindFilter = null;
|
||||
if (!string.IsNullOrEmpty(state))
|
||||
{
|
||||
if (!JobWire.TryParseState(state, out var s)) return ApiErrors.BadRequest(context, "invalid_filter", "state");
|
||||
stateFilter = s;
|
||||
}
|
||||
if (!string.IsNullOrEmpty(kind))
|
||||
{
|
||||
if (!JobWire.TryParseKind(kind, out var k)) return ApiErrors.BadRequest(context, "invalid_filter", "kind");
|
||||
kindFilter = k;
|
||||
}
|
||||
var page = await db.Jobs.ListAsync(stateFilter, kindFilter, limit ?? 50, string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted);
|
||||
return Results.Json(new Page<JobDto>([.. page.Items.Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, TitanoDatabase db, JobEngineHost host,
|
||||
ServerArchive archive, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (!JobWire.TryParseKind(request.Kind, out var kind) || !(kind == JobKind.Render || SequenceKinds.Contains(kind) || ArchiveKinds.Contains(kind)))
|
||||
return ApiErrors.BadRequest(context, "invalid_job_kind");
|
||||
var needed = kind == JobKind.Render ? Permissions.Render : SequenceKinds.Contains(kind) ? Permissions.Edit : Permissions.ManageArchive;
|
||||
if (!caller.Has(needed)) return ApiErrors.Forbidden(context);
|
||||
if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind));
|
||||
|
||||
IReadOnlyList<Guid> targets;
|
||||
string label;
|
||||
if (ArchiveKinds.Contains(kind))
|
||||
{
|
||||
targets = [archive.Id];
|
||||
label = archive.Current.Name;
|
||||
}
|
||||
else
|
||||
{
|
||||
var ids = request.Target ?? [];
|
||||
if (ids.Count == 0 || (kind == JobKind.Render && ids.Count != 1)) return ApiErrors.BadRequest(context, "invalid_parameters", "target");
|
||||
var titles = new List<string>(ids.Count);
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
titles.Add(sequence.DisplayTitle);
|
||||
}
|
||||
targets = ids;
|
||||
label = titles.Count == 1 ? titles[0] : string.Join(", ", titles.Take(3)) + (titles.Count > 3 ? " …" : string.Empty);
|
||||
}
|
||||
if (kind == JobKind.Render)
|
||||
{
|
||||
if (ParseRender(request.ParametersJson) is not { } render) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
|
||||
label = $"{label} → {render.PresetName}";
|
||||
}
|
||||
else if (request.ParametersJson is not null && !IsJsonObject(request.ParametersJson))
|
||||
{
|
||||
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
|
||||
}
|
||||
|
||||
var job = await host.Engine.EnqueueAsync(kind, targets, label, request.ParametersJson, JobPriority.User, caller.Id, ct);
|
||||
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {label}");
|
||||
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
private static async Task<IResult> PriorityAsync(HttpContext context, Caller caller, Guid id, JobPriorityRequest request, TitanoDatabase db, JobEngineHost host)
|
||||
{
|
||||
if (!JobWire.TryParsePriority(request.Priority, out var priority)) return ApiErrors.BadRequest(context, "invalid_priority");
|
||||
return await ActAsync(context, caller, id, db, [JobState.Queued, JobState.Paused], async (job, ct) =>
|
||||
{
|
||||
await db.Jobs.SetPriorityAsync(job.Id, priority, ct);
|
||||
host.Publish(job with { Priority = priority });
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Applies <paramref name="action"/> when the job is in one of <paramref name="allowed"/> states and the caller created it or administers the archive.</summary>
|
||||
private static async Task<IResult> ActAsync(HttpContext context, Caller caller, Guid id, TitanoDatabase db, JobState[] allowed, Func<Job, CancellationToken, Task> action)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Jobs.GetAsync(id, ct) is not { } job) return ApiErrors.NotFound(context, "job");
|
||||
if (job.CreatedBy != caller.Id && !caller.Has(Permissions.ManageArchive)) return ApiErrors.Forbidden(context);
|
||||
if (!allowed.Contains(job.State)) return ApiErrors.Conflict(context, "invalid_state", JobWire.State(job.State));
|
||||
await action(job, ct);
|
||||
var updated = await db.Jobs.GetAsync(id, ct) ?? job;
|
||||
return Results.Json(Dto.Job(updated), ProtocolJson.Default.JobDto);
|
||||
}
|
||||
|
||||
/// <summary>Render parameters, or null when they are missing or incomplete.</summary>
|
||||
public static RenderJobParameters? ParseRender(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return null;
|
||||
try
|
||||
{
|
||||
var p = JsonSerializer.Deserialize(json, ProtocolJson.Default.RenderJobParameters);
|
||||
return p is { PresetName.Length: > 0, PresetJson.Length: > 0, Codec.Length: > 0, Width: > 0, Height: > 0 } && IsJsonObject(p.PresetJson) ? p : null;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsJsonObject(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
return document.RootElement.ValueKind == JsonValueKind.Object;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Events;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Security;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary><c>/api/v1/nodes</c> (BRIEF §14.7): render node registration, heartbeat, claim, progress, failure and output upload.</summary>
|
||||
public static class NodeEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
api.MapGet("/nodes", ListAsync).Requires(Permissions.Read | Permissions.RenderNode);
|
||||
api.MapDelete("/nodes/{id:guid}", DeleteAsync).Requires(Permissions.RenderNode | Permissions.ManageArchive);
|
||||
|
||||
var nodes = api.MapGroup("/nodes").Requires(Permissions.RenderNode);
|
||||
nodes.MapPost("/register", async (HttpContext c, Caller caller, RegisterNodeRequest request, RenderNodeService service) =>
|
||||
(await service.RegisterAsync(caller, request, c.RequestAborted)).ToResult(c, n => Results.Json(n, ProtocolJson.Default.RenderNodeDto)));
|
||||
nodes.MapPost("/{id:guid}/heartbeat", async (HttpContext c, Caller caller, Guid id, RenderNodeService service) =>
|
||||
(await service.HeartbeatAsync(caller, id, c.RequestAborted)).ToResult(c, _ => Results.NoContent()));
|
||||
nodes.MapPost("/{id:guid}/claim", async (HttpContext c, Caller caller, Guid id, RenderNodeService service) =>
|
||||
(await service.ClaimAsync(caller, id, c.RequestAborted)).ToResult(c, job => job is null ? Results.NoContent() : Results.Json(job, ProtocolJson.Default.ClaimedJob)));
|
||||
nodes.MapPost("/{id:guid}/jobs/{jobId:guid}/progress", async (HttpContext c, Caller caller, Guid id, Guid jobId, NodeProgress progress, RenderNodeService service) =>
|
||||
(await service.ProgressAsync(caller, id, jobId, progress, c.RequestAborted)).ToResult(c, _ => Results.NoContent()));
|
||||
nodes.MapPost("/{id:guid}/jobs/{jobId:guid}/failed", async (HttpContext c, Caller caller, Guid id, Guid jobId, NodeJobFailure failure, RenderNodeService service) =>
|
||||
(await service.FailAsync(caller, id, jobId, failure, c.RequestAborted)).ToResult(c, _ => Results.NoContent()));
|
||||
nodes.MapPost("/{id:guid}/jobs/{jobId:guid}/result", async (HttpContext c, Caller caller, Guid id, Guid jobId, RenderResultRequest request, RenderNodeService service) =>
|
||||
(await service.StartResultAsync(caller, id, jobId, request, c.RequestAborted))
|
||||
.ToResult(c, r => Results.Json(r, ProtocolJson.Default.StartUploadResponse, statusCode: StatusCodes.Status201Created)));
|
||||
nodes.MapPost("/{id:guid}/jobs/{jobId:guid}/result/complete", async (HttpContext c, Caller caller, Guid id, Guid jobId, RenderNodeService service,
|
||||
IHostApplicationLifetime lifetime) =>
|
||||
// The commit runs to the end even if the node disconnects meanwhile.
|
||||
(await service.CompleteResultAsync(caller, id, jobId, lifetime.ApplicationStopping)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.RenderDto)));
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAsync(HttpContext context, TitanoDatabase db)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
var users = (await db.Users.ListAsync(ct)).ToDictionary(u => u.Id, u => u.Username);
|
||||
var nodes = await db.RenderNodes.ListAsync(ct);
|
||||
return Results.Json(nodes.Select(n => Dto.Node(n, users.GetValueOrDefault(n.UserId, string.Empty))).ToList(), ProtocolJson.Default.ListRenderNodeDto);
|
||||
}
|
||||
|
||||
/// <summary>Forgets a node (its owner or an archive admin); its running jobs go back to the queue.</summary>
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, TitanoDatabase db, EventHub events)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.RenderNodes.GetAsync(id, ct) is not { } node) return ApiErrors.NotFound(context, "node");
|
||||
if (node.UserId != caller.Id && !caller.Has(Permissions.ManageArchive)) return ApiErrors.Forbidden(context);
|
||||
await db.Jobs.RequeueRunningAsync(RenderNodeService.NodeKey(node), ct);
|
||||
await db.RenderNodes.DeleteAsync(id, ct);
|
||||
events.Publish(new NodeStateEvent(node.Id, node.ClientName, RenderNodeService.Offline));
|
||||
return Results.NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>Result of a server operation: a value, or an HTTP status with an API error code (and optional details).</summary>
|
||||
public readonly record struct Outcome<T>(T? Value, int Status, string? Code, string? Details)
|
||||
{
|
||||
public bool Succeeded => Code is null;
|
||||
|
||||
public static Outcome<T> Ok(T value) => new(value, StatusCodes.Status200OK, null, null);
|
||||
|
||||
public static Outcome<T> Fail(int status, string code, string? details = null) => new(default, status, code, details);
|
||||
|
||||
/// <summary>The API response: <paramref name="ok"/> for a value, the error body otherwise.</summary>
|
||||
public IResult ToResult(HttpContext context, Func<T, IResult> ok) =>
|
||||
Succeeded ? ok(Value!) : ApiErrors.Result(context, Status, Code!, Details);
|
||||
|
||||
public static implicit operator Outcome<T>(T value) => Ok(value);
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
using System.Buffers.Text;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Events;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/sequences</c>: library listing with filters and keyset paging, detail with ETag, edits with
|
||||
/// <c>settings_version</c> optimistic concurrency, the sync manifest, frames, analysis, statistics and renders.
|
||||
/// </summary>
|
||||
public static class SequenceEndpoints
|
||||
{
|
||||
private const int MaxTitle = 200;
|
||||
private const int MaxNotes = 2000;
|
||||
private const int MaxTags = 50;
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
// Uploaders list sequences to pick an upload target.
|
||||
var sequences = api.MapGroup("/sequences").Requires(Permissions.Read | Permissions.Upload);
|
||||
sequences.MapGet("", ListAsync);
|
||||
sequences.MapPost("", CreateAsync).Requires(Permissions.Upload | Permissions.Edit);
|
||||
sequences.MapGet("/{id:guid}", GetAsync);
|
||||
sequences.MapPatch("/{id:guid}", UpdateAsync).Requires(Permissions.Edit);
|
||||
sequences.MapDelete("/{id:guid}", DeleteAsync).Requires(Permissions.Delete);
|
||||
sequences.MapGet("/{id:guid}/manifest", ManifestAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/frames", FramesAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/analysis", AnalysisAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/stats", StatsAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/renders", RendersAsync).Requires(Permissions.Read);
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, int? year, string? camera, string? status,
|
||||
string? tag, string? q, string? owner, string? sort, string? cursor, int? limit, Caller caller)
|
||||
{
|
||||
if (!TryParseStatus(status, out var with, out var without)) return ApiErrors.BadRequest(context, "invalid_filter", "status");
|
||||
if (!TryParseSort(sort, out var order)) return ApiErrors.BadRequest(context, "invalid_filter", "sort");
|
||||
Guid? ownerId = null;
|
||||
if (owner == "me") ownerId = caller.Id;
|
||||
else if (owner is not null && Guid.TryParse(owner, out var parsed)) ownerId = parsed;
|
||||
else if (owner is not null) return ApiErrors.BadRequest(context, "invalid_filter", "owner");
|
||||
|
||||
var query = new SequenceQuery
|
||||
{
|
||||
ArchiveId = archive.Id,
|
||||
Year = year,
|
||||
Camera = string.IsNullOrWhiteSpace(camera) ? null : camera,
|
||||
WithStatus = with,
|
||||
WithoutStatus = without,
|
||||
Tag = string.IsNullOrWhiteSpace(tag) ? null : tag,
|
||||
Text = string.IsNullOrWhiteSpace(q) ? null : q,
|
||||
OwnerUserId = ownerId,
|
||||
Sort = order,
|
||||
Limit = limit ?? 100,
|
||||
Cursor = string.IsNullOrEmpty(cursor) ? null : cursor,
|
||||
};
|
||||
var page = await db.Sequences.ListAsync(query, context.RequestAborted);
|
||||
long? total = query.Cursor is null ? await db.Sequences.CountAsync(query, context.RequestAborted) : null;
|
||||
return Results.Json(new Titano.Protocol.Page<SequenceDto>([.. page.Items.Select(Dto.Sequence)], page.NextCursor, total), ProtocolJson.Default.PageSequenceDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateSequenceRequest request, TitanoDatabase db, ServerArchive archive,
|
||||
AuditLog audit, EventHub events, TimeProvider time)
|
||||
{
|
||||
var title = request.Title?.Trim();
|
||||
if (title is { Length: > MaxTitle }) return ApiErrors.BadRequest(context, "bad_request", "title");
|
||||
var hint = request.CameraHint?.Trim();
|
||||
var sequence = new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = archive.Id,
|
||||
Title = string.IsNullOrEmpty(title) ? null : title,
|
||||
// Placed in the archive by the ingest when its first frame arrives.
|
||||
Folder = string.Empty,
|
||||
CameraModel = string.IsNullOrEmpty(hint) ? null : hint[..Math.Min(hint.Length, MaxTitle)],
|
||||
Origin = SequenceOrigin.Server,
|
||||
SyncState = SyncState.InSync,
|
||||
OwnerUserId = caller.Id,
|
||||
UpdatedAt = time.GetUtcNow(),
|
||||
};
|
||||
await db.Sequences.UpsertAsync(sequence, context.RequestAborted);
|
||||
await audit.WriteAsync(caller, context, "sequence_created", "sequence", sequence.Id.ToString(), sequence.DisplayTitle);
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "created", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
context.Response.Headers.ETag = ETag(sequence);
|
||||
return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto, statusCode: StatusCodes.Status201Created);
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetAsync(HttpContext context, Guid id, TitanoDatabase db)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
var etag = ETag(sequence);
|
||||
if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified);
|
||||
context.Response.Headers.ETag = etag;
|
||||
return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateSequenceRequest request, TitanoDatabase db,
|
||||
AuditLog audit, EventHub events)
|
||||
{
|
||||
if (request.Title is { Length: > MaxTitle }) return ApiErrors.BadRequest(context, "bad_request", "title");
|
||||
if (request.Notes is { Length: > MaxNotes }) return ApiErrors.BadRequest(context, "bad_request", "notes");
|
||||
if (request.Rating is < 0 or > 5) return ApiErrors.BadRequest(context, "bad_request", "rating");
|
||||
if (request.Tags is { } tags && (tags.Count > MaxTags || tags.Any(t => t is null || t.Trim().Length > TagRepository.MaxLength)))
|
||||
return ApiErrors.BadRequest(context, "bad_request", "tags");
|
||||
if (request.SettingsJson is not null && !IsJson(request.SettingsJson)) return ApiErrors.BadRequest(context, "invalid_settings");
|
||||
|
||||
var expected = request.ExpectedSettingsVersion ?? IfMatchVersion(context);
|
||||
var edit = new SequenceEdit { Title = request.Title, Tags = request.Tags, Rating = request.Rating, Notes = request.Notes, SettingsJson = request.SettingsJson };
|
||||
var result = await db.Sequences.EditAsync(id, edit, expected, context.RequestAborted);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case SequenceEditOutcome.NotFound:
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
case SequenceEditOutcome.Conflict:
|
||||
context.Response.Headers.ETag = ETag(result.Sequence!);
|
||||
return ApiErrors.Conflict(context, "settings_conflict", result.Sequence!.SettingsVersion.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
var sequence = result.Sequence!;
|
||||
await audit.WriteAsync(caller, context, "sequence_updated", "sequence", id.ToString(), Changes(request));
|
||||
events.Publish(new SequenceChangedEvent(id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
context.Response.Headers.ETag = ETag(sequence);
|
||||
return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a sequence from the index and moves its folder into the archive's trash (BRIEF §0.2 rule 8: nothing is
|
||||
/// erased). <c>?dryRun=true</c> only reports what would happen. Owners and admins only.
|
||||
/// </summary>
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db, ServerArchive archive,
|
||||
ServerOptions options, AuditLog audit, EventHub events)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context);
|
||||
var folder = string.IsNullOrEmpty(sequence.Folder) ? null : ArchivePaths.Resolve(archive.Root, sequence.Folder);
|
||||
var trash = Path.Combine(options.TrashPath, id.ToString("N"));
|
||||
var hasFolder = folder is not null && Directory.Exists(folder);
|
||||
var plan = new SequenceDeletePlan(id, sequence.Folder, hasFolder ? Path.GetRelativePath(archive.Root, trash).Replace('\\', '/') : null,
|
||||
sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true);
|
||||
if (dryRun == true) return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
|
||||
|
||||
if (hasFolder)
|
||||
{
|
||||
Directory.CreateDirectory(options.TrashPath);
|
||||
Directory.Move(folder!, trash);
|
||||
}
|
||||
await db.Sequences.DeleteAsync(id, context.RequestAborted);
|
||||
await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", id.ToString(), sequence.DisplayTitle);
|
||||
events.Publish(new SequenceChangedEvent(id, "deleted", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
|
||||
}
|
||||
|
||||
/// <summary>Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5); ETag over the version counters.</summary>
|
||||
private static async Task<IResult> ManifestAsync(HttpContext context, Guid id, TitanoDatabase db)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
var etag = string.Create(CultureInfo.InvariantCulture, $"\"m{sequence.SettingsVersion}-{sequence.FramesVersion}-{sequence.RenderedCount}\"");
|
||||
if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified);
|
||||
|
||||
var hasProxy = sequence.Status.HasFlag(SequenceStatus.ProxiesBuilt);
|
||||
var hasThumb = sequence.Status.HasFlag(SequenceStatus.ThumbsBuilt);
|
||||
var frames = new List<ManifestFrame>(sequence.FrameCount);
|
||||
var after = -1;
|
||||
while (true)
|
||||
{
|
||||
var batch = await db.Frames.ListBySequenceAsync(id, after, 1000, ct);
|
||||
frames.AddRange(batch.Select(f => new ManifestFrame(f.Id, f.Index, f.FileName, f.Size, f.Sha256 ?? string.Empty, hasProxy, hasThumb)));
|
||||
if (batch.Count < 1000) break;
|
||||
after = batch[^1].Index;
|
||||
}
|
||||
var renders = await db.Renders.ListBySequenceAsync(id, ct);
|
||||
context.Response.Headers.ETag = etag;
|
||||
return Results.Json(new SequenceManifest(id, sequence.FramesVersion, sequence.SettingsVersion, sequence.SettingsJson, sequence.Tags, frames,
|
||||
[.. renders.Select(Dto.Render)]), ProtocolJson.Default.SequenceManifest);
|
||||
}
|
||||
|
||||
private static async Task<IResult> FramesAsync(HttpContext context, Guid id, string? cursor, int? limit, TitanoDatabase db)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Sequences.GetAsync(id, ct) is null) return ApiErrors.NotFound(context, "sequence");
|
||||
var after = -1;
|
||||
if (!string.IsNullOrEmpty(cursor) && !FrameCursor.TryDecode(cursor, out after)) return ApiErrors.BadRequest(context, "invalid_cursor");
|
||||
var take = Math.Clamp(limit ?? 500, 1, 1000);
|
||||
var frames = await db.Frames.ListBySequenceAsync(id, after, take, ct);
|
||||
var next = frames.Count == take ? FrameCursor.Encode(frames[^1].Index) : null;
|
||||
return Results.Json(new Titano.Protocol.Page<FrameDto>([.. frames.Select(Dto.Frame)], next, null), ProtocolJson.Default.PageFrameDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> AnalysisAsync(HttpContext context, Guid id, TitanoDatabase db) =>
|
||||
await db.Sequences.GetAsync(id, context.RequestAborted) switch
|
||||
{
|
||||
null => ApiErrors.NotFound(context, "sequence"),
|
||||
{ AnalysisJson: { } json } => Results.Text(json, "application/json; charset=utf-8"),
|
||||
_ => ApiErrors.NotFound(context, "analysis"),
|
||||
};
|
||||
|
||||
private static async Task<IResult> StatsAsync(HttpContext context, Guid id, TitanoDatabase db)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } s) return ApiErrors.NotFound(context, "sequence");
|
||||
var stats = await db.Frames.GetSequenceStatsAsync(id, context.RequestAborted);
|
||||
return Results.Json(new SequenceStatsDto(
|
||||
id, s.FrameCount, s.TotalBytes, s.FirstCapture, s.LastCapture, s.MedianInterval,
|
||||
[.. stats.ByFormat.Select(f => new KeyValueCount(f.Format.ToString().ToLowerInvariant(), f.Photos, f.Bytes))],
|
||||
stats.Missing, stats.Corrupt, stats.Duplicate, stats.Excluded), ProtocolJson.Default.SequenceStatsDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> RendersAsync(HttpContext context, Guid id, TitanoDatabase db)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is null) return ApiErrors.NotFound(context, "sequence");
|
||||
var renders = await db.Renders.ListBySequenceAsync(id, context.RequestAborted);
|
||||
return Results.Json(renders.Select(Dto.Render).ToList(), ProtocolJson.Default.ListRenderDto);
|
||||
}
|
||||
|
||||
/// <summary>Changes whenever anything the sequence representation shows changes (versions, status, statistics).</summary>
|
||||
private static string ETag(Sequence s) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"\"{s.SettingsVersion}-{s.FramesVersion}-{s.UpdatedAt.UtcTicks}\"");
|
||||
|
||||
/// <summary>The settings version named by an <c>If-Match</c> ETag of <see cref="ETag"/>, if any.</summary>
|
||||
private static int? IfMatchVersion(HttpContext context)
|
||||
{
|
||||
var header = context.Request.Headers.IfMatch.ToString().Trim('"', ' ');
|
||||
var dash = header.IndexOf('-', StringComparison.Ordinal);
|
||||
return dash > 0 && int.TryParse(header.AsSpan(0, dash), NumberStyles.None, CultureInfo.InvariantCulture, out var version) ? version : null;
|
||||
}
|
||||
|
||||
private static bool TryParseStatus(string? text, out SequenceStatus with, out SequenceStatus without)
|
||||
{
|
||||
with = without = SequenceStatus.None;
|
||||
if (string.IsNullOrWhiteSpace(text)) return true;
|
||||
foreach (var part in text.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
var clear = part.StartsWith('-');
|
||||
var name = clear ? part[1..] : part;
|
||||
var flag = Enum.GetValues<SequenceStatus>().FirstOrDefault(v => v != SequenceStatus.None && v.ToString().Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (flag == SequenceStatus.None) return false;
|
||||
if (clear) without |= flag;
|
||||
else with |= flag;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryParseSort(string? text, out SequenceSort sort)
|
||||
{
|
||||
sort = SequenceSort.Newest;
|
||||
if (string.IsNullOrEmpty(text)) return true;
|
||||
foreach (var candidate in Enum.GetValues<SequenceSort>())
|
||||
{
|
||||
if (candidate.ToString().Equals(text, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
sort = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsJson(string text)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var _ = JsonDocument.Parse(text);
|
||||
return true;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Changes(UpdateSequenceRequest r)
|
||||
{
|
||||
var fields = new List<string>();
|
||||
if (r.Title is not null) fields.Add("title");
|
||||
if (r.Tags is not null) fields.Add("tags");
|
||||
if (r.Rating is not null) fields.Add("rating");
|
||||
if (r.Notes is not null) fields.Add("notes");
|
||||
if (r.SettingsJson is not null) fields.Add("settings");
|
||||
return string.Join(", ", fields);
|
||||
}
|
||||
|
||||
/// <summary>Opaque cursor of the frame listing: the index of the last frame returned.</summary>
|
||||
private static class FrameCursor
|
||||
{
|
||||
private const string Prefix = "frames|";
|
||||
|
||||
public static string Encode(int index) =>
|
||||
Base64Url.EncodeToString(Encoding.UTF8.GetBytes(Prefix + index.ToString(CultureInfo.InvariantCulture)));
|
||||
|
||||
public static bool TryDecode(string cursor, out int index)
|
||||
{
|
||||
index = -1;
|
||||
try
|
||||
{
|
||||
var text = Encoding.UTF8.GetString(Base64Url.DecodeFromChars(cursor));
|
||||
return text.StartsWith(Prefix, StringComparison.Ordinal)
|
||||
&& int.TryParse(text.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out index);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +1,48 @@
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Security;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary><c>/health</c>, <c>/api/v1/server/info</c> and <c>/api/v1/i18n/{culture}</c>.</summary>
|
||||
/// <summary><c>/health</c>, <c>/api/v1/server/info</c> and <c>/api/v1/i18n/{culture}</c> (all anonymous).</summary>
|
||||
public static class SystemEndpoints
|
||||
{
|
||||
private static readonly string[] AdminAreas = ["Common", "Admin"];
|
||||
|
||||
/// <summary>Languages with translated resources (English plus every satellite of the catalog), for the admin language menu.</summary>
|
||||
private static readonly Lazy<string> AdminLanguages = new(() => string.Join(',', Languages.Shipped.Where(code =>
|
||||
{
|
||||
if (code == "en") return true;
|
||||
try
|
||||
{
|
||||
typeof(Loc).Assembly.GetSatelliteAssembly(CultureInfo.GetCultureInfo(code));
|
||||
return true;
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
})));
|
||||
|
||||
public static string Version { get; } =
|
||||
typeof(SystemEndpoints).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
public static void Map(WebApplication app, ServerOptions options, ServerState state)
|
||||
public static void Map(WebApplication app, RouteGroupBuilder api)
|
||||
{
|
||||
app.MapGet("/health", () =>
|
||||
{
|
||||
var checks = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing",
|
||||
["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing",
|
||||
};
|
||||
return Results.Json(new HealthStatus("ok", Version, checks), ProtocolJson.Default.HealthStatus);
|
||||
});
|
||||
app.MapGet("/health", HealthAsync);
|
||||
|
||||
var api = app.MapGroup("/api/v1");
|
||||
api.MapGet("/server/info", () => Results.Json(new ServerInfo(
|
||||
api.MapGet("/server/info", (ServerOptions options, ServerState state) => Results.Json(new ServerInfo(
|
||||
options.ServerName,
|
||||
Version,
|
||||
ApiVersion.Current,
|
||||
state.Capabilities,
|
||||
state.TlsFingerprint,
|
||||
["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"],
|
||||
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes)), ProtocolJson.Default.ServerInfo));
|
||||
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength)), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller();
|
||||
|
||||
api.MapGet("/i18n/{culture}", (string culture) =>
|
||||
{
|
||||
@@ -52,15 +60,46 @@ public static class SystemEndpoints
|
||||
foreach (var (k, v) in Loc.GetArea(area, ci)) strings[k] = v;
|
||||
strings["$culture"] = ci.Name;
|
||||
strings["$rtl"] = ci.TextInfo.IsRightToLeft ? "true" : "false";
|
||||
strings["$languages"] = AdminLanguages.Value;
|
||||
return Results.Json(strings, ProtocolJson.Default.DictionaryStringString);
|
||||
});
|
||||
}).AllowAnonymousCaller();
|
||||
}
|
||||
|
||||
/// <summary>Liveness for the container health check: 503 while the database cannot be reached.</summary>
|
||||
private static async Task<IResult> HealthAsync(HttpContext context, ServerOptions options, TitanoDatabase db)
|
||||
{
|
||||
var checks = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing",
|
||||
["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing",
|
||||
};
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(3));
|
||||
try
|
||||
{
|
||||
await using var session = await db.Database.OpenAsync(timeout.Token);
|
||||
await session.ExecuteAsync("SELECT 1", [], timeout.Token);
|
||||
checks["database"] = "ok";
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or OperationCanceledException or IOException)
|
||||
{
|
||||
checks["database"] = "unavailable";
|
||||
}
|
||||
var healthy = checks["database"] == "ok";
|
||||
return Results.Json(new HealthStatus(healthy ? "ok" : "unavailable", Version, checks), ProtocolJson.Default.HealthStatus,
|
||||
statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Process-wide facts computed at startup.</summary>
|
||||
public sealed class ServerState
|
||||
{
|
||||
public string? TlsFingerprint { get; set; }
|
||||
public string? TlsFingerprint { get; init; }
|
||||
|
||||
/// <summary>Engine and version of the database ("PostgreSQL 17.2", "SQLite 3.45.1").</summary>
|
||||
public string Database { get; init; } = string.Empty;
|
||||
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events"];
|
||||
|
||||
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/uploads</c> (BRIEF §14.4). Chunk, state and cancel calls also serve render nodes uploading their output,
|
||||
/// which start and complete through the node endpoints.
|
||||
/// </summary>
|
||||
public static class UploadEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var uploads = api.MapGroup("/uploads").Requires(Permissions.Upload | Permissions.RenderNode);
|
||||
uploads.MapPost("", StartAsync).Requires(Permissions.Upload);
|
||||
uploads.MapPut("/{id:guid}/chunks/{index:int}", ChunkAsync);
|
||||
uploads.MapGet("/{id:guid}", async (HttpContext context, Caller caller, Guid id, UploadService service) =>
|
||||
(await service.GetStateAsync(caller, id, context.RequestAborted)).ToResult(context, s => Results.Json(s, ProtocolJson.Default.UploadState)));
|
||||
uploads.MapDelete("/{id:guid}", async (HttpContext context, Caller caller, Guid id, UploadService service) =>
|
||||
(await service.CancelAsync(caller, id, context.RequestAborted)).ToResult(context, _ => Results.NoContent()));
|
||||
uploads.MapPost("/{id:guid}/complete", async (HttpContext context, Caller caller, Guid id, UploadService service) =>
|
||||
(await service.CompleteAsync(caller, id)).ToResult(context, r => Results.Json(r, ProtocolJson.Default.CompleteUploadResponse)))
|
||||
.Requires(Permissions.Upload);
|
||||
}
|
||||
|
||||
private static async Task<IResult> StartAsync(HttpContext context, Caller caller, StartUploadRequest request, UploadService service)
|
||||
{
|
||||
var outcome = await service.StartAsync(caller, request, context.RequestAborted);
|
||||
return outcome.ToResult(context, r => Results.Json(r, ProtocolJson.Default.StartUploadResponse,
|
||||
statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created));
|
||||
}
|
||||
|
||||
private static async Task<IResult> ChunkAsync(HttpContext context, Caller caller, Guid id, int index, UploadService service, ServerOptions options)
|
||||
{
|
||||
// Chunks are the only large request bodies; every other endpoint keeps Kestrel's small default limit.
|
||||
if (context.Features.Get<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } limit) limit.MaxRequestBodySize = options.ChunkSizeBytes;
|
||||
var outcome = await service.ReceiveChunkAsync(caller, id, index, context.Request, context.RequestAborted);
|
||||
return outcome.ToResult(context, r => Results.Json(r, ProtocolJson.Default.ChunkReceived));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Globalization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Security;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary><c>/api/v1/users</c> (admin): accounts, roles, quotas, render-node right, temporary passwords.</summary>
|
||||
public static class UserEndpoints
|
||||
{
|
||||
private const int MaxDisplayName = 100;
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var users = api.MapGroup("/users").Requires(Permissions.ManageUsers);
|
||||
users.MapGet("", ListAsync);
|
||||
users.MapPost("", CreateAsync);
|
||||
users.MapGet("/{id:guid}", GetAsync);
|
||||
users.MapPatch("/{id:guid}", UpdateAsync);
|
||||
users.MapDelete("/{id:guid}", DeleteAsync);
|
||||
users.MapPost("/{id:guid}/reset-password", ResetPasswordAsync);
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAsync(HttpContext context, TitanoDatabase db, TimeProvider time)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
var users = await db.Users.ListAsync(ct);
|
||||
var latest = await db.Tokens.LatestByUserAsync(ct);
|
||||
var uploads = await db.Uploads.CommittedCountByUserAsync(time.GetUtcNow().AddDays(-30), ct);
|
||||
var rows = users.Select(u =>
|
||||
{
|
||||
var token = latest.GetValueOrDefault(u.Id);
|
||||
return new UserSummaryDto(Dto.User(u), token?.LastUsed ?? u.LastLogin, token?.ClientName, uploads.GetValueOrDefault(u.Id));
|
||||
}).ToList();
|
||||
return Results.Json(rows, ProtocolJson.Default.ListUserSummaryDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetAsync(HttpContext context, Guid id, TitanoDatabase db) =>
|
||||
await db.Users.GetAsync(id, context.RequestAborted) is { } user
|
||||
? Results.Json(Dto.User(user), ProtocolJson.Default.UserDto)
|
||||
: ApiErrors.NotFound(context, "user");
|
||||
|
||||
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateUserRequest request, TitanoDatabase db, AuditLog audit, TimeProvider time)
|
||||
{
|
||||
var username = request.Username?.Trim();
|
||||
if (!Accounts.IsValidUsername(username)) return ApiErrors.BadRequest(context, "invalid_username");
|
||||
if (!Accounts.TryParseRole(request.Role, out var role)) return ApiErrors.BadRequest(context, "invalid_role");
|
||||
if (request.QuotaBytes < 0) return ApiErrors.BadRequest(context, "bad_request", "quotaBytes");
|
||||
var password = string.IsNullOrEmpty(request.Password) ? TemporaryPassword.Generate() : request.Password;
|
||||
if (!PasswordHasher.IsAcceptable(password)) return WeakPassword(context);
|
||||
|
||||
var user = new User
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Username = username!,
|
||||
DisplayName = Clean(request.DisplayName),
|
||||
PasswordHash = PasswordHasher.Hash(password),
|
||||
Role = role,
|
||||
Permissions = Accounts.PermissionsFor(role, request.AllowRenderNode),
|
||||
QuotaBytes = request.QuotaBytes,
|
||||
MustChangePassword = true,
|
||||
Created = time.GetUtcNow(),
|
||||
};
|
||||
try
|
||||
{
|
||||
await db.Users.CreateAsync(user, context.RequestAborted);
|
||||
}
|
||||
catch (DatabaseException ex) when (ex.IsUniqueViolation)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "username_taken");
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "user_created", "user", user.Id.ToString(), $"{user.Username} · {Dto.Role(role)}");
|
||||
return Results.Json(new TemporaryPasswordResponse(Dto.User(user), password), ProtocolJson.Default.TemporaryPasswordResponse, statusCode: StatusCodes.Status201Created);
|
||||
}
|
||||
|
||||
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateUserRequest request, TitanoDatabase db, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user");
|
||||
var role = user.Role;
|
||||
if (request.Role is not null && !Accounts.TryParseRole(request.Role, out role)) return ApiErrors.BadRequest(context, "invalid_role");
|
||||
if (request.QuotaBytes < 0) return ApiErrors.BadRequest(context, "bad_request", "quotaBytes");
|
||||
var updated = user with
|
||||
{
|
||||
DisplayName = request.DisplayName is null ? user.DisplayName : Clean(request.DisplayName),
|
||||
Role = role,
|
||||
Permissions = Accounts.PermissionsFor(role, request.AllowRenderNode ?? user.Permissions.HasFlag(Permissions.RenderNode)),
|
||||
QuotaBytes = request.QuotaBytes ?? user.QuotaBytes,
|
||||
Disabled = request.Disabled ?? user.Disabled,
|
||||
};
|
||||
var losesAdmin = IsActiveAdmin(user) && !IsActiveAdmin(updated);
|
||||
if (losesAdmin && user.Id == caller.Id) return ApiErrors.Conflict(context, "self");
|
||||
if (losesAdmin && !await HasOtherActiveAdminAsync(db, user.Id, ct)) return ApiErrors.Conflict(context, "last_admin");
|
||||
|
||||
await db.Users.UpdateAsync(updated, ct);
|
||||
if (updated.Disabled && !user.Disabled) await db.Tokens.RevokeAllAsync(id, ct);
|
||||
await audit.WriteAsync(caller, context, "user_updated", "user", id.ToString(), Changes(user, updated));
|
||||
return Results.Json(Dto.User(updated), ProtocolJson.Default.UserDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, TitanoDatabase db, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (id == caller.Id) return ApiErrors.Conflict(context, "self");
|
||||
if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user");
|
||||
if (IsActiveAdmin(user) && !await HasOtherActiveAdminAsync(db, id, ct)) return ApiErrors.Conflict(context, "last_admin");
|
||||
|
||||
// Render jobs of the user's nodes go back to the queue before the nodes disappear with the account.
|
||||
foreach (var node in (await db.RenderNodes.ListAsync(ct)).Where(n => n.UserId == id))
|
||||
await db.Jobs.RequeueRunningAsync(node.Id.ToString(), ct);
|
||||
var reassigned = await db.Sequences.ReassignOwnerAsync(id, caller.Id, ct);
|
||||
await db.Users.DeleteAsync(id, ct);
|
||||
await audit.WriteAsync(caller, context, "user_deleted", "user", id.ToString(),
|
||||
$"{user.Username} · {reassigned.ToString(CultureInfo.InvariantCulture)}");
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
private static async Task<IResult> ResetPasswordAsync(HttpContext context, Caller caller, Guid id, ResetPasswordRequest? request, TitanoDatabase db, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user");
|
||||
var password = string.IsNullOrEmpty(request?.Password) ? TemporaryPassword.Generate() : request.Password;
|
||||
if (!PasswordHasher.IsAcceptable(password)) return WeakPassword(context);
|
||||
var updated = user with { PasswordHash = PasswordHasher.Hash(password), MustChangePassword = true };
|
||||
await db.Users.UpdateAsync(updated, ct);
|
||||
await db.Tokens.RevokeAllAsync(id, ct);
|
||||
await audit.WriteAsync(caller, context, "password_reset", "user", id.ToString(), user.Username);
|
||||
return Results.Json(new TemporaryPasswordResponse(Dto.User(updated), password), ProtocolJson.Default.TemporaryPasswordResponse);
|
||||
}
|
||||
|
||||
private static bool IsActiveAdmin(User user) => user.Role == UserRole.Admin && !user.Disabled;
|
||||
|
||||
private static async Task<bool> HasOtherActiveAdminAsync(TitanoDatabase db, Guid except, CancellationToken ct) =>
|
||||
(await db.Users.ListAsync(ct)).Any(u => u.Id != except && IsActiveAdmin(u));
|
||||
|
||||
private static IResult WeakPassword(HttpContext context) =>
|
||||
ApiErrors.BadRequest(context, "weak_password", PasswordHasher.MinimumLength.ToString(CultureInfo.InvariantCulture), PasswordHasher.MinimumLength);
|
||||
|
||||
private static string? Clean(string? displayName)
|
||||
{
|
||||
var trimmed = displayName?.Trim();
|
||||
return string.IsNullOrEmpty(trimmed) ? null : trimmed[..Math.Min(trimmed.Length, MaxDisplayName)];
|
||||
}
|
||||
|
||||
/// <summary>Audit detail listing the fields an edit changed (never secrets).</summary>
|
||||
private static string Changes(User before, User after)
|
||||
{
|
||||
var changes = new List<string>();
|
||||
if (before.DisplayName != after.DisplayName) changes.Add("displayName");
|
||||
if (before.Role != after.Role) changes.Add("role=" + Dto.Role(after.Role));
|
||||
if (before.Permissions != after.Permissions) changes.Add("permissions");
|
||||
if (before.QuotaBytes != after.QuotaBytes) changes.Add("quota=" + after.QuotaBytes.ToString(CultureInfo.InvariantCulture));
|
||||
if (before.Disabled != after.Disabled) changes.Add(after.Disabled ? "disabled" : "enabled");
|
||||
return string.Join(", ", changes);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user