The server decodes with managed decoders only, so HEIF originals had no
proxies, thumbnails from their small previews and no pixels for analysis or
managed renders, and nothing could send it proxies (ENG-05). Manifests now
carry the archive's proxy spec and, per frame, its flags and whether the
server wants its proxy. PUT /api/v1/frames/{id}/proxy (Edit or RenderNode)
stores a JPEG of at most 64 MiB that decodes and whose Exif capture time is
the frame's, then queues thumbnails and the proxy pass. An upload from the
desktop makes and sends the wanted proxies after the originals and counts
them as local changes; a render node sends those it can make from the
originals it fetched once the job is done. The server never makes such a
proxy from a preview, drops one left by a renumbered frame, takes thumbnails
from a proxy, and analyses and renders those frames from their proxies.
Render nodes fetched every frame of the manifest: frames missing, corrupt or
excluded on the server failed the download, and originals not hashed yet
failed the SHA-256 check (ENG-07). Nodes now skip those frames, fetch unhashed
originals into the job folder with a size check, judge decodability with their
own decoders, and use the proxy of a frame they cannot decode.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
393 lines
22 KiB
C#
393 lines
22 KiB
C#
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;
|
|
|
|
/// <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}/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<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,
|
|
// 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Moves a sequence's folder into the archive's trash and removes it from the index through the archive engine's
|
|
/// <see cref="SequenceTrash"/> (BRIEF §0.2 rule 8: nothing is erased, the trash keeps it restorable).
|
|
/// <c>?dryRun=true</c> only reports what would happen. Owners and admins only. A sequence that cannot move is refused
|
|
/// with the reason as its code: 409 <c>sequence_busy</c> (a job works on it or its archive), <c>archive_root</c>,
|
|
/// <c>contains_sequences</c>, <c>sidecar_mismatch</c>, <c>folder_missing</c>; 503 <c>archive_offline</c>.
|
|
/// </summary>
|
|
private static async Task<IResult> 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"),
|
|
};
|
|
|
|
/// <summary>
|
|
/// Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5), with the proxies the server asks
|
|
/// for (<see cref="ServerProxies"/>); ETag over the version counters and the number of proxies asked for.
|
|
/// </summary>
|
|
private static async Task<IResult> 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<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"),
|
|
};
|
|
|
|
/// <summary>The full deep-analysis report (<c>.titano/analysis.json</c>) a client's editor shows for a server sequence.</summary>
|
|
private static async Task<IResult> 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<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;
|
|
}
|
|
|
|
/// <summary>The hero frame edit of new settings: the frame of their hero when it is not the stored settings' hero.</summary>
|
|
private static async Task<Guid?> 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<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");
|
|
if (r.HeroFrameId is not null) fields.Add("hero");
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
}
|