using System.Text.Json; using System.Text.Json.Serialization; using Chronos.Core.Model; using Chronos.Data.Archiving.Jobs; using Chronos.Protocol; namespace Chronos.Data.Videos; /// /// What the videos library lists (owner review 1, R9): every member optional, combined with "and". The values are those of /// GET /api/v1/videos (). /// public sealed record VideoQuery { /// The most videos a page holds. public const int MaxLimit = 500; /// Text in the sequence title, the preset name or the file name (any case). public string? Text { get; init; } /// , or ; null for every kind. public string? Kind { get; init; } /// A codec name as recorded (h264, hevc, pngsequence…); null for every codec. public string? Codec { get; init; } /// The year the render was made (UTC). public int? Year { get; init; } /// The renders of one sequence. public Guid? SequenceId { get; init; } /// One of ; null for newest first. public string? Sort { get; init; } /// The of the previous page; null for the first. public string? Cursor { get; init; } /// Videos per page, 1... public int Limit { get; init; } = 100; /// The query of an API request (its limit clamped, the default when none is given). public static VideoQuery From(VideoQueryDto dto) { ArgumentNullException.ThrowIfNull(dto); return new VideoQuery { Text = dto.Q, Kind = dto.Kind, Codec = dto.Codec, Year = dto.Year, SequenceId = dto.Sequence, Sort = dto.Sort, Cursor = dto.Cursor, Limit = dto.Limit is { } limit ? Math.Clamp(limit, 1, MaxLimit) : 100, }; } } /// A render as the videos library shows it: the render, its sequence and project, where its file is, and its copies. public sealed record VideoItem { public required Render Render { get; init; } /// The display title of the render's sequence. public required string SequenceTitle { get; init; } /// When the sequence's first photo was taken; null when unknown. public DateTime? SequenceFirstCapture { get; init; } /// The project rendered (owner review 2, R8); null for a render of the sequence's settings. public string? ProjectName { get; init; } /// The number of the project version rendered; null with . public int? ProjectVersionNumber { get; init; } /// Absolute path of the render's file (or folder, for an image sequence) on this host. public required string FullPath { get; init; } /// The file is not at : shown as Missing, and a delete removes only its row. public bool Missing { get; init; } /// Its verified copies in videos folders, oldest first. public IReadOnlyList Copies { get; init; } = []; /// The library kind (). public string Kind => RenderKind.Of(Render); /// or . public string State => Missing ? VideoStates.Missing : VideoStates.Ok; /// The file (or folder) name. public string FileName => Path.GetFileName(FullPath.TrimEnd('/', '\\')); } /// One page of the videos library; is the cursor of the next page, null on the last one. /// Videos matching the query on every page; null when not counted. public sealed record VideoPage(IReadOnlyList Items, string? Next, long? Total = null) { public static VideoPage Empty { get; } = new([], null, 0); } /// A render a delete leaves where it is: is one of . /// The render, when it exists. public sealed record VideoBlocked(Guid RenderId, string Reason, VideoItem? Video = null); /// /// The dry run of deleting renders into the trash (decision 17): the renders that go (a missing one only loses its row), the /// renders left where they are, and the plan's fingerprint, which the delete itself must give back. Copies in videos /// folders are never touched. /// public sealed record VideoDeletePlan(IReadOnlyList Items, IReadOnlyList Blocked, string Fingerprint) { /// The bytes that move into the trash (missing files count nothing). public long Bytes => Items.Where(i => !i.Missing).Sum(i => i.Render.Bytes); } /// What a delete did: the renders moved into the trash (or, missing, whose rows went), those left, and the trash entries made. /// The names of the entries made (), each restorable. public sealed record VideoDeleteResult(IReadOnlyList Deleted, IReadOnlyList Blocked, IReadOnlyList TrashEntries); /// /// The parameters of a job (decision 16): the renders to copy into , /// each hash-verified before it takes its name (a free one, " (2)" on a collision), the render never touched. /// /// The renders, in the order they are copied. /// The videos folder (absolute), checked again when the job runs. /// On the desktop: the renders are the signed-in server's, downloaded into the folder. /// The user (server) or PC (desktop) recorded as . public sealed record VideoCopyParameters(IReadOnlyList RenderIds, string Folder, bool FromServer = false, string? RequestedBy = null) { public string ToJson() => JsonSerializer.Serialize(this, VideoJson.Default.VideoCopyParameters); /// The parameters of a job; null when it has none that read. public static VideoCopyParameters? Read(string? json) { if (string.IsNullOrWhiteSpace(json)) return null; try { return JsonSerializer.Deserialize(json, VideoJson.Default.VideoCopyParameters) is { RenderIds: not null, Folder.Length: > 0 } parameters ? parameters : null; } catch (JsonException) { return null; } } } /// /// The error codes of the videos library (), the same as the server's API errors: /// each has a server message Server.Error.<Code> and a desktop message Errors.Videos.*. /// public static class VideoErrors { /// No videos folder is set (409). public const string FolderUnset = "videos_folder_unset"; /// The videos folder lies inside an archive root or the workspace (422). public const string FolderInvalid = "videos_folder_invalid"; /// The plan of a delete changed since it was made (409; nothing moved). public const string PlanChanged = "plan_changed"; /// A copy, or a trashed video being restored, does not match its render's SHA-256. public const string HashMismatch = "trash_hash_mismatch"; /// Not enough free space in the videos folder (507). public const string NoSpace = "videos_no_space"; /// A trashed video's sequence is not in the library: restore the sequence first (409). public const string SequenceGone = "sequence_gone"; /// A send, an upload or a copy of the render is running (409). public const string Busy = "video_busy"; } /// A videos library operation refused with one of ; nothing was changed. public sealed class VideoLibraryException(string code, string message) : InvalidOperationException(message) { public string Code { get; } = code; } /// The names of the videos trash entries (decision 17): videos-<render id>-<UTC ticks>, listed as kind "videos". public static class VideoTrashNames { /// The prefix of every videos entry name. public const string Prefix = "videos-"; /// The folder of the videos area inside an archive's trash, which holds the entries and their records. public const string FolderName = "videos"; /// The entry name of render deleted at . public static string EntryName(Guid renderId, DateTimeOffset deletedAt) => Prefix + renderId.ToString("D") + "-" + deletedAt.UtcTicks.ToString(System.Globalization.CultureInfo.InvariantCulture); /// Whether is a videos entry name (and nothing else: no path, no other entry's name). public static bool IsEntryName(string? name) => TryParse(name, out _, out _); /// The render id and the UTC ticks of a videos entry name; false for any other name. public static bool TryParse(string? name, out Guid renderId, out long ticks) { renderId = Guid.Empty; ticks = 0; if (name is null || !name.StartsWith(Prefix, StringComparison.Ordinal)) return false; var rest = name.AsSpan(Prefix.Length); // A "D" guid is 36 characters; then "-" and the ticks. return rest.Length > 37 && rest[36] == '-' && Guid.TryParseExact(rest[..36], "D", out renderId) && long.TryParse(rest[37..], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out ticks); } } /// /// The videos library of one index (owner review 1, R9): every render of its archives in one list, deleted into the trash /// and restored by id, and copied hash-verified into a videos folder. The desktop's Videos section and the server's /// /api/v1/videos endpoints use it; is the instance of an archive engine. /// public interface IVideoLibrary { /// False for the groundwork stub (): callers show no library then. bool IsAvailable { get; } /// One page of the renders matching , each with its copies and whether its file is there. Task ListAsync(VideoQuery query, CancellationToken cancellationToken = default); /// One render; null when the index has no such render. Task GetAsync(Guid renderId, CancellationToken cancellationToken = default); /// The dry run of deleting into the trash; nothing moves. Task PlanDeleteAsync(IReadOnlyList renderIds, CancellationToken cancellationToken = default); /// /// Deletes as planned: each file into .chronos/trash/videos/ of its archive with a /// record, its row removed and its sequence's render count recounted; a missing file loses only its row. /// /// : is not the plan's now; nothing moved. Task DeleteAsync(IReadOnlyList renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default); /// /// Brings a videos trash entry of archive back: the file re-hashed against its record, moved /// back (to a free name when its own is taken) and its row inserted again with the same render id. /// /// The entry is not in the trash. /// or ; nothing moved. Task RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default); /// /// Why cannot be the videos folder ( or /// ); null when it can. /// string? FolderProblem(string? folder); /// The job copying ' renders; enqueue it on the host's engine. /// The folder cannot be the videos folder (). ArchiveJobRequest CopyJob(VideoCopyParameters parameters); } /// /// The videos library until its parcel lands (phase 5 groundwork): lists nothing, finds nothing, and refuses every change /// with ; registered so the server and the desktop compile against /// . /// public sealed class NotImplementedVideoLibrary : IVideoLibrary { public static NotImplementedVideoLibrary Instance { get; } = new(); public bool IsAvailable => false; public Task ListAsync(VideoQuery query, CancellationToken cancellationToken = default) => Task.FromResult(VideoPage.Empty); public Task GetAsync(Guid renderId, CancellationToken cancellationToken = default) => Task.FromResult(null); public Task PlanDeleteAsync(IReadOnlyList renderIds, CancellationToken cancellationToken = default) => throw new NotImplementedException("The videos library is not implemented yet."); public Task DeleteAsync(IReadOnlyList renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default) => throw new NotImplementedException("The videos library is not implemented yet."); public Task RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) => throw new NotImplementedException("The videos library is not implemented yet."); public string? FolderProblem(string? folder) => string.IsNullOrWhiteSpace(folder) ? VideoErrors.FolderUnset : null; public ArchiveJobRequest CopyJob(VideoCopyParameters parameters) => throw new NotImplementedException("The videos library is not implemented yet."); } [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, PropertyNameCaseInsensitive = true)] [JsonSerializable(typeof(VideoCopyParameters))] internal sealed partial class VideoJson : JsonSerializerContext;