feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder. Closes #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #27.
This commit is contained in:
1 parent
188b2c2e55
commit
728ffa35cb
729 files changed
+26954
-1652
No files matched your search
@@ -0,0 +1,301 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// What the videos library lists (owner review 1, R9): every member optional, combined with "and". The values are those of
|
||||
/// <c>GET /api/v1/videos</c> (<see cref="VideoQueryDto"/>).
|
||||
/// </summary>
|
||||
public sealed record VideoQuery
|
||||
{
|
||||
/// <summary>The most videos a page holds.</summary>
|
||||
public const int MaxLimit = 500;
|
||||
|
||||
/// <summary>Text in the sequence title, the preset name or the file name (any case).</summary>
|
||||
public string? Text { get; init; }
|
||||
|
||||
/// <summary><see cref="RenderKind.Video"/>, <see cref="RenderKind.Still"/> or <see cref="RenderKind.Sequence"/>; null for every kind.</summary>
|
||||
public string? Kind { get; init; }
|
||||
|
||||
/// <summary>A codec name as recorded (<c>h264</c>, <c>hevc</c>, <c>pngsequence</c>…); null for every codec.</summary>
|
||||
public string? Codec { get; init; }
|
||||
|
||||
/// <summary>The year the render was made (UTC).</summary>
|
||||
public int? Year { get; init; }
|
||||
|
||||
/// <summary>The renders of one sequence.</summary>
|
||||
public Guid? SequenceId { get; init; }
|
||||
|
||||
/// <summary>One of <see cref="VideoSorts"/>; null for newest first.</summary>
|
||||
public string? Sort { get; init; }
|
||||
|
||||
/// <summary>The <see cref="VideoPage.Next"/> of the previous page; null for the first.</summary>
|
||||
public string? Cursor { get; init; }
|
||||
|
||||
/// <summary>Videos per page, 1..<see cref="MaxLimit"/>.</summary>
|
||||
public int Limit { get; init; } = 100;
|
||||
|
||||
/// <summary>The query of an API request (its limit clamped, the default when none is given).</summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A render as the videos library shows it: the render, its sequence and project, where its file is, and its copies.</summary>
|
||||
public sealed record VideoItem
|
||||
{
|
||||
public required Render Render { get; init; }
|
||||
|
||||
/// <summary>The display title of the render's sequence.</summary>
|
||||
public required string SequenceTitle { get; init; }
|
||||
|
||||
/// <summary>When the sequence's first photo was taken; null when unknown.</summary>
|
||||
public DateTime? SequenceFirstCapture { get; init; }
|
||||
|
||||
/// <summary>The project rendered (owner review 2, R8); null for a render of the sequence's settings.</summary>
|
||||
public string? ProjectName { get; init; }
|
||||
|
||||
/// <summary>The number of the project version rendered; null with <see cref="ProjectName"/>.</summary>
|
||||
public int? ProjectVersionNumber { get; init; }
|
||||
|
||||
/// <summary>Absolute path of the render's file (or folder, for an image sequence) on this host.</summary>
|
||||
public required string FullPath { get; init; }
|
||||
|
||||
/// <summary>The file is not at <see cref="FullPath"/>: shown as Missing, and a delete removes only its row.</summary>
|
||||
public bool Missing { get; init; }
|
||||
|
||||
/// <summary>Its verified copies in videos folders, oldest first.</summary>
|
||||
public IReadOnlyList<RenderCopy> Copies { get; init; } = [];
|
||||
|
||||
/// <summary>The library kind (<see cref="RenderKind.Of(Render)"/>).</summary>
|
||||
public string Kind => RenderKind.Of(Render);
|
||||
|
||||
/// <summary><see cref="VideoStates.Ok"/> or <see cref="VideoStates.Missing"/>.</summary>
|
||||
public string State => Missing ? VideoStates.Missing : VideoStates.Ok;
|
||||
|
||||
/// <summary>The file (or folder) name.</summary>
|
||||
public string FileName => Path.GetFileName(FullPath.TrimEnd('/', '\\'));
|
||||
}
|
||||
|
||||
/// <summary>One page of the videos library; <see cref="Next"/> is the cursor of the next page, null on the last one.</summary>
|
||||
/// <param name="Total">Videos matching the query on every page; null when not counted.</param>
|
||||
public sealed record VideoPage(IReadOnlyList<VideoItem> Items, string? Next, long? Total = null)
|
||||
{
|
||||
public static VideoPage Empty { get; } = new([], null, 0);
|
||||
}
|
||||
|
||||
/// <summary>A render a delete leaves where it is: <see cref="Reason"/> is one of <see cref="VideoBlockReasons"/>.</summary>
|
||||
/// <param name="Video">The render, when it exists.</param>
|
||||
public sealed record VideoBlocked(Guid RenderId, string Reason, VideoItem? Video = null);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record VideoDeletePlan(IReadOnlyList<VideoItem> Items, IReadOnlyList<VideoBlocked> Blocked, string Fingerprint)
|
||||
{
|
||||
/// <summary>The bytes that move into the trash (missing files count nothing).</summary>
|
||||
public long Bytes => Items.Where(i => !i.Missing).Sum(i => i.Render.Bytes);
|
||||
}
|
||||
|
||||
/// <summary>What a delete did: the renders moved into the trash (or, missing, whose rows went), those left, and the trash entries made.</summary>
|
||||
/// <param name="TrashEntries">The names of the entries made (<see cref="VideoTrashNames"/>), each restorable.</param>
|
||||
public sealed record VideoDeleteResult(IReadOnlyList<VideoItem> Deleted, IReadOnlyList<VideoBlocked> Blocked, IReadOnlyList<string> TrashEntries);
|
||||
|
||||
/// <summary>
|
||||
/// The parameters of a <see cref="JobKind.VideoCopy"/> job (decision 16): the renders to copy into <see cref="Folder"/>,
|
||||
/// each hash-verified before it takes its name (a free one, " (2)" on a collision), the render never touched.
|
||||
/// </summary>
|
||||
/// <param name="RenderIds">The renders, in the order they are copied.</param>
|
||||
/// <param name="Folder">The videos folder (absolute), checked again when the job runs.</param>
|
||||
/// <param name="FromServer">On the desktop: the renders are the signed-in server's, downloaded into the folder.</param>
|
||||
/// <param name="RequestedBy">The user (server) or PC (desktop) recorded as <see cref="RenderCopy.CopiedBy"/>.</param>
|
||||
/// <param name="Server">With <paramref name="FromServer"/>: the server the renders are downloaded from (its address as the
|
||||
/// desktop's connections name it, <see cref="Sync.ISyncConnector.ConnectAsync"/>).</param>
|
||||
/// <param name="SequenceIds">With <paramref name="FromServer"/>: the server's sequence of each render, in the order of
|
||||
/// <paramref name="RenderIds"/>; its manifest gives the SHA-256 a download is verified against.</param>
|
||||
public sealed record VideoCopyParameters(IReadOnlyList<Guid> RenderIds, string Folder, bool FromServer = false, string? RequestedBy = null,
|
||||
string? Server = null, IReadOnlyList<Guid>? SequenceIds = null)
|
||||
{
|
||||
public string ToJson() => JsonSerializer.Serialize(this, VideoJson.Default.VideoCopyParameters);
|
||||
|
||||
/// <summary>The parameters of a job; null when it has none that read.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The error codes of the videos library (<see cref="VideoLibraryException.Code"/>), the same as the server's API errors:
|
||||
/// each has a server message <c>Server.Error.<Code></c> and a desktop message <c>Errors.Videos.*</c>.
|
||||
/// </summary>
|
||||
public static class VideoErrors
|
||||
{
|
||||
/// <summary>No videos folder is set (409).</summary>
|
||||
public const string FolderUnset = "videos_folder_unset";
|
||||
|
||||
/// <summary>The videos folder lies inside an archive root or the workspace (422).</summary>
|
||||
public const string FolderInvalid = "videos_folder_invalid";
|
||||
|
||||
/// <summary>The plan of a delete changed since it was made (409; nothing moved).</summary>
|
||||
public const string PlanChanged = "plan_changed";
|
||||
|
||||
/// <summary>A copy, or a trashed video being restored, does not match its render's SHA-256.</summary>
|
||||
public const string HashMismatch = "trash_hash_mismatch";
|
||||
|
||||
/// <summary>Not enough free space in the videos folder (507).</summary>
|
||||
public const string NoSpace = "videos_no_space";
|
||||
|
||||
/// <summary>A trashed video's sequence is not in the library: restore the sequence first (409).</summary>
|
||||
public const string SequenceGone = "sequence_gone";
|
||||
|
||||
/// <summary>A send, an upload or a copy of the render is running (409).</summary>
|
||||
public const string Busy = "video_busy";
|
||||
}
|
||||
|
||||
/// <summary>A videos library operation refused with one of <see cref="VideoErrors"/>; nothing was changed.</summary>
|
||||
public sealed class VideoLibraryException(string code, string message) : InvalidOperationException(message)
|
||||
{
|
||||
public string Code { get; } = code;
|
||||
}
|
||||
|
||||
/// <summary>The names of the videos trash entries (decision 17): <c>videos-<render id>-<UTC ticks></c>, listed as kind "videos".</summary>
|
||||
public static class VideoTrashNames
|
||||
{
|
||||
/// <summary>The prefix of every videos entry name.</summary>
|
||||
public const string Prefix = "videos-";
|
||||
|
||||
/// <summary>The folder of the videos area inside an archive's trash, which holds the entries and their records.</summary>
|
||||
public const string FolderName = "videos";
|
||||
|
||||
/// <summary>The entry name of render <paramref name="renderId"/> deleted at <paramref name="deletedAt"/>.</summary>
|
||||
public static string EntryName(Guid renderId, DateTimeOffset deletedAt) =>
|
||||
Prefix + renderId.ToString("D") + "-" + deletedAt.UtcTicks.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Whether <paramref name="name"/> is a videos entry name (and nothing else: no path, no other entry's name).</summary>
|
||||
public static bool IsEntryName(string? name) => TryParse(name, out _, out _);
|
||||
|
||||
/// <summary>The render id and the UTC ticks of a videos entry name; false for any other name.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <c>/api/v1/videos</c> endpoints use it; <see cref="Archiving.ArchiveService.Videos"/> is the instance of an archive engine.
|
||||
/// </summary>
|
||||
public interface IVideoLibrary
|
||||
{
|
||||
/// <summary>False for the groundwork stub (<see cref="NotImplementedVideoLibrary"/>): callers show no library then.</summary>
|
||||
bool IsAvailable { get; }
|
||||
|
||||
/// <summary>One page of the renders matching <paramref name="query"/>, each with its copies and whether its file is there.</summary>
|
||||
Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>One render; null when the index has no such render.</summary>
|
||||
Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// The verified copies this host made of <paramref name="renderIds"/>, renders of its index or not (a server's render
|
||||
/// downloaded into the videos folder); none for a render it never copied.
|
||||
/// </summary>
|
||||
Task<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>> CopiesAsync(IReadOnlyCollection<Guid> renderIds, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>>(new Dictionary<Guid, IReadOnlyList<RenderCopy>>());
|
||||
|
||||
/// <summary>The dry run of deleting <paramref name="renderIds"/> into the trash; nothing moves.</summary>
|
||||
Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes <paramref name="renderIds"/> as planned: each file into <c>.chronos/trash/videos/</c> of its archive with a
|
||||
/// record, its row removed and its sequence's render count recounted; a missing file loses only its row.
|
||||
/// </summary>
|
||||
/// <exception cref="VideoLibraryException"><see cref="VideoErrors.PlanChanged"/>: <paramref name="fingerprint"/> is not the plan's now; nothing moved.</exception>
|
||||
Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Brings a videos trash entry of archive <paramref name="archiveId"/> 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.
|
||||
/// </summary>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
/// <exception cref="VideoLibraryException"><see cref="VideoErrors.HashMismatch"/> or <see cref="VideoErrors.SequenceGone"/>; nothing moved.</exception>
|
||||
Task<Render> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="folder"/> cannot be the videos folder (<see cref="VideoErrors.FolderUnset"/> or
|
||||
/// <see cref="VideoErrors.FolderInvalid"/>); null when it can.
|
||||
/// </summary>
|
||||
string? FolderProblem(string? folder);
|
||||
|
||||
/// <summary>The <see cref="JobKind.VideoCopy"/> job copying <paramref name="parameters"/>' renders; enqueue it on the host's engine.</summary>
|
||||
/// <exception cref="VideoLibraryException">The folder cannot be the videos folder (<see cref="FolderProblem"/>).</exception>
|
||||
ArchiveJobRequest CopyJob(VideoCopyParameters parameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The videos library until its parcel lands (phase 5 groundwork): lists nothing, finds nothing, and refuses every change
|
||||
/// with <see cref="NotImplementedException"/>; registered so the server and the desktop compile against
|
||||
/// <see cref="IVideoLibrary"/>.
|
||||
/// </summary>
|
||||
public sealed class NotImplementedVideoLibrary : IVideoLibrary
|
||||
{
|
||||
public static NotImplementedVideoLibrary Instance { get; } = new();
|
||||
|
||||
public bool IsAvailable => false;
|
||||
|
||||
public Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default) => Task.FromResult(VideoPage.Empty);
|
||||
|
||||
public Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default) => Task.FromResult<VideoItem?>(null);
|
||||
|
||||
public Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default) =>
|
||||
throw new NotImplementedException("The videos library is not implemented yet.");
|
||||
|
||||
public Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default) =>
|
||||
throw new NotImplementedException("The videos library is not implemented yet.");
|
||||
|
||||
public Task<Render> 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;
|
||||
@@ -0,0 +1,243 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Videos;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.VideoCopy"/> (owner review 1, R9, decision 16): copies renders into the videos folder, on the desktop
|
||||
/// and on the server. The folder is checked again first, and the free space for every render still to copy, so a copy that
|
||||
/// cannot fit fails before it writes anything. Each render is written as <c>.incoming-<id>.part</c> in the folder and
|
||||
/// flushed, hashed and compared with the render's SHA-256 (the render hashed first when it never was, and remembered; an
|
||||
/// image sequence's folder file by file against its own files), then renamed without overwriting to its own name or a free
|
||||
/// " (2)" one, and recorded in <c>render_copies</c>. A copy that does not match is deleted and that render fails; the
|
||||
/// render itself is never touched. On the desktop a server's render (<see cref="VideoCopyParameters.FromServer"/>) is
|
||||
/// downloaded into the part file and checked against the SHA-256 its server's manifest gives. Checkpoint:
|
||||
/// <c>done:<n></c>, the renders done; leftovers of an interrupted copy are removed before it starts again.
|
||||
/// </summary>
|
||||
internal sealed class VideoCopyJobHandler(ChronosDatabase db, VideoLibrary library) : IJobHandler
|
||||
{
|
||||
private const string Prefix = "done:";
|
||||
|
||||
public JobKind Kind => JobKind.VideoCopy;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var parameters = VideoCopyParameters.Read(context.Job.ParametersJson) ?? throw new InvalidDataException(Loc.L("Errors.Render.Parameters"));
|
||||
if (await library.FolderProblemAsync(parameters.Folder, ct).ConfigureAwait(false) is { } problem) throw VideoLibrary.Refusal(problem);
|
||||
var folder = parameters.Folder;
|
||||
Directory.CreateDirectory(folder);
|
||||
var ids = parameters.RenderIds;
|
||||
var start = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal)
|
||||
&& int.TryParse(checkpoint.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var done)
|
||||
? int.Min(done, ids.Count)
|
||||
: 0;
|
||||
foreach (var id in ids.Skip(start)) Remove(VideosFolder.PartPath(folder, id));
|
||||
await context.ReportAsync(start, ids.Count, Loc.L("Videos.Job.Copying")).ConfigureAwait(false);
|
||||
|
||||
using var remote = parameters.FromServer ? await ConnectAsync(parameters, ct).ConfigureAwait(false) : null;
|
||||
var sources = new List<Source?>(ids.Count);
|
||||
for (var i = 0; i < ids.Count; i++)
|
||||
sources.Add(i < start ? null : await SourceAsync(context, parameters, remote, i, ct).ConfigureAwait(false));
|
||||
// Every render still to copy must fit before anything is written.
|
||||
var needed = sources.Where(s => s is not null).Sum(s => s!.Bytes);
|
||||
if (VideosFolder.FreeBytes(folder, library.FreeSpace) is { } free && free < needed)
|
||||
throw new VideoLibraryException(VideoErrors.NoSpace, Loc.L("Errors.Videos.NoSpace", Megabytes(needed - free)));
|
||||
|
||||
var failed = 0;
|
||||
for (var i = start; i < ids.Count; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (sources[i] is not { } source)
|
||||
{
|
||||
failed++;
|
||||
}
|
||||
else if (!await CopyAsync(context, parameters, remote, source, ct).ConfigureAwait(false))
|
||||
{
|
||||
failed++;
|
||||
}
|
||||
await context.CheckpointAsync(Prefix + (i + 1).ToString(CultureInfo.InvariantCulture), i + 1, ids.Count).ConfigureAwait(false);
|
||||
}
|
||||
if (failed > 0) throw new InvalidOperationException(Loc.L("Errors.Render.Failed", failed, ids.Count - start));
|
||||
}
|
||||
|
||||
/// <summary>What one render's copy reads: its id, name, size, and the SHA-256 it is verified against (null: an image sequence).</summary>
|
||||
/// <param name="Path">The render's file or folder on this host; null for a server's render.</param>
|
||||
/// <param name="Sequence">The server's sequence of a server's render.</param>
|
||||
private sealed record Source(Guid RenderId, string Name, string? Path, bool IsFolder, long Bytes, string? Sha256, Guid? Sequence);
|
||||
|
||||
/// <summary>The render at <paramref name="index"/> as it is now; null (logged) when it is gone or its file is missing.</summary>
|
||||
private async Task<Source?> SourceAsync(JobContext context, VideoCopyParameters parameters, ISyncRemote? remote, int index, CancellationToken ct)
|
||||
{
|
||||
var id = parameters.RenderIds[index];
|
||||
if (remote is not null)
|
||||
{
|
||||
var sequence = parameters.SequenceIds is { } sequences && index < sequences.Count ? sequences[index] : (Guid?)null;
|
||||
var render = sequence is { } s ? (await remote.GetManifestAsync(s, ct).ConfigureAwait(false)).Renders.FirstOrDefault(r => r.Id == id) : null;
|
||||
if (render is null)
|
||||
{
|
||||
context.Log(Loc.L("Videos.Log.Missing", id.ToString("D")));
|
||||
return null;
|
||||
}
|
||||
// Named by the server as it downloads.
|
||||
return new Source(id, id.ToString("N"), null, false, render.Bytes, render.Sha256, sequence);
|
||||
}
|
||||
if (await library.GetAsync(id, ct).ConfigureAwait(false) is not { } item || item.Missing)
|
||||
{
|
||||
context.Log(Loc.L("Videos.Log.Missing", (await library.GetAsync(id, ct).ConfigureAwait(false))?.FileName ?? id.ToString("D")));
|
||||
return null;
|
||||
}
|
||||
var folder = Directory.Exists(item.FullPath);
|
||||
string? sha = null;
|
||||
if (!folder)
|
||||
{
|
||||
sha = item.Render.Sha256;
|
||||
if (sha is null)
|
||||
{
|
||||
// A render of before migration 0010: hashed now, and remembered.
|
||||
await context.ReportAsync(context.Done, context.Total, Loc.L("Videos.Job.Verifying")).ConfigureAwait(false);
|
||||
sha = await ContentHash.Sha256Async(item.FullPath, cancellationToken: ct).ConfigureAwait(false);
|
||||
await db.Renders.SetSha256Async(id, sha, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
var bytes = folder ? new DirectoryInfo(item.FullPath).EnumerateFiles("*", SearchOption.AllDirectories).Sum(f => f.Length) : new FileInfo(item.FullPath).Length;
|
||||
return new Source(id, item.FileName, item.FullPath, folder, bytes, sha, null);
|
||||
}
|
||||
|
||||
/// <summary>Copies one render, verified, under a free name, and records the copy; false (logged) when the copy did not match.</summary>
|
||||
private async Task<bool> CopyAsync(JobContext context, VideoCopyParameters parameters, ISyncRemote? remote, Source source, CancellationToken ct)
|
||||
{
|
||||
var folder = parameters.Folder;
|
||||
var part = VideosFolder.PartPath(folder, source.RenderId);
|
||||
Remove(part);
|
||||
string? sha;
|
||||
try
|
||||
{
|
||||
if (remote is not null)
|
||||
{
|
||||
await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
var given = await remote.DownloadRenderAsync(source.RenderId, file, ct).ConfigureAwait(false);
|
||||
file.Flush(flushToDisk: true);
|
||||
source = source with { Name = SyncTransfers.SafeFileName(given) ?? source.Name };
|
||||
}
|
||||
sha = await Verified(part, source.Sha256, context, ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (source.IsFolder)
|
||||
{
|
||||
// An image sequence: each file copied and compared with its own.
|
||||
foreach (var file in Directory.EnumerateFiles(source.Path!, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var target = Path.Combine(part, Path.GetRelativePath(source.Path!, file));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
await VideoTrash.CopyFileAsync(file, target, ct).ConfigureAwait(false);
|
||||
var expected = await ContentHash.Sha256Async(file, cancellationToken: ct).ConfigureAwait(false);
|
||||
if (await Verified(target, expected, context, ct).ConfigureAwait(false) is null)
|
||||
{
|
||||
Mismatch(context, source, part);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Directory.CreateDirectory(part);
|
||||
sha = null;
|
||||
await Commit(context, parameters, source, part, sha).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
await VideoTrash.CopyFileAsync(source.Path!, part, ct).ConfigureAwait(false);
|
||||
sha = await Verified(part, source.Sha256, context, ct).ConfigureAwait(false);
|
||||
}
|
||||
if (sha is null)
|
||||
{
|
||||
Mismatch(context, source, part);
|
||||
return false;
|
||||
}
|
||||
// Inside the try: a rename the folder refuses (an antivirus, a permission changed) leaves no part copy behind.
|
||||
await Commit(context, parameters, source, part, sha).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Remove(part);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The copy takes its name (never overwriting: another free name when one appeared meanwhile) and is recorded.</summary>
|
||||
private async Task Commit(JobContext context, VideoCopyParameters parameters, Source source, string part, string? sha)
|
||||
{
|
||||
string target;
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
target = VideosFolder.FreeName(parameters.Folder, source.Name, source.IsFolder);
|
||||
try
|
||||
{
|
||||
if (source.IsFolder) Directory.Move(part, target);
|
||||
else File.Move(part, target, overwrite: false);
|
||||
break;
|
||||
}
|
||||
catch (IOException) when (attempt < 5 && (File.Exists(target) || Directory.Exists(target)))
|
||||
{
|
||||
// Taken between the look and the move: the next free name.
|
||||
}
|
||||
}
|
||||
var bytes = source.IsFolder ? new DirectoryInfo(target).EnumerateFiles("*", SearchOption.AllDirectories).Sum(f => f.Length) : new FileInfo(target).Length;
|
||||
await db.RenderCopies.InsertAsync(new RenderCopy
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
RenderId = source.RenderId,
|
||||
Path = target,
|
||||
Sha256 = sha,
|
||||
Bytes = bytes,
|
||||
CopiedAt = DateTimeOffset.UtcNow,
|
||||
CopiedBy = parameters.RequestedBy,
|
||||
}, CancellationToken.None).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Videos.Log.Copied", source.Name, target));
|
||||
Log.Info("videos", $"Render {source.RenderId} copied to {target} ({bytes} bytes, verified)");
|
||||
}
|
||||
|
||||
/// <summary>The SHA-256 of the copy at <paramref name="path"/> when it matches <paramref name="expected"/> (any, when none is known); null otherwise.</summary>
|
||||
private static async Task<string?> Verified(string path, string? expected, JobContext context, CancellationToken ct)
|
||||
{
|
||||
await context.ReportAsync(context.Done, context.Total, Loc.L("Videos.Job.Verifying")).ConfigureAwait(false);
|
||||
var sha = await ContentHash.Sha256Async(path, cancellationToken: ct).ConfigureAwait(false);
|
||||
return expected is null || string.Equals(sha, expected, StringComparison.OrdinalIgnoreCase) ? sha : null;
|
||||
}
|
||||
|
||||
private static void Mismatch(JobContext context, Source source, string part)
|
||||
{
|
||||
Remove(part);
|
||||
context.Log(Loc.L("Videos.Log.Mismatch", source.Name));
|
||||
Log.Warning("videos", $"The copy of render {source.RenderId} did not match it; the copy was removed");
|
||||
}
|
||||
|
||||
private async Task<ISyncRemote> ConnectAsync(VideoCopyParameters parameters, CancellationToken ct)
|
||||
{
|
||||
if (library.Servers is not { } servers || parameters.Server is not { Length: > 0 } server
|
||||
|| await servers.ConnectAsync(server, ct).ConfigureAwait(false) is not { } remote)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Sync.NotLinked"));
|
||||
return remote;
|
||||
}
|
||||
|
||||
private static string Megabytes(long bytes) => Housekeeping.CleanupSteps.Megabytes(bytes);
|
||||
|
||||
private static void Remove(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
|
||||
else if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"{path} could not be removed", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Videos;
|
||||
|
||||
/// <summary>
|
||||
/// The videos library of one index (owner review 1, R9): every render of its archives in one list, newest first unless
|
||||
/// asked, each with its sequence, its project, whether its file is there and its copies; deleted into its archive's trash
|
||||
/// after a dry run whose fingerprint the delete gives back (decision 17), restored by id (decision 18), and copied
|
||||
/// hash-verified into a videos folder by a <see cref="JobKind.VideoCopy"/> job (decision 16). The renders themselves are
|
||||
/// never changed, and copies in a videos folder are never touched.
|
||||
/// </summary>
|
||||
public sealed class VideoLibrary : IVideoLibrary
|
||||
{
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
|
||||
internal VideoLibrary(ChronosDatabase db, SequenceWriter writer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
Trash = new VideoTrash(db, writer);
|
||||
}
|
||||
|
||||
public bool IsAvailable => true;
|
||||
|
||||
/// <summary>
|
||||
/// Folders a videos folder may not lie in besides the archive roots (decision 15): the desktop's workspace. Asked each
|
||||
/// time a folder is checked.
|
||||
/// </summary>
|
||||
public Func<IReadOnlyList<string>>? ProtectedFolders { get; set; }
|
||||
|
||||
/// <summary>The desktop's signed-in servers: a copy of a server's renders (<see cref="VideoCopyParameters.FromServer"/>) downloads through them.</summary>
|
||||
public ISyncConnector? Servers { get; set; }
|
||||
|
||||
/// <summary>How the host measures free space under a folder; null: the folder's drive.</summary>
|
||||
public Func<string, long?>? FreeSpace => _writer.Options.FreeSpace;
|
||||
|
||||
internal VideoTrash Trash { get; }
|
||||
|
||||
public async Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var (renders, next, total) = await _db.Renders.ListPageAsync(query, cancellationToken).ConfigureAwait(false);
|
||||
return new VideoPage(await ItemsAsync(renders, cancellationToken).ConfigureAwait(false), next, total);
|
||||
}
|
||||
|
||||
public async Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default) =>
|
||||
await _db.Renders.GetAsync(renderId, cancellationToken).ConfigureAwait(false) is { } render
|
||||
? (await ItemsAsync([render], cancellationToken).ConfigureAwait(false)).FirstOrDefault()
|
||||
: null;
|
||||
|
||||
public Task<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>> CopiesAsync(IReadOnlyCollection<Guid> renderIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(renderIds);
|
||||
return _db.RenderCopies.ListByRendersAsync(renderIds, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(renderIds);
|
||||
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
|
||||
var items = new List<VideoItem>();
|
||||
var blocked = new List<VideoBlocked>();
|
||||
foreach (var id in renderIds.Distinct())
|
||||
{
|
||||
if (await GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item) blocked.Add(new VideoBlocked(id, VideoBlockReasons.NotFound));
|
||||
else if (busy.Contains(id)) blocked.Add(new VideoBlocked(id, VideoBlockReasons.Busy, item));
|
||||
else items.Add(item);
|
||||
}
|
||||
return new VideoDeletePlan(items, blocked, Fingerprint(items, blocked));
|
||||
}
|
||||
|
||||
public async Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(renderIds);
|
||||
var plan = await PlanDeleteAsync(renderIds, cancellationToken).ConfigureAwait(false);
|
||||
if (!string.Equals(plan.Fingerprint, fingerprint, StringComparison.Ordinal))
|
||||
throw new VideoLibraryException(VideoErrors.PlanChanged, Loc.L("Errors.Videos.Fingerprint"));
|
||||
var deleted = new List<VideoItem>();
|
||||
var entries = new List<string>();
|
||||
var archives = new Dictionary<Guid, Archive?>();
|
||||
foreach (var item in plan.Items)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var archive = await ArchiveOfAsync(archives, item.Render.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (archive is null)
|
||||
{
|
||||
// The sequence left the index since the plan: so did its renders.
|
||||
continue;
|
||||
}
|
||||
if (await Trash.DeleteAsync(archive, item.Render, deletedBy, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry.Name);
|
||||
deleted.Add(item);
|
||||
}
|
||||
return new VideoDeleteResult(deleted, plan.Blocked, entries);
|
||||
}
|
||||
|
||||
public async Task<Render> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var archive = await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ArgumentException($"Unknown archive {archiveId}.", nameof(archiveId));
|
||||
return await Trash.RestoreAsync(archive, entryName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Settles the deletes into the trash a crash interrupted in <paramref name="archive"/> (<see cref="VideoTrash.RecoverAsync"/>).</summary>
|
||||
public Task<int> RecoverAsync(Archive archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
return Trash.RecoverAsync(archive, cancellationToken);
|
||||
}
|
||||
|
||||
public string? FolderProblem(string? folder)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(folder)) return VideoErrors.FolderUnset;
|
||||
// Asked from the UI thread and the server's endpoints alike: the roots are read off any synchronisation context.
|
||||
var roots = Task.Run(() => _db.Archives.ListAsync()).GetAwaiter().GetResult().Select(a => a.RootPath);
|
||||
return VideosFolder.Problem(folder, [.. roots, .. ProtectedFolders?.Invoke() ?? []]);
|
||||
}
|
||||
|
||||
/// <summary><see cref="FolderProblem"/> without blocking: what the copy job checks again when it runs.</summary>
|
||||
internal async Task<string?> FolderProblemAsync(string? folder, CancellationToken cancellationToken)
|
||||
{
|
||||
var roots = (await _db.Archives.ListAsync(cancellationToken).ConfigureAwait(false)).Select(a => a.RootPath);
|
||||
return VideosFolder.Problem(folder, [.. roots, .. ProtectedFolders?.Invoke() ?? []]);
|
||||
}
|
||||
|
||||
public ArchiveJobRequest CopyJob(VideoCopyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
if (FolderProblem(parameters.Folder) is { } problem) throw Refusal(problem);
|
||||
if (parameters.RenderIds.Count == 0) throw new ArgumentException("No render to copy.", nameof(parameters));
|
||||
var ids = parameters.RenderIds.Distinct().ToList();
|
||||
var folder = VideosFolder.Normalize(parameters.Folder);
|
||||
return new ArchiveJobRequest(JobKind.VideoCopy, ids, Loc.L("Videos.Target.Copy", ids.Count.ToString(Loc.Culture)),
|
||||
(parameters with { RenderIds = ids, Folder = folder }).ToJson(), JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>The exception of a videos folder that cannot be used, with its localised message.</summary>
|
||||
internal static VideoLibraryException Refusal(string code) => new(code, Loc.L(code == VideoErrors.FolderUnset ? "Errors.Videos.FolderUnset" : "Errors.Videos.FolderInsideArchive"));
|
||||
|
||||
/// <summary>
|
||||
/// The fingerprint of a delete plan: SHA-256 of each render's id, path, size, creation and whether its file is there, and
|
||||
/// of each render left where it is with why, in id order. Another render, a render moved, grown, gone or busy since gives
|
||||
/// another fingerprint.
|
||||
/// </summary>
|
||||
internal static string Fingerprint(IEnumerable<VideoItem> items, IEnumerable<VideoBlocked> blocked)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
foreach (var item in items.OrderBy(i => i.Render.Id))
|
||||
{
|
||||
var r = item.Render;
|
||||
text.Append(CultureInfo.InvariantCulture, $"{r.Id:N}|{r.OutputPath}|{r.Bytes}|{r.Created.UtcTicks}|{(item.Missing ? "missing" : "ok")}\n");
|
||||
}
|
||||
foreach (var block in blocked.OrderBy(b => b.RenderId)) text.Append(CultureInfo.InvariantCulture, $"{block.RenderId:N}|blocked|{block.Reason}\n");
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
|
||||
}
|
||||
|
||||
/// <summary>The renders a running or paused job holds: those a copy works on (its targets are render ids).</summary>
|
||||
private async Task<HashSet<Guid>> BusyAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var busy = new HashSet<Guid>();
|
||||
foreach (var hold in await _db.Jobs.ListHoldsAsync(null, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (hold.Kind == JobKind.VideoCopy) busy.UnionWith(hold.TargetIds);
|
||||
}
|
||||
return busy;
|
||||
}
|
||||
|
||||
/// <summary>The library items of <paramref name="renders"/>: each with its sequence, project, file state and copies, in their order.</summary>
|
||||
private async Task<IReadOnlyList<VideoItem>> ItemsAsync(IReadOnlyList<Render> renders, CancellationToken cancellationToken)
|
||||
{
|
||||
if (renders.Count == 0) return [];
|
||||
var copies = await _db.RenderCopies.ListByRendersAsync([.. renders.Select(r => r.Id)], cancellationToken).ConfigureAwait(false);
|
||||
var sequences = new Dictionary<Guid, Sequence?>();
|
||||
var archives = new Dictionary<Guid, Archive?>();
|
||||
var projects = new Dictionary<Guid, string?>();
|
||||
var versions = new Dictionary<Guid, int?>();
|
||||
var items = new List<VideoItem>(renders.Count);
|
||||
foreach (var render in renders)
|
||||
{
|
||||
if (!sequences.TryGetValue(render.SequenceId, out var sequence))
|
||||
sequences[render.SequenceId] = sequence = await _db.Sequences.GetAsync(render.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (sequence is null) continue;
|
||||
if (!archives.TryGetValue(sequence.ArchiveId, out var archive))
|
||||
archives[sequence.ArchiveId] = archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false);
|
||||
string? projectName = null;
|
||||
if (render.ProjectId is { } projectId && !projects.TryGetValue(projectId, out projectName))
|
||||
projects[projectId] = projectName = (await _db.Projects.GetAsync(projectId, cancellationToken).ConfigureAwait(false))?.Name;
|
||||
int? number = null;
|
||||
if (render.ProjectVersionId is { } versionId && !versions.TryGetValue(versionId, out number))
|
||||
versions[versionId] = number = (await _db.Projects.GetVersionAsync(versionId, cancellationToken).ConfigureAwait(false))?.Number;
|
||||
var full = archive is null || Path.IsPathRooted(render.OutputPath) ? render.OutputPath : SyncService.RenderFile(archive, render);
|
||||
items.Add(new VideoItem
|
||||
{
|
||||
Render = render,
|
||||
SequenceTitle = sequence.DisplayTitle,
|
||||
SequenceFirstCapture = sequence.FirstCapture,
|
||||
ProjectName = projectName,
|
||||
ProjectVersionNumber = projectName is null ? null : number,
|
||||
FullPath = full,
|
||||
Missing = !File.Exists(full) && !Directory.Exists(full),
|
||||
Copies = copies.TryGetValue(render.Id, out var made) ? made : [],
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private async Task<Archive?> ArchiveOfAsync(Dictionary<Guid, Archive?> known, Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) is not { } sequence) return null;
|
||||
if (!known.TryGetValue(sequence.ArchiveId, out var archive))
|
||||
known[sequence.ArchiveId] = archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false);
|
||||
return archive;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Processing;
|
||||
|
||||
namespace Chronos.Data.Videos;
|
||||
|
||||
/// <summary>One file of a trashed image sequence, as it was when it went: its path inside the folder, size and SHA-256.</summary>
|
||||
internal sealed record VideoTrashFile(string Path, long Size, string Sha256);
|
||||
|
||||
/// <summary>
|
||||
/// What the trash keeps next to a deleted render (decision 17): the render's row, where its file was, the SHA-256 it is
|
||||
/// restored against (each file's, for an image sequence's folder), its sequence, and who deleted it when.
|
||||
/// </summary>
|
||||
/// <param name="Name">The file (or folder) name inside the entry's folder: the render's own name.</param>
|
||||
/// <param name="OriginalPath">The absolute path the render was at.</param>
|
||||
/// <param name="SequenceFolder">The sequence's archive-relative folder at deletion: a restore follows a Reorganize since.</param>
|
||||
internal sealed record VideoTrashRecord(Render Render, string Name, string OriginalPath, Guid ArchiveId, Guid SequenceId, string SequenceTitle,
|
||||
string SequenceFolder, string? Sha256, IReadOnlyList<VideoTrashFile>? Files, int FileCount, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy);
|
||||
|
||||
/// <summary>
|
||||
/// The videos area of an archive's trash (owner review 1, R9, decisions 17 and 18): <c>.chronos/trash/videos/</c>, which
|
||||
/// holds a folder per deleted render (<c><render id>-<UTC ticks></c>, the entry name without its
|
||||
/// <see cref="VideoTrashNames.Prefix"/>) with the render's file or folder inside, and its record next to it. A delete runs
|
||||
/// under the sequence's lease: the record is written first under a pending name (the journal, never listed), then the file
|
||||
/// moves (renamed on its volume; copied, verified and deleted from another one), then the row goes and the record takes its
|
||||
/// name. A delete a crash interrupted is settled by <see cref="RecoverAsync"/>: completed when the file reached the
|
||||
/// trash, undone otherwise. Records live under <c>trash/videos/</c>, so an older Chronos never reads one as a sequence's.
|
||||
/// </summary>
|
||||
internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
|
||||
{
|
||||
private const string RecordExtension = ".json";
|
||||
|
||||
/// <summary>The suffix of a record whose delete is under way: the journal a crash leaves.</summary>
|
||||
internal const string PendingSuffix = ".pending";
|
||||
|
||||
private const string PartSuffix = ".part";
|
||||
|
||||
/// <summary>
|
||||
/// The suffix of a marker next to an entry's folder naming a source a copy could not remove after it verified (a file
|
||||
/// held open): settled by <see cref="RecoverAsync"/>.
|
||||
/// </summary>
|
||||
internal const string LeftoverSuffix = ".leftover";
|
||||
|
||||
/// <summary>Tests: move as if the trash were on another volume (copy, verify, delete).</summary>
|
||||
internal bool ForceCopy { get; set; }
|
||||
|
||||
/// <summary>Tests: stop a delete right after its file moved, as a crash would (the journal stays).</summary>
|
||||
internal bool CrashAfterMove { get; set; }
|
||||
|
||||
/// <summary>The videos area of an archive's trash.</summary>
|
||||
public static string Directory(ArchivePaths archive) => Path.Combine(SequenceTrash.TrashDirectory(archive), VideoTrashNames.FolderName);
|
||||
|
||||
/// <summary>The entry's folder and record on disk.</summary>
|
||||
internal static (string Folder, string Record) Location(ArchivePaths paths, string name)
|
||||
{
|
||||
var folder = Path.Combine(Directory(paths), DiskName(name));
|
||||
return (folder, folder + RecordExtension);
|
||||
}
|
||||
|
||||
/// <summary>The videos entries of an archive's trash (records whose folder is gone, or whose delete is under way, left out).</summary>
|
||||
internal static IReadOnlyList<TrashEntry> List(Archive archive, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = Directory(new ArchivePaths(archive.RootPath));
|
||||
if (!System.IO.Directory.Exists(folder)) return [];
|
||||
var entries = new List<TrashEntry>();
|
||||
foreach (var path in System.IO.Directory.EnumerateFiles(folder, "*" + RecordExtension))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (!path.EndsWith(RecordExtension, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var disk = Path.GetFileNameWithoutExtension(path);
|
||||
if (!System.IO.Directory.Exists(Path.Combine(folder, disk)) || ReadRecord(path) is not { } record) continue;
|
||||
entries.Add(Entry(archive.Id, VideoTrashNames.Prefix + disk, record));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>A videos entry as the trash lists it, read from its record now; null when it is not one or cannot be read.</summary>
|
||||
internal static TrashEntry? ReadListed(ArchivePaths paths, Guid archiveId, string name) =>
|
||||
VideoTrashNames.IsEntryName(name) && ReadRecord(Location(paths, name).Record) is { } record ? Entry(archiveId, name, record) : null;
|
||||
|
||||
/// <summary>
|
||||
/// Moves <paramref name="render"/>'s file into the trash with its record, and removes its row (its sequence's render count
|
||||
/// recounted); a render whose file is missing loses only its row. Returns the entry made; null when only the row went
|
||||
/// (or the render was gone already).
|
||||
/// </summary>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">Another writer holds the sequence.</exception>
|
||||
internal async Task<TrashEntry?> DeleteAsync(Archive archive, Render render, string? deletedBy, CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var sequence = await db.Sequences.GetAsync(render.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
await using (sequence is null ? null : await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (await db.Renders.GetAsync(render.Id, cancellationToken).ConfigureAwait(false) is not { } row) return null;
|
||||
var source = Sync.SyncService.RenderFile(archive, row);
|
||||
var isFile = File.Exists(source);
|
||||
if (!isFile && !System.IO.Directory.Exists(source))
|
||||
{
|
||||
await db.Renders.DeleteAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
Log.Info("videos", $"Render {row.Id} ({row.OutputPath}) removed from the index: its file is missing");
|
||||
return null;
|
||||
}
|
||||
string? sha = null;
|
||||
IReadOnlyList<VideoTrashFile>? files = null;
|
||||
long bytes;
|
||||
if (isFile)
|
||||
{
|
||||
// Hashed now, under the lease, whatever the row says: the record keeps the bytes that go into the trash, which a
|
||||
// restore checks. A file changed in place since it was recorded (or never hashed, before migration 0010) has its
|
||||
// row brought up to date, so it is never trashed under a hash it can no longer be restored against.
|
||||
sha = await ContentHash.Sha256Async(source, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (!string.Equals(sha, row.Sha256, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (row.Sha256 is not null) Log.Warning("videos", $"{source} changed since it was recorded; it goes to the trash as it is now");
|
||||
await db.Renders.SetSha256Async(row.Id, sha, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
bytes = new FileInfo(source).Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
files = await HashFolderAsync(source, cancellationToken).ConfigureAwait(false);
|
||||
bytes = files.Sum(f => f.Size);
|
||||
}
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var name = VideoTrashNames.EntryName(row.Id, now);
|
||||
var (entryFolder, recordPath) = Location(paths, name);
|
||||
var fileName = Path.GetFileName(source.TrimEnd('/', '\\'));
|
||||
var record = new VideoTrashRecord(row with { Sha256 = sha ?? row.Sha256 }, fileName, source, archive.Id, row.SequenceId,
|
||||
sequence?.DisplayTitle ?? fileName, sequence?.Folder ?? string.Empty, sha, files, files?.Count ?? 1, bytes, now, deletedBy);
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, SequenceTrash.EntryLease(name), writer.Options.Owner, writer.Options.LeaseWait,
|
||||
writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
System.IO.Directory.CreateDirectory(entryFolder);
|
||||
// The journal first: a crash from here on is settled by RecoverAsync.
|
||||
AtomicFile.WriteAllText(recordPath + PendingSuffix, JsonSerializer.Serialize(record, VideoTrashJson.Default.VideoTrashRecord));
|
||||
var target = Path.Combine(entryFolder, fileName);
|
||||
bool removed;
|
||||
try
|
||||
{
|
||||
removed = await MoveAsync(source, target, record, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// A file is open elsewhere, the copy did not verify, or the move was cancelled before the verified copy took
|
||||
// its name in the trash: nothing moved, the render stays where it was.
|
||||
Log.Warning("videos", $"{source} could not move to the trash; it stays where it is", ex);
|
||||
Undo(target, entryFolder, recordPath);
|
||||
throw;
|
||||
}
|
||||
if (CrashAfterMove) throw new IOException("Simulated crash after the move.");
|
||||
// The file is in the trash (verified, when copied): the delete is done, its row goes too, to the end, whatever
|
||||
// the caller cancels meanwhile. A source a copy could not remove stays whole and is left for RecoverAsync.
|
||||
await db.Renders.DeleteAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
if (!removed) MarkLeftover(entryFolder, source);
|
||||
Publish(recordPath);
|
||||
}
|
||||
Log.Info("videos", $"{source} moved to the trash ({name}, {bytes} bytes)");
|
||||
return Entry(archive.Id, name, record);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings a videos entry back: its file re-hashed against its record (refused on a mismatch), its sequence in the index
|
||||
/// (refused otherwise: restore the sequence first), then moved back where it was (into the sequence's folder as it is now
|
||||
/// after a Reorganize; a free name when its own is taken) and its row inserted again with the same render id.
|
||||
/// </summary>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
/// <exception cref="VideoLibraryException"><see cref="VideoErrors.HashMismatch"/> or <see cref="VideoErrors.SequenceGone"/>; nothing moved.</exception>
|
||||
/// <exception cref="InvalidOperationException">The index holds a render of that id already; nothing moved.</exception>
|
||||
internal async Task<Render> RestoreAsync(Archive archive, string name, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(name);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
if (!VideoTrashNames.IsEntryName(name)) throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
var (entryFolder, recordPath) = Location(paths, name);
|
||||
if (!System.IO.Directory.Exists(entryFolder) || ReadRecord(recordPath) is not { } record)
|
||||
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, SequenceTrash.EntryLease(name), writer.Options.Owner, writer.Options.LeaseWait,
|
||||
writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var trashed = Path.Combine(entryFolder, record.Name);
|
||||
if (!File.Exists(trashed) && !System.IO.Directory.Exists(trashed)) throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
if (await db.Renders.GetAsync(record.Render.Id, cancellationToken).ConfigureAwait(false) is not null)
|
||||
throw new InvalidOperationException(Loc.L("Server.Error.RenderExists"));
|
||||
var sequence = await db.Sequences.GetAsync(record.SequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new VideoLibraryException(VideoErrors.SequenceGone, Loc.L("Errors.Videos.SequenceGone", record.SequenceTitle));
|
||||
if (!await MatchesAsync(trashed, record, cancellationToken).ConfigureAwait(false))
|
||||
throw new VideoLibraryException(VideoErrors.HashMismatch, Loc.L("Errors.Videos.TrashMismatch"));
|
||||
Render restored;
|
||||
bool removed;
|
||||
await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// The original this entry's delete could not remove goes first (still what went into the trash), so the
|
||||
// render takes its own name back.
|
||||
await SettleLeftoverAsync(paths, entryFolder, cancellationToken).ConfigureAwait(false);
|
||||
// A name a render of this process is writing counts as taken, and stays reserved until the move is done: the
|
||||
// render's commit would otherwise land on the restored file (and commits never overwrite, for other processes).
|
||||
using var names = new OutputNames();
|
||||
var target = names.Reserve(taken => Destination(paths, record, sequence, taken));
|
||||
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
removed = await MoveAsync(trashed, target, record, cancellationToken).ConfigureAwait(false);
|
||||
restored = record.Render with { SequenceId = sequence.Id, OutputPath = Stored(paths, target), Sha256 = record.Sha256 };
|
||||
try
|
||||
{
|
||||
await db.Renders.InsertAsync(restored, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("videos", $"{target} could not be indexed again; it goes back into the trash", ex);
|
||||
// A copy that could not remove the trashed one left it whole: the copy alone goes.
|
||||
if (!removed) RemoveSource(target);
|
||||
else if (!await MoveAsync(target, trashed, record, CancellationToken.None).ConfigureAwait(false))
|
||||
Log.Warning("videos", $"{target} went back into the trash but is left over where it was restored to");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
// The render is back: its trash copy goes (left for RecoverAsync when a copy could not remove it), then its record.
|
||||
if (!removed) MarkLeftover(entryFolder, trashed);
|
||||
File.Delete(recordPath);
|
||||
if (removed) RemoveEmpty(entryFolder);
|
||||
Log.Info("videos", $"{name} restored to {restored.OutputPath}");
|
||||
return restored;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles the deletes a crash interrupted in <paramref name="archive"/>'s trash (their pending records): a delete whose
|
||||
/// file reached the trash is completed (the row goes, the record takes its name), any other is undone (what was copied
|
||||
/// goes, the render stays where it is). Each runs under its sequence's lease when the index still holds the sequence.
|
||||
/// </summary>
|
||||
internal async Task<int> RecoverAsync(Archive archive, CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var folder = Directory(paths);
|
||||
if (!System.IO.Directory.Exists(folder) || ArchiveVolume.Probe(paths) != ArchiveAvailability.Online) return 0;
|
||||
var settled = 0;
|
||||
foreach (var pending in System.IO.Directory.EnumerateFiles(folder, "*" + RecordExtension + PendingSuffix).ToList())
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var recordPath = pending[..^PendingSuffix.Length];
|
||||
var entryFolder = recordPath[..^RecordExtension.Length];
|
||||
if (ReadRecord(pending) is not { } record)
|
||||
{
|
||||
Log.Warning("videos", $"The pending trash record {pending} cannot be read; it stays");
|
||||
continue;
|
||||
}
|
||||
var sequence = await db.Sequences.GetAsync(record.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
await using (sequence is null ? null : await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!File.Exists(pending)) continue;
|
||||
var target = Path.Combine(entryFolder, record.Name);
|
||||
if (File.Exists(target) || System.IO.Directory.Exists(target))
|
||||
{
|
||||
// The file reached the trash (a copy only takes its name once verified): the delete completes. A source still
|
||||
// there is the original a copy left behind, unless something new took its name since.
|
||||
if (await db.Renders.GetAsync(record.Render.Id, cancellationToken).ConfigureAwait(false) is not null)
|
||||
await db.Renders.DeleteAsync(record.Render.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
if ((File.Exists(record.OriginalPath) || System.IO.Directory.Exists(record.OriginalPath))
|
||||
&& await MatchesAsync(record.OriginalPath, record, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
RemoveSource(record.OriginalPath);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"{record.OriginalPath} is still in use; it is removed at the next start", ex);
|
||||
MarkLeftover(entryFolder, record.OriginalPath);
|
||||
}
|
||||
}
|
||||
Publish(recordPath);
|
||||
Log.Info("videos", $"An interrupted delete of {record.OriginalPath} completed");
|
||||
}
|
||||
else
|
||||
{
|
||||
// The file never reached the trash: what was copied goes, and the render stays as it is.
|
||||
Undo(target, entryFolder, recordPath);
|
||||
Log.Info("videos", $"An interrupted delete of {record.OriginalPath} was undone");
|
||||
}
|
||||
settled++;
|
||||
}
|
||||
}
|
||||
foreach (var marker in System.IO.Directory.EnumerateFiles(folder, "*" + LeftoverSuffix).ToList())
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (!marker.EndsWith(LeftoverSuffix, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var entryFolder = marker[..^LeftoverSuffix.Length];
|
||||
var sequence = ReadRecord(entryFolder + RecordExtension) is { } record
|
||||
? await db.Sequences.GetAsync(record.SequenceId, cancellationToken).ConfigureAwait(false)
|
||||
: null;
|
||||
await using (sequence is null ? null : await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (await SettleLeftoverAsync(paths, entryFolder, cancellationToken).ConfigureAwait(false)) settled++;
|
||||
}
|
||||
}
|
||||
return settled;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles what a move that copied left at its source because it could not remove it (a file held open): the original of
|
||||
/// a delete, removed once it still holds what went into the trash and no render was recorded there since; the trash copy
|
||||
/// of a restore, removed once the render is back in the index. Its marker goes either way, unless removing fails again
|
||||
/// (the next start tries again). True when the marker was settled.
|
||||
/// </summary>
|
||||
private async Task<bool> SettleLeftoverAsync(ArchivePaths paths, string entryFolder, CancellationToken cancellationToken)
|
||||
{
|
||||
var marker = entryFolder + LeftoverSuffix;
|
||||
if (!File.Exists(marker)) return false;
|
||||
try
|
||||
{
|
||||
var path = File.ReadAllText(marker).Trim();
|
||||
var record = ReadRecord(entryFolder + RecordExtension);
|
||||
var indexed = record is not null && await db.Renders.GetAsync(record.Render.Id, cancellationToken).ConfigureAwait(false) is not null;
|
||||
var inside = path.Length > 0 && Path.GetFullPath(path).StartsWith(Path.GetFullPath(entryFolder) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
|
||||
if (path.Length > 0 && (File.Exists(path) || System.IO.Directory.Exists(path)))
|
||||
{
|
||||
if (inside && (record is null || indexed))
|
||||
{
|
||||
// A restored render's trash copy: the render is back, the copy goes, and a record a crash left with it.
|
||||
RemoveSource(path);
|
||||
if (record is not null) File.Delete(entryFolder + RecordExtension);
|
||||
RemoveEmpty(entryFolder);
|
||||
}
|
||||
else if (!inside && record is not null && !indexed)
|
||||
{
|
||||
var stored = Stored(paths, path);
|
||||
var recorded = await db.Renders.ListBySequenceAsync(record.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (recorded.All(r => r.OutputPath != stored) && await MatchesAsync(path, record, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
RemoveSource(path);
|
||||
Log.Info("videos", $"{path}, left over by a delete, removed");
|
||||
}
|
||||
}
|
||||
}
|
||||
File.Delete(marker);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"What {marker} names could not be removed yet; the next start tries again", ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Records that a move's source stays at <paramref name="path"/> for <see cref="SettleLeftoverAsync"/>; a failure is logged.</summary>
|
||||
private static void MarkLeftover(string entryFolder, string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
AtomicFile.WriteAllText(entryFolder + LeftoverSuffix, path);
|
||||
Log.Warning("videos", $"{path} could not be removed after it was copied; it is removed at the next start");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"{path} is left over and could not be recorded as such", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SHA-256 of every file of an image sequence's folder (paths inside it, forward slashes, in order); the folder's
|
||||
/// own render records no hash (decision 14).
|
||||
/// </summary>
|
||||
internal static async Task<IReadOnlyList<VideoTrashFile>> HashFolderAsync(string folder, CancellationToken cancellationToken)
|
||||
{
|
||||
var files = new List<VideoTrashFile>();
|
||||
foreach (var file in System.IO.Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal))
|
||||
{
|
||||
var sha = await ContentHash.Sha256Async(file, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
files.Add(new VideoTrashFile(Path.GetRelativePath(folder, file).Replace('\\', '/'), new FileInfo(file).Length, sha));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/// <summary>Whether the file or folder at <paramref name="path"/> holds what <paramref name="record"/> says, re-hashed now.</summary>
|
||||
private static async Task<bool> MatchesAsync(string path, VideoTrashRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
if (record.Files is { } expected)
|
||||
{
|
||||
if (!System.IO.Directory.Exists(path)) return false;
|
||||
var actual = await HashFolderAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
return actual.Count == expected.Count && actual.Zip(expected).All(p =>
|
||||
p.First.Path == p.Second.Path && p.First.Size == p.Second.Size && string.Equals(p.First.Sha256, p.Second.Sha256, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
if (!File.Exists(path)) return false;
|
||||
if (record.Sha256 is null) return true;
|
||||
var sha = await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
return string.Equals(sha, record.Sha256, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a render's file or folder from <paramref name="from"/> to <paramref name="to"/>: renamed on one volume; copied
|
||||
/// under a part name, verified against <paramref name="record"/>, renamed and the source removed across volumes. Once the
|
||||
/// verified copy took its name the move is done: a source that cannot be removed then (a file held open) stays whole
|
||||
/// (<see cref="RemoveSource"/>) and the move returns false, for the caller to record it as left over.
|
||||
/// </summary>
|
||||
/// <returns>True when the source is gone; false when the copy is in place and the source left over.</returns>
|
||||
/// <exception cref="IOException">The move failed before it took its name (nothing moved, no part copy left), the copy not verifying among others.</exception>
|
||||
private async Task<bool> MoveAsync(string from, string to, VideoTrashRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = System.IO.Directory.Exists(from);
|
||||
if (!ForceCopy && SameVolume(from, to))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (folder) System.IO.Directory.Move(from, to);
|
||||
else File.Move(from, to, overwrite: false);
|
||||
return true;
|
||||
}
|
||||
catch (IOException) when (folder && !System.IO.Directory.Exists(to) && System.IO.Directory.Exists(from))
|
||||
{
|
||||
// Another mount on the same root (Linux), or a file of the folder held open (Windows): copied instead.
|
||||
}
|
||||
}
|
||||
var part = to + PartSuffix;
|
||||
try
|
||||
{
|
||||
DeletePath(part);
|
||||
if (folder)
|
||||
{
|
||||
foreach (var file in System.IO.Directory.EnumerateFiles(from, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var target = Path.Combine(part, Path.GetRelativePath(from, file));
|
||||
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
await CopyFileAsync(file, target, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
System.IO.Directory.CreateDirectory(part);
|
||||
}
|
||||
else
|
||||
{
|
||||
await CopyFileAsync(from, part, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (!await MatchesAsync(part, record, cancellationToken).ConfigureAwait(false)) throw new IOException(Loc.L("Errors.Videos.TrashMismatch"));
|
||||
if (folder) System.IO.Directory.Move(part, to);
|
||||
else File.Move(part, to, overwrite: false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
try
|
||||
{
|
||||
DeletePath(part);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"The part copy {part} could not be removed", ex);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
try
|
||||
{
|
||||
RemoveSource(from);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"{from} was copied to {to} but could not be removed: it stays whole", ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the source of a verified copy all or nothing: a file is deleted; a folder is renamed aside first (which fails
|
||||
/// at once while any of its files is open on Windows, leaving it whole), then erased.
|
||||
/// </summary>
|
||||
private static void RemoveSource(string path)
|
||||
{
|
||||
if (System.IO.Directory.Exists(path))
|
||||
{
|
||||
var full = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
var aside = Path.Combine(Path.GetDirectoryName(full)!, "." + Path.GetFileName(full) + ".removing-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
System.IO.Directory.Move(full, aside);
|
||||
try
|
||||
{
|
||||
SequenceTrash.Erase(aside);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Its name is free and its content is in the trash already: what could not be erased is only left over.
|
||||
Log.Warning("videos", $"{aside} could not be erased whole; it is left over", ex);
|
||||
}
|
||||
}
|
||||
else if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copies a file, flushed to the disk.</summary>
|
||||
internal static async Task CopyFileAsync(string source, string target, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var from = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
await using var to = new FileStream(target, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 20, FileOptions.Asynchronous);
|
||||
await from.CopyToAsync(to, cancellationToken).ConfigureAwait(false);
|
||||
to.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where a restored render goes: where it was (in its sequence's folder as the index has it now), or a free name next to
|
||||
/// it when that one is on disk or <paramref name="taken"/> (an output a render of this process is writing).
|
||||
/// </summary>
|
||||
private static string Destination(ArchivePaths paths, VideoTrashRecord record, Sequence sequence, Func<string, bool> taken)
|
||||
{
|
||||
var stored = record.Render.OutputPath;
|
||||
string full;
|
||||
if (Path.IsPathRooted(stored)) full = stored;
|
||||
else
|
||||
{
|
||||
var from = record.SequenceFolder;
|
||||
var rebased = from.Length > 0 && from != sequence.Folder && stored.StartsWith(from + "/", StringComparison.Ordinal)
|
||||
? (sequence.Folder.Length == 0 ? stored[(from.Length + 1)..] : sequence.Folder + stored[from.Length..])
|
||||
: stored;
|
||||
full = paths.FromRelative(rebased);
|
||||
}
|
||||
return File.Exists(full) || System.IO.Directory.Exists(full) || taken(full)
|
||||
? VideosFolder.FreeName(Path.GetDirectoryName(full)!, Path.GetFileName(full), record.Files is not null, taken)
|
||||
: full;
|
||||
}
|
||||
|
||||
/// <summary>Archive-relative for outputs inside the archive (as renders are recorded), absolute otherwise.</summary>
|
||||
internal static string Stored(ArchivePaths paths, string output)
|
||||
{
|
||||
var relative = paths.ToRelative(output);
|
||||
return relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) ? output : relative;
|
||||
}
|
||||
|
||||
private static bool SameVolume(string a, string b) =>
|
||||
string.Equals(Path.GetPathRoot(Path.GetFullPath(a)), Path.GetPathRoot(Path.GetFullPath(b)), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Removes what a delete that did not complete left in the trash: the part copy, the entry's folder and its journal.</summary>
|
||||
private static void Undo(string target, string entryFolder, string recordPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
DeletePath(target + PartSuffix);
|
||||
RemoveEmpty(entryFolder);
|
||||
File.Delete(recordPath + PendingSuffix);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"What an unfinished delete left in {entryFolder} could not be removed; the next start settles it", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Lists an entry whose delete completed: its record takes its own name. A failure (logged) is settled by the next <see cref="RecoverAsync"/>.</summary>
|
||||
private static void Publish(string recordPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(recordPath + PendingSuffix, recordPath, overwrite: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"Trash record {recordPath} keeps its pending name; the next start lists it", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RemoveEmpty(string folder)
|
||||
{
|
||||
if (System.IO.Directory.Exists(folder) && !System.IO.Directory.EnumerateFileSystemEntries(folder).Any()) System.IO.Directory.Delete(folder);
|
||||
}
|
||||
|
||||
private static void DeletePath(string path)
|
||||
{
|
||||
if (System.IO.Directory.Exists(path)) SequenceTrash.Erase(path);
|
||||
else if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
|
||||
/// <summary>The folder name of an entry: its name without <see cref="VideoTrashNames.Prefix"/>, never a path.</summary>
|
||||
private static string DiskName(string name) =>
|
||||
Path.GetFileName(name.StartsWith(VideoTrashNames.Prefix, StringComparison.Ordinal) ? name[VideoTrashNames.Prefix.Length..] : name);
|
||||
|
||||
/// <summary>
|
||||
/// A videos entry as the trash lists it: titled by its sequence, with the path the render was deleted from (its file
|
||||
/// name last, which the panel's restore message and the desktop's row show).
|
||||
/// </summary>
|
||||
private static TrashEntry Entry(Guid archiveId, string name, VideoTrashRecord record)
|
||||
{
|
||||
var stored = record.Render.OutputPath.Replace('\\', '/').TrimEnd('/');
|
||||
var title = string.IsNullOrWhiteSpace(record.SequenceTitle) ? record.Name : record.SequenceTitle;
|
||||
return new TrashEntry(archiveId, name, record.SequenceId, title, stored, 0, record.FileCount, record.Bytes,
|
||||
record.DeletedAt, record.DeletedBy, TrashKind.Videos);
|
||||
}
|
||||
|
||||
private static VideoTrashRecord? ReadRecord(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), VideoTrashJson.Default.VideoTrashRecord) : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("videos", $"Trash record {path} is unreadable", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
IgnoreReadOnlyProperties = true)]
|
||||
[JsonSerializable(typeof(VideoTrashRecord))]
|
||||
internal sealed partial class VideoTrashJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Chronos.Data.Videos;
|
||||
|
||||
/// <summary>
|
||||
/// The videos folder (owner review 1, R9, decision 15): a flat folder outside every archive and the workspace that renders
|
||||
/// are copied into, each under its own name or, when that is taken, "name (2)", "name (3)"… (the export naming rule). A
|
||||
/// copy is written as <c>.incoming-<render id>.part</c> first and takes its name only once verified.
|
||||
/// </summary>
|
||||
public static class VideosFolder
|
||||
{
|
||||
/// <summary>The prefix of a copy being written; never a name a finished copy takes.</summary>
|
||||
public const string PartPrefix = ".incoming-";
|
||||
|
||||
/// <summary>The suffix of a copy being written.</summary>
|
||||
public const string PartSuffix = ".part";
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="folder"/> cannot be the videos folder: <see cref="VideoErrors.FolderUnset"/> when blank,
|
||||
/// <see cref="VideoErrors.FolderInvalid"/> when it is not an absolute path or lies inside (or is) one of
|
||||
/// <paramref name="protectedRoots"/> (the archive roots, the workspace); null when it can.
|
||||
/// </summary>
|
||||
public static string? Problem(string? folder, IEnumerable<string?> protectedRoots)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(protectedRoots);
|
||||
if (string.IsNullOrWhiteSpace(folder)) return VideoErrors.FolderUnset;
|
||||
string full;
|
||||
try
|
||||
{
|
||||
if (!Path.IsPathFullyQualified(folder)) return VideoErrors.FolderInvalid;
|
||||
full = Normalize(folder);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return VideoErrors.FolderInvalid;
|
||||
}
|
||||
foreach (var root in protectedRoots)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(root)) continue;
|
||||
if (IsInside(full, Normalize(root))) return VideoErrors.FolderInvalid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="path"/> is <paramref name="root"/> or lies below it (both full and normalised).</summary>
|
||||
internal static bool IsInside(string path, string root)
|
||||
{
|
||||
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
if (string.Equals(path, root, comparison)) return true;
|
||||
var prefix = root.EndsWith(Path.DirectorySeparatorChar) ? root : root + Path.DirectorySeparatorChar;
|
||||
return path.StartsWith(prefix, comparison);
|
||||
}
|
||||
|
||||
/// <summary>The full path without a trailing separator (a drive or file-system root keeps its own).</summary>
|
||||
internal static string Normalize(string path)
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
var trimmed = full.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
return trimmed.Length == 0 || trimmed.EndsWith(':') ? full : trimmed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path a copy named <paramref name="fileName"/> takes in <paramref name="folder"/>: the name itself when free, else
|
||||
/// "name (2).ext", "name (3).ext"… (a folder's name, an image sequence, has no extension to keep).
|
||||
/// </summary>
|
||||
/// <param name="isFolder">The copy is an image sequence's folder: its whole name is the stem.</param>
|
||||
/// <param name="taken">Names in use besides those on disk (outputs a render of this process is writing).</param>
|
||||
public static string FreeName(string folder, string fileName, bool isFolder = false, Func<string, bool>? taken = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(fileName);
|
||||
var name = Path.GetFileName(fileName);
|
||||
var (stem, extension) = isFolder ? (name, string.Empty) : (Path.GetFileNameWithoutExtension(name), Path.GetExtension(name));
|
||||
for (var n = 1; ; n++)
|
||||
{
|
||||
var candidate = Path.Combine(folder, (n == 1 ? stem : string.Create(CultureInfo.InvariantCulture, $"{stem} ({n})")) + extension);
|
||||
if (!File.Exists(candidate) && !Directory.Exists(candidate) && taken?.Invoke(candidate) != true) return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where the copy of render <paramref name="renderId"/> is written in <paramref name="folder"/> until it is verified.</summary>
|
||||
public static string PartPath(string folder, Guid renderId) => Path.Combine(folder, PartPrefix + renderId.ToString("N") + PartSuffix);
|
||||
|
||||
/// <summary>
|
||||
/// The free bytes of the volume of <paramref name="folder"/>: what <paramref name="measure"/> says (a host's own measure,
|
||||
/// tests), else the drive's; null when unknown.
|
||||
/// </summary>
|
||||
public static long? FreeBytes(string folder, Func<string, long?>? measure = null)
|
||||
{
|
||||
if (measure?.Invoke(folder) is { } measured) return measured;
|
||||
try
|
||||
{
|
||||
var root = Path.GetPathRoot(Path.GetFullPath(folder));
|
||||
return string.IsNullOrEmpty(root) ? null : new DriveInfo(root).AvailableFreeSpace;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user