using System.Buffers.Text; using System.Globalization; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.Mvc; using Titano.Core.Model; using Titano.Core.Project; using Titano.Data; using Titano.Data.Archiving; using Titano.Data.Processing; 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; /// /// /api/v1/sequences: library listing with filters and keyset paging, detail with ETag, edits with /// settings_version optimistic concurrency, the sync manifest, frames, analysis, statistics and renders. /// 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}/analysis/report", ReportAsync).Requires(Permissions.Read); sequences.MapGet("/{id:guid}/stats", StatsAsync).Requires(Permissions.Read); sequences.MapGet("/{id:guid}/renders", RendersAsync).Requires(Permissions.Read); // Renders made on a client, sent on request (BRIEF §14.5); chunks go through /uploads. sequences.MapPost("/{id:guid}/renders", async (HttpContext c, Caller caller, Guid id, RenderUploadRequest request, RenderUploads uploads) => (await uploads.StartAsync(caller, id, request, c.RequestAborted)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.StartUploadResponse, statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created))).Requires(Permissions.Upload | Permissions.Edit); sequences.MapPost("/{id:guid}/renders/{uploadId:guid}/complete", async (HttpContext c, Caller caller, Guid id, Guid uploadId, RenderUploads uploads, IHostApplicationLifetime lifetime) => // The commit runs to the end even if the client disconnects meanwhile. (await uploads.CompleteAsync(caller, id, uploadId, lifetime.ApplicationStopping)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.RenderDto))) .Requires(Permissions.Upload | Permissions.Edit); } private static async Task 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([.. page.Items.Select(Dto.Sequence)], page.NextCursor, total), ProtocolJson.Default.PageSequenceDto); } private static async Task 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 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 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, // A client that sends only the settings (the sync of a local copy) moves the hero frame with the project's hero. HeroFrameId = request.HeroFrameId ?? (request.SettingsJson is { } settings ? await SettingsHeroAsync(db, id, settings, context.RequestAborted) : null), }; 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); } /// /// Moves a sequence's folder into the archive's trash and removes it from the index through the archive engine's /// (BRIEF §0.2 rule 8: nothing is erased, the trash keeps it restorable). /// ?dryRun=true only reports what would happen. Owners and admins only. A sequence that cannot move is refused /// with the reason as its code: 409 sequence_busy (a job works on it or its archive), archive_root, /// contains_sequences, sidecar_mismatch, folder_missing; 503 archive_offline. /// private static async Task DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db, [FromServices] ArchiveService? archives, AuditLog audit, EventHub events) { var ct = context.RequestAborted; if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context); var trash = archives?.Trash ?? new SequenceTrash(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner }); DeletePlan plan; try { plan = await trash.PlanAsync([id], null, ct); if (plan.Blocked is [{ } blocked]) return Refused(context, blocked.Reason); if (dryRun != true) await trash.DeleteAsync(plan, caller.User.Username, null, ct); } catch (ArgumentException) { // Deleted by someone else between the lookup and the plan. return ApiErrors.NotFound(context, "sequence"); } catch (Titano.Core.Archiving.ArchiveOfflineException) { return Refused(context, DeleteBlock.Offline); } catch (Exception ex) when (ex is StaleDeletePlanException or Titano.Core.Archiving.LeaseUnavailableException) { return Refused(context, DeleteBlock.Busy); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // A file of the folder is open elsewhere: nothing moved. return ApiErrors.Conflict(context, "folder_in_use"); } var step = plan.Steps[0]; var result = new SequenceDeletePlan(id, sequence.Folder, step.TrashFolder, sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true); if (dryRun == true) return Results.Json(result, ProtocolJson.Default.SequenceDeletePlan); 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(result, ProtocolJson.Default.SequenceDeletePlan); } private static IResult Refused(HttpContext context, DeleteBlock reason) => reason switch { DeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"), DeleteBlock.Busy => ApiErrors.Conflict(context, "sequence_busy"), DeleteBlock.ArchiveRoot => ApiErrors.Conflict(context, "archive_root"), DeleteBlock.ContainsSequences => ApiErrors.Conflict(context, "contains_sequences"), DeleteBlock.ForeignSidecar => ApiErrors.Conflict(context, "sidecar_mismatch"), _ => ApiErrors.Conflict(context, "folder_missing"), }; /// /// Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5), with the proxies the server asks /// for (); ETag over the version counters and the number of proxies asked for. /// private static async Task ManifestAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive) { var ct = context.RequestAborted; if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); var spec = ServerProxies.Spec(archive.Current); var frames = await ServerProxies.FramesAsync(db, archive.Current, sequence, spec, ct); var etag = string.Create(CultureInfo.InvariantCulture, $"\"m{sequence.SettingsVersion}-{sequence.FramesVersion}-{sequence.RenderedCount}-{frames.Count(f => f.WantsProxy)}\""); if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified); 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)], spec), ProtocolJson.Default.SequenceManifest); } private static async Task 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([.. frames.Select(Dto.Frame)], next, null), ProtocolJson.Default.PageFrameDto); } private static async Task 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"), }; /// The full deep-analysis report (.titano/analysis.json) a client's editor shows for a server sequence. private static async Task ReportAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive) { if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); if (string.IsNullOrEmpty(sequence.Folder)) return ApiErrors.NotFound(context, "analysis"); var path = new Core.Archiving.ArchivePaths(archive.Root).Sequence(sequence.Folder).AnalysisPath; var file = new FileInfo(path); if (!file.Exists || file.LinkTarget is not null || !ArchivePathGuard.IsInside(archive.Root, path)) return ApiErrors.NotFound(context, "analysis"); var etag = string.Create(CultureInfo.InvariantCulture, $"a-{file.Length}-{file.LastWriteTimeUtc.Ticks}"); return FileResponses.Serve(context, file, 0, file.Length, "application/json; charset=utf-8", "no-cache", etag) ?? ApiErrors.NotFound(context, "analysis"); } private static async Task 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 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); } /// Changes whenever anything the sequence representation shows changes (versions, status, statistics). private static string ETag(Sequence s) => string.Create(CultureInfo.InvariantCulture, $"\"{s.SettingsVersion}-{s.FramesVersion}-{s.UpdatedAt.UtcTicks}\""); /// The settings version named by an If-Match ETag of , if any. 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().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()) { if (candidate.ToString().Equals(text, StringComparison.OrdinalIgnoreCase)) { sort = candidate; return true; } } return false; } /// The hero frame edit of new settings: the frame of their hero when it is not the stored settings' hero. private static async Task SettingsHeroAsync(TitanoDatabase db, Guid id, string settingsJson, CancellationToken ct) { if (await db.Sequences.GetAsync(id, ct) is not { } current) return null; try { var before = string.IsNullOrWhiteSpace(current.SettingsJson) ? null : ProjectSettings.FromJson(current.SettingsJson).HeroFrame; return await HeroFrame.EditAsync(db, id, before, ProjectSettings.FromJson(settingsJson).HeroFrame, ct); } catch (Exception ex) when (ex is JsonException or InvalidDataException) { // Not a project of this Titano (a newer one, or free JSON): its hero is unknown here, the stored one stays. return null; } } 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(); 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"); if (r.HeroFrameId is not null) fields.Add("hero"); return string.Join(", ", fields); } /// Opaque cursor of the frame listing: the index of the last frame returned. 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; } } } }