From b746aff45d79c96885254744161989f637ba0891 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 27 Nov 2026 23:08:38 +0100 Subject: [PATCH] E3: formati e fotogrammi nella copia verso le cartelle esterne MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La richiesta di copia porta i formati («Copia in…» per foto e video, poi la destinazione, poi le impostazioni), i fotogrammi dei video e la «Copia di nuovo» di una sola copia. Il piano prevede convertiti, copiati com'è e fotogrammi; il lavoro si ricorda di fotogrammi ed identità esatta per la ripresa. La copia converte prima dei controlli di spazio e di FAT32, adotta un file già presente solo se lunghezza e SHA-256 della conversione coincidono, e prende i fotogrammi di un video in un solo passaggio, ognuno con il suo istante esatto come identità. Un file copiato in qualunque forma che non sia un fotogramma è «già copiato»; un fotogramma non rende mai copiato il file (nuovo segno FrameOnly). Le note sono un elenco di codici, con i testi italiani nuovi e il rapporto che mostra i file copiati con una nota. Le prove dell'archivio e dei piani delle query seguono le nuove ricerche; due prove nuove coprono una foto convertita e un fotogramma. Co-Authored-By: Claude Opus 5.5 --- src/Febe.Core/Export/ExportConversion.cs | 87 ++ src/Febe.Core/Export/ExportConversions.cs | 99 ++ src/Febe.Core/Export/ExportCopier.cs | 922 ++++++++++++++---- src/Febe.Core/Export/ExportDestinations.cs | 19 +- src/Febe.Core/Export/ExportEnvironment.cs | 17 +- src/Febe.Core/Export/ExportModels.cs | 48 +- src/Febe.Core/Export/ExportPlanner.cs | 326 ++++++- src/Febe.Core/Export/ExportReports.cs | 72 +- src/Febe.Core/Export/ExportRunSettings.cs | 57 +- src/Febe.Core/Export/ExportService.cs | 132 ++- src/Febe.Core/Export/ExportText.cs | 103 +- .../Library/Conversion/MediaConverter.cs | 3 + src/Febe.Core/Storage/IExportStore.cs | 63 +- src/Febe.Data/Stores/ExportFilterSql.cs | 19 +- src/Febe.Data/Stores/ExportStore.cs | 101 +- .../Febe.Tests/Data/ExportConstraintTests.cs | 8 +- tests/Febe.Tests/Data/ExportStoreTests.cs | 25 +- .../Export/ExportConversionTests.cs | 95 ++ .../Export/ExportCopiesFilterTests.cs | 2 +- 19 files changed, 1941 insertions(+), 257 deletions(-) create mode 100644 src/Febe.Core/Export/ExportConversion.cs create mode 100644 src/Febe.Core/Export/ExportConversions.cs create mode 100644 tests/Febe.Tests/Export/ExportConversionTests.cs diff --git a/src/Febe.Core/Export/ExportConversion.cs b/src/Febe.Core/Export/ExportConversion.cs new file mode 100644 index 0000000..92c1f11 --- /dev/null +++ b/src/Febe.Core/Export/ExportConversion.cs @@ -0,0 +1,87 @@ +using System.Security.Cryptography; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; + +namespace Febe.Core.Export; + +/// +/// The conversion of a library file for a copy (tappa E3, WP1.6b): with the files of the +/// export environment, and the hash of content that is only known once written (a remux). +/// +internal static class ExportConversion +{ + /// Prepares the library file at in (never Original). + /// A photo's bytes are not those of . + public static Task PrepareAsync(ExportEnvironment env, string source, Media media, ExportFormat target, string sha256, CancellationToken ct) => + MediaConverter.PrepareAsync(() => env.FileSystem.OpenRandomAccess(source), media.RelativePath!, media.Kind, target, sha256, env.Throttle, ct); + + /// The SHA-256 (lowercase hex) and length of what writes, written nowhere. + public static async Task<(string Sha256, long Length)> HashAsync(Func produce, CancellationToken ct) + { + await using var sink = new HashingSink(); + await produce(sink, ct).ConfigureAwait(false); + return (sink.Finish(), sink.Length); + } + + /// A stream that only hashes and counts what is written to it. + private sealed class HashingSink : Stream + { + private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + private long length; + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => length; + + public override long Position + { + get => length; + set => throw new NotSupportedException(); + } + + public string Finish() => Convert.ToHexStringLower(hash.GetHashAndReset()); + + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + + public override void Write(ReadOnlySpan buffer) + { + hash.AppendData(buffer); + length += buffer.Length; + } + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + Write(buffer.Span); + return ValueTask.CompletedTask; + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + hash.Dispose(); + } + + base.Dispose(disposing); + } + } +} diff --git a/src/Febe.Core/Export/ExportConversions.cs b/src/Febe.Core/Export/ExportConversions.cs new file mode 100644 index 0000000..ffdef0c --- /dev/null +++ b/src/Febe.Core/Export/ExportConversions.cs @@ -0,0 +1,99 @@ +using Febe.Core.Domain; +using Febe.Core.Library.Conversion; + +namespace Febe.Core.Export; + +/// What the plan expects of a file in a format, from its name only (tappa E3: the copy decides on the bytes). +public enum ExportPrediction +{ + /// Copied byte for byte: Original, or already in the format asked. + Whole, + + /// Converted into the format asked. + Converted, + + /// Copied as it is with a note (HEIC, AVIF, raw, GIF, WebM). + AsIs, +} + +/// +/// The format of a copy (spec §4.10 «Conversione del formato», decisions D1, D2 and D5-D7 of tappa E3): which format a +/// file gets in a destination, and what the plan predicts of it from its name. +/// +public static class ExportConversions +{ + /// + /// The format of a file of : the «Copia in…» override of this request, else the destination's, + /// else the general settings' (D1). A value that does not belong to the kind counts as not set. + /// + public static ExportFormat Resolve(MediaKind kind, ExportFormatChoice? request, ExportDestination destination, ExportSettings settings) + { + ArgumentNullException.ThrowIfNull(destination); + ArgumentNullException.ThrowIfNull(settings); + Func fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat : ExportFormats.IsVideoFormat; + var chosen = kind == MediaKind.Photo + ? new[] { request?.Photo, destination.PhotoFormat, settings.PhotoFormat } + : [request?.Video, destination.VideoFormat, settings.VideoFormat]; + foreach (var format in chosen) + { + if (format is { } f && fits(f)) + { + return f; + } + } + + return ExportFormat.Original; + } + + /// The variant a format asks for: Whole for Original, Converted otherwise. + public static ExportVariant VariantOf(ExportFormat format) => format == ExportFormat.Original ? ExportVariant.Whole : ExportVariant.Converted; + + /// + /// What the plan expects, by extension («circa»): Original, or the same format (.jpg/.jpeg, .png, + /// .webp, .mp4) → Whole; HEIC, HEIF, AVIF, raw, GIF and WebM → AsIs; anything else → Converted. + /// + public static ExportPrediction Predict(string relativePath, MediaKind kind, ExportFormat target) + { + ArgumentNullException.ThrowIfNull(relativePath); + if (target == ExportFormat.Original) + { + return ExportPrediction.Whole; + } + + var extension = Path.GetExtension(relativePath).ToLowerInvariant(); + var same = target switch + { + ExportFormat.Jpg => extension is ".jpg" or ".jpeg", + ExportFormat.Png => extension == ".png", + ExportFormat.WebpLossless => extension == ".webp", + ExportFormat.Mp4 => extension == ".mp4", + _ => false, + }; + if (same) + { + return ExportPrediction.Whole; + } + + return AsIsLabel(relativePath) is not null ? ExportPrediction.AsIs : ExportPrediction.Converted; + } + + /// The kind of a file copied as it is, for «3 HEIC copiati come sono»: «HEIC», «AVIF», «raw», «GIF», «WebM»; null otherwise. + public static string? AsIsLabel(string relativePath) + { + ArgumentNullException.ThrowIfNull(relativePath); + var extension = Path.GetExtension(relativePath).ToLowerInvariant(); + return extension switch + { + ".heic" or ".heif" => "HEIC", + ".avif" => "AVIF", + ".gif" => "GIF", + ".webm" => "WebM", + _ when MediaConverter.IsRawExtension(extension) => "raw", + _ => null, + }; + } + + /// The effective identity the plan expects (D2): (Converted, format) when predicted converted, else (Whole, Original). + public static (ExportVariant Variant, ExportFormat Format) PredictedIdentity(string relativePath, MediaKind kind, ExportFormat target) => + Predict(relativePath, kind, target) == ExportPrediction.Converted ? (ExportVariant.Converted, target) : (ExportVariant.Whole, ExportFormat.Original); +} diff --git a/src/Febe.Core/Export/ExportCopier.cs b/src/Febe.Core/Export/ExportCopier.cs index 0084b56..6b6484e 100644 --- a/src/Febe.Core/Export/ExportCopier.cs +++ b/src/Febe.Core/Export/ExportCopier.cs @@ -1,5 +1,8 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Images; using Febe.Core.Domain; using Febe.Core.Library; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Export; @@ -18,6 +21,9 @@ namespace Febe.Core.Export; /// nothing is copied during an engine session: the job waits; /// resumable: every file has its state, and the target path is recorded before its .part exists. /// +/// Tappa E3: a file is converted (before the space check) into the format its item asks, or copied as it is with a +/// note; a file already copied in any form but a frame is «già copiato» (D3); the frames of a video are taken in one +/// batch, each one with its exact instant as identity (D4, D12). /// public sealed class ExportCopier(ExportEnvironment env) { @@ -66,6 +72,8 @@ public sealed class ExportCopier(ExportEnvironment env) x.SetFileTime = library.SetFileTimeToPublication; x.OneOnly = settings.SamePost == SamePostCopies.OneOnly; x.CopyAgain = await ExportRunSettings.GetCopyAgainAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false); + x.Frames = await ExportRunSettings.GetFramesAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false); + x.Exact = await ExportRunSettings.GetExactAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false); x.Effective = await new ExportDestinations(_env).ResolveAllAsync(ct).ConfigureAwait(false); var summary = await store.GetRunSummaryAsync(runId, ct).ConfigureAwait(false); x.FilesTotal = summary.Total; @@ -73,47 +81,41 @@ public sealed class ExportCopier(ExportEnvironment env) x.ByState = new Dictionary(summary.ByState); x.BytesTotal = await PendingBytesAsync(runId, ct).ConfigureAwait(false); - var groupFiles = 0; - long groupBytes = 0; - long after = 0; - while (true) + var pending = new PendingItems(store, runId); + while (await pending.PeekAsync(ct).ConfigureAwait(false) is { } item) { - var page = await store.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); - if (page.Count == 0) + ct.ThrowIfCancellationRequested(); + if (item.Variant == ExportVariant.Frame) { - break; + // The following frames of the same video and format are one batch, also across pages (WP1.7). + var batch = new List { pending.Take() }; + while (await pending.PeekAsync(ct).ConfigureAwait(false) is { Variant: ExportVariant.Frame } next + && next.MediaId == item.MediaId && next.Format == item.Format) + { + batch.Add(pending.Take()); + } + + if (await ProcessFrameBatchAsync(x, batch, ct).ConfigureAwait(false) is { } paused) + { + return await PauseAsync(x, paused).ConfigureAwait(false); + } + + continue; } - after = page[^1].Id; - foreach (var item in page) + pending.Take(); + if (await BeforeItemAsync(x, ct).ConfigureAwait(false) is { } problem) { - ct.ThrowIfCancellationRequested(); - if (groupFiles == 0 && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem) - { - return await PauseAsync(x, problem).ConfigureAwait(false); - } - - await WaitOutsideSessionAsync(x, ct).ConfigureAwait(false); - var result = await ProcessItemAsync(x, item, ct).ConfigureAwait(false); - if (result.Pause is { } pause) - { - return await PauseAsync(x, pause).ConfigureAwait(false); - } - - x.FilesDone++; - x.BytesDone += result.Bytes; - x.ByState[ExportItemState.Pending] = Math.Max(0, x.ByState.GetValueOrDefault(ExportItemState.Pending) - 1); - x.ByState[result.State] = x.ByState.GetValueOrDefault(result.State) + 1; - groupFiles++; - groupBytes += result.Bytes; - if (groupFiles >= Math.Max(1, _env.GroupFiles) || groupBytes >= _env.GroupBytes) - { - groupFiles = 0; - groupBytes = 0; - } - - x.Report(_env, ExportPhase.Copying, result.Path); + return await PauseAsync(x, problem).ConfigureAwait(false); } + + var result = await ProcessItemAsync(x, item, ct).ConfigureAwait(false); + if (result.Pause is { } pause) + { + return await PauseAsync(x, pause).ConfigureAwait(false); + } + + Account(x, result); } var final = await store.GetRunSummaryAsync(runId, none).ConfigureAwait(false); @@ -176,6 +178,36 @@ public sealed class ExportCopier(ExportEnvironment env) return problem; } + /// Before a file: the probe at the start of each group, then the wait for the end of an engine session. + private async Task BeforeItemAsync(RunContext x, CancellationToken ct) + { + if (x.GroupFiles == 0 && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem) + { + return problem; + } + + await WaitOutsideSessionAsync(x, ct).ConfigureAwait(false); + return null; + } + + /// The counts of one finished item: progress, states, and the group of the probe. + private void Account(RunContext x, ItemResult result) + { + x.FilesDone++; + x.BytesDone += result.Bytes; + x.ByState[ExportItemState.Pending] = Math.Max(0, x.ByState.GetValueOrDefault(ExportItemState.Pending) - 1); + x.ByState[result.State] = x.ByState.GetValueOrDefault(result.State) + 1; + x.GroupFiles++; + x.GroupBytes += result.Written ?? result.Bytes; + if (x.GroupFiles >= Math.Max(1, _env.GroupFiles) || x.GroupBytes >= _env.GroupBytes) + { + x.GroupFiles = 0; + x.GroupBytes = 0; + } + + x.Report(_env, ExportPhase.Copying, result.Path); + } + private async Task PauseAsync(RunContext x, string message) { x.Destination = await ExportPause.PauseAsync(_env, x.Destination, message).ConfigureAwait(false); @@ -194,6 +226,7 @@ public sealed class ExportCopier(ExportEnvironment env) } } + /// The library bytes of the pending files (frames count nothing: their size is not known before). private async Task PendingBytesAsync(long runId, CancellationToken ct) { long total = 0; @@ -209,7 +242,7 @@ public sealed class ExportCopier(ExportEnvironment env) after = page[^1].Id; foreach (var item in page) { - if (item.MediaId is { } id && await _env.Storage.Media.GetAsync(id, ct).ConfigureAwait(false) is { Bytes: { } bytes }) + if (item.Variant != ExportVariant.Frame && item.MediaId is { } id && await _env.Storage.Media.GetAsync(id, ct).ConfigureAwait(false) is { Bytes: { } bytes }) { total += bytes; } @@ -217,18 +250,17 @@ public sealed class ExportCopier(ExportEnvironment env) } } - private async Task ProcessItemAsync(RunContext x, ExportItem item, CancellationToken ct) + /// + /// a. The library file of an item, as the job may use it now: present, of its account, still going to this + /// destination (decisions D2, D3 of tappa E2: «Esporta questo account» off skips every copy). Otherwise the state + /// and note the item ends with. + /// + private async Task SourceAsync(RunContext x, ExportItem item, CancellationToken ct) { var storage = _env.Storage; - var exports = storage.Exports; - var none = CancellationToken.None; - var destination = x.Destination; - var root = destination.RootPath; - - // a. No longer in the library. if (item.AccountId is not { } accountId || await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is not { } account) { - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.AccountRemoved, LastError = null }, 0, null).ConfigureAwait(false); + return new SourceCheck(null, ExportItemState.Skipped, ExportText.Notes.AccountRemoved, 0); } var media = item.MediaId is { } mediaId ? await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) : null; @@ -238,138 +270,560 @@ public sealed class ExportCopier(ExportEnvironment env) : null; if (source is null || media is null || entry is null) { - return await FinishAsync(item with { State = ExportItemState.Missing, Note = ExportText.Notes.SourceMissing, LastError = null }, 0, null).ConfigureAwait(false); + return new SourceCheck(null, ExportItemState.Missing, ExportText.Notes.SourceMissing, 0); } - // The account may have been switched off, or got another folder, or the destination stopped taking this type - // since the job was planned (decisions D2, D3 of tappa E2): «Esporta questo account» off skips every copy. var (title, inHighlight) = await HighlightAsync(entry, ct).ConfigureAwait(false); - if (!x.Effective.TryGetValue(accountId, out var effective) || effective.Destination?.Id != destination.Id + if (!x.Effective.TryGetValue(accountId, out var effective) || effective.Destination?.Id != x.Destination.Id || !effective.Wants(ExportPaths.TypeOf(entry.Kind, media.Kind, inHighlight))) { - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.NotExported, LastError = null }, media.Bytes ?? 0, null).ConfigureAwait(false); + return new SourceCheck(null, ExportItemState.Skipped, ExportText.Notes.NotExported, item.Variant == ExportVariant.Frame ? 0 : media.Bytes ?? 0); + } + + var bytes = media.Bytes ?? _env.FileSystem.FileLength(source) ?? 0; + return new SourceCheck(new LibraryFile(account, entry, media, source, media.Sha256!, bytes, title, inHighlight), ExportItemState.Pending, null, bytes); + } + + private async Task ProcessItemAsync(RunContext x, ExportItem item, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + + var check = await SourceAsync(x, item, ct).ConfigureAwait(false); + if (check.File is not { } library) + { + return await FinishAsync(item with { State = check.State, Note = check.Note, LastError = null }, check.Bytes, null).ConfigureAwait(false); } // b. The file may have changed since the job was planned. - var sha = media.Sha256!; + var sha = library.Sha256; if (!string.Equals(item.SourceSha256, sha, StringComparison.Ordinal)) { item = item with { SourceSha256 = sha }; } - var bytes = media.Bytes ?? _env.FileSystem.FileLength(source) ?? 0; - var identity = new ExportCopyIdentity(destination.Id, accountId, sha, ExportVariant.Whole, ExportFormat.Original, null); - var file = new FileContext(account, entry, media, source, sha, bytes, identity, title, inHighlight); + // The form asked (D2): the effective one is known once the file is prepared; until then the plan's prediction. + var target = item.Variant == ExportVariant.Whole ? ExportFormat.Original : item.Format; + var predicted = x.Exact ? (item.Variant, item.Format) : ExportConversions.PredictedIdentity(library.Media.RelativePath!, library.Media.Kind, target); + var file = new FileContext(library, new ExportCopyIdentity(destination.Id, library.Account.Id, sha, predicted.Item1, predicted.Item2, null)); // c. Already copied, removed, superseded, copied for another account, or failed before. - var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false); - ExportCopy? failed = null; - if (current is { State: ExportCopyState.Copied }) + var done = x.Exact + ? await ExactLookupAsync(x, item, file, ct).ConfigureAwait(false) + : await AnyFormLookupAsync(x, item, file, predicted, ct).ConfigureAwait(false); + if (done is not null) { - if (current.RelativePath is { } copied && Exists(root, copied)) - { - return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = copied, Note = null, LastError = null }, bytes, copied).ConfigureAwait(false); - } - - // The file is not there: «Tolto», unless the whole destination went away meanwhile. A root that was away - // for a moment and answers the probe again is asked once more for the file before it is called «Tolto». - if (!Directory.Exists(root)) - { - if (await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone) - { - return ItemResult.Paused(gone); - } - - if (current.RelativePath is { } back && Exists(root, back)) - { - return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = back, Note = null, LastError = null }, bytes, back).ConfigureAwait(false); - } - } - - await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); - if (!x.CopyAgain) - { - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, bytes, current.RelativePath).ConfigureAwait(false); - } - } - else if (current is { State: ExportCopyState.Failed }) - { - failed = current; - } - else if (!x.CopyAgain) - { - var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false); - if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded }) - { - var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded; - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, bytes, latest.RelativePath).ConfigureAwait(false); - } - - if (await exports.FindReplacedCopyAsync(destination.Id, accountId, sha, ct).ConfigureAwait(false) is { } replaced) - { - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, bytes, replaced.RelativePath).ConfigureAwait(false); - } + return done; } if (x.OneOnly - && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, accountId, ct).ConfigureAwait(false) is { RelativePath: { } elsewherePath } elsewhere - && await x.DestinationAsync(storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where + && await exports.FindCopiedElsewhereAsync(sha, library.Account.Id, ct).ConfigureAwait(false) is { RelativePath: { } elsewherePath } elsewhere + && await x.DestinationAsync(_env.Storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where && Exists(where.RootPath, elsewherePath)) { return await FinishAsync( item with { State = ExportItemState.AlreadyCopied, Note = ExportText.Notes.CopiedForAnotherAccount, CopyId = elsewhere.Id, LastError = null }, - bytes, + library.Bytes, null).ConfigureAwait(false); } - return await WriteAsync(x, item, file, failed, ct).ConfigureAwait(false); + // d. The conversion, before the space check (D17): its length is what the destination gets. + MediaConversionResult? conversion = null; + Output output; + if (target == ExportFormat.Original) + { + output = Output.Whole(library, []); + } + else + { + try + { + conversion = await ExportConversion.PrepareAsync(_env, library.Source, library.Media, target, sha, ct).ConfigureAwait(false); + } + catch (ContentChangedException ex) + { + return await FailUnpreparedAsync(item, file, ex.Message, ExportText.Notes.SourceChanged).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return await FailUnpreparedAsync(item, file, ExportText.ErrorText(ex), null).ConfigureAwait(false); + } + + output = conversion.Variant == ExportVariant.Whole + ? Output.Whole(library, conversion.Notes) + : new Output(conversion.Variant, conversion.Format, null, conversion.Extension, null, conversion.Length, conversion.Sha256, conversion.Produce, conversion.Notes); + } + + using (conversion) + { + var effective = file.Identity with { Variant = output.Variant, Format = output.Format }; + file = file with { Identity = effective }; + ExportCopy? failed = null; + var current = await exports.FindCurrentCopyAsync(effective, ct).ConfigureAwait(false); + if (current is { State: ExportCopyState.Copied }) + { + // Another form was asked and the bytes gave this one (an «Exact» of a form that is now copied as it is). + var (present, gone) = await PresentCopyAsync(x, [current], ct).ConfigureAwait(false); + if (gone is not null) + { + return ItemResult.Paused(gone); + } + + if (present is not null) + { + await exports.ClearFailedAsync(destination.Id, library.Account.Id, sha, effective, none).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = null, LastError = null }, library.Bytes, present.RelativePath).ConfigureAwait(false); + } + + await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); + if (!x.CopyAgain) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, library.Bytes, current.RelativePath).ConfigureAwait(false); + } + } + else if (current is { State: ExportCopyState.Failed }) + { + failed = current; + } + + var result = await WriteAsync(x, item, file, output, failed, ct).ConfigureAwait(false); + if (result.State is ExportItemState.Copied or ExportItemState.Adopted or ExportItemState.AlreadyCopied && result.Pause is null) + { + // A copy of the file is there now: the «Non riuscito» rows of its other forms have no file and no use. + await exports.ClearFailedAsync(destination.Id, library.Account.Id, sha, effective, none).ConfigureAwait(false); + } + + return result; + } } - /// d. and e.: the path, the limits of the disk, adoption, the safe write and its record. - private async Task WriteAsync(RunContext x, ExportItem item, FileContext file, ExportCopy? failed, CancellationToken ct) + /// + /// «Già copiato» in any form but a frame (D3 of tappa E3, the rule of the plan and of the «Copie» filter): a Copied + /// copy whose file is there ends the item; copies whose file is gone become «Tolto» (after the root answered); a + /// «Non riuscito» copy is tried again; otherwise the newest copy «Tolto» or «Superato», or a copy superseded by this + /// file, skips it unless «Copia di nuovo» was asked. Null: the file is to be written. + /// + private async Task AnyFormLookupAsync(RunContext x, ExportItem item, FileContext file, (ExportVariant Variant, ExportFormat Format) predicted, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + var library = file.Library; + var current = await exports.ListCurrentCopiesAnyFormAsync(destination.Id, library.Account.Id, library.Sha256, ct).ConfigureAwait(false); + var copied = current.Where(c => c.State == ExportCopyState.Copied).ToList(); + if (copied.Count > 0) + { + var (present, gone) = await PresentCopyAsync(x, copied, ct).ConfigureAwait(false); + if (gone is not null) + { + return ItemResult.Paused(gone); + } + + if (present is not null) + { + var note = present.Variant == predicted.Variant && present.Format == predicted.Format ? null : ExportText.Notes.CopiedInAnotherFormat; + if (present.Identity is { } kept) + { + await exports.ClearFailedAsync(destination.Id, library.Account.Id, library.Sha256, kept, none).ConfigureAwait(false); + } + + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = note, LastError = null }, library.Bytes, present.RelativePath).ConfigureAwait(false); + } + + foreach (var copy in copied) + { + await exports.UpdateCopyAsync(copy with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); + } + + return x.CopyAgain + ? null + : await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = copied[0].Id, LastError = null }, library.Bytes, copied[0].RelativePath).ConfigureAwait(false); + } + + if (current.Count > 0 || x.CopyAgain) + { + return null; // a «Non riuscito» copy is tried again; «Copia di nuovo» writes the current form + } + + var latest = await exports.FindLatestCopyAnyFormAsync(destination.Id, library.Account.Id, library.Sha256, ct).ConfigureAwait(false); + if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded }) + { + var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded; + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, library.Bytes, latest.RelativePath).ConfigureAwait(false); + } + + if (await exports.FindReplacedCopyAsync(destination.Id, library.Account.Id, library.Sha256, ct).ConfigureAwait(false) is { } replaced) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, library.Bytes, replaced.RelativePath).ConfigureAwait(false); + } + + return null; + } + + /// «Copia di nuovo» of one copy row (D11 of tappa E3): the rules of tappa E2 on its exact identity only. + private async Task ExactLookupAsync(RunContext x, ExportItem item, FileContext file, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var library = file.Library; + var current = await exports.FindCurrentCopyAsync(file.Identity, ct).ConfigureAwait(false); + if (current is { State: ExportCopyState.Copied }) + { + var (present, gone) = await PresentCopyAsync(x, [current], ct).ConfigureAwait(false); + if (gone is not null) + { + return ItemResult.Paused(gone); + } + + if (present is not null) + { + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = null, LastError = null }, library.Bytes, present.RelativePath).ConfigureAwait(false); + } + + await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); + return x.CopyAgain + ? null + : await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, library.Bytes, current.RelativePath).ConfigureAwait(false); + } + + if (current is not null || x.CopyAgain) + { + return null; + } + + var latest = await exports.FindLatestCopyAsync(file.Identity, ct).ConfigureAwait(false); + if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded }) + { + var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded; + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, library.Bytes, latest.RelativePath).ConfigureAwait(false); + } + + if (await exports.FindReplacedCopyAsync(file.Identity.DestinationId, library.Account.Id, library.Sha256, ct).ConfigureAwait(false) is { } replaced) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, library.Bytes, replaced.RelativePath).ConfigureAwait(false); + } + + return null; + } + + /// + /// The first of whose file is in the destination. When none is, and the root itself is + /// away, the destination is probed: a root that answers again is asked once more for the files (a file is «Tolto» + /// only when the destination is there); one that does not answer gives the reason of the pause. + /// + private async Task<(ExportCopy? Present, string? Pause)> PresentCopyAsync(RunContext x, IReadOnlyList copies, CancellationToken ct) + { + var root = x.Destination.RootPath; + foreach (var copy in copies) + { + if (copy.RelativePath is { } path && Exists(root, path)) + { + return (copy, null); + } + } + + if (Directory.Exists(root)) + { + return (null, null); + } + + if (await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone) + { + return (null, gone); + } + + return (copies.FirstOrDefault(c => c.RelativePath is { } back && Exists(root, back)), null); + } + + /// The file could not be prepared: the item fails, recorded under the form the plan expected. + private async Task FailUnpreparedAsync(ExportItem item, FileContext file, string error, string? note) + { + var current = await _env.Storage.Exports.FindCurrentCopyAsync(file.Identity, CancellationToken.None).ConfigureAwait(false); + return current is { State: ExportCopyState.Copied } + ? await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error }, file.Library.Bytes, item.RelativePath).ConfigureAwait(false) + : await FailAsync(item, file, current, error, note).ConfigureAwait(false); + } + + /// + /// The frames of one video in one format (D12 of tappa E3): the video is opened once, each frame's exact instant is + /// found, a frame already copied at that instant is «Già copiato» (one copy per sample in the batch), the others are + /// decoded in decoding order and written one at a time. A pause leaves the rest of the batch pending. Returns the + /// reason of a pause, or null. + /// + private async Task ProcessFrameBatchAsync(RunContext x, List batch, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + if (await BeforeItemAsync(x, ct).ConfigureAwait(false) is { } problem) + { + return problem; + } + + async Task EndAllAsync(IEnumerable items, ExportItemState state, string? note, string? error) + { + foreach (var item in items) + { + Account(x, await FinishAsync(item with { State = state, Note = note, LastError = error }, 0, null).ConfigureAwait(false)); + } + } + + var check = await SourceAsync(x, batch[0], ct).ConfigureAwait(false); + if (check.File is not { } library) + { + await EndAllAsync(batch, check.State, check.Note, null).ConfigureAwait(false); + return null; + } + + var sha = library.Sha256; + batch = batch.Select(i => string.Equals(i.SourceSha256, sha, StringComparison.Ordinal) ? i : i with { SourceSha256 = sha }).ToList(); + var format = batch[0].Format; + var (mode, count) = x.Frames ?? (FrameMode.At, 1); + var firstId = mode == FrameMode.Count + ? await exports.FirstItemIdAsync(x.Run.Id, library.Media.Id, ExportVariant.Frame, format, ct).ConfigureAwait(false) ?? batch[0].Id + : 0; + + Stream stream; + try + { + // The frames are of the file recorded: hashed once before they are taken (WP1.6b). + if (!string.Equals(await _env.FileSystem.ComputeSha256Async(library.Source, ct).ConfigureAwait(false), sha, StringComparison.Ordinal)) + { + await EndAllAsync(batch, ExportItemState.Failed, ExportText.Notes.SourceChanged, SourceChangedText).ConfigureAwait(false); + return null; + } + + stream = _env.FileSystem.OpenRandomAccess(library.Source); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + await EndAllAsync(batch, ExportItemState.Failed, null, ExportText.ErrorText(ex)).ConfigureAwait(false); + return null; + } + + await using (stream.ConfigureAwait(false)) + { + var (reader, info) = await Task.Run( + () => + { + var opened = VideoFrameReader.Open(stream, out var found); + return (opened, found); + }, + ct).ConfigureAwait(false); + using (reader) + { + var targets = info.Available ? reader.Locate([.. batch.Select(i => i.FrameAt ?? TimeSpan.Zero)]) : []; + if (targets.Count != batch.Count) + { + await EndAllAsync(batch, ExportItemState.Skipped, ExportText.Notes.FrameNotAvailable, null).ConfigureAwait(false); + return null; + } + + // The exact identity of each frame; frames on one sample follow the first of them (one copy). + var plans = new FramePlan?[batch.Count]; + var leaderOf = new Dictionary(); + var followers = new Dictionary>(); + var toWrite = new List(); + for (var k = 0; k < batch.Count; k++) + { + var target = targets[k]; + if (leaderOf.TryGetValue(target.Sample, out var leader)) + { + followers[leader].Add(k); + continue; + } + + leaderOf[target.Sample] = k; + followers[k] = []; + var at = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual)); + var identity = new ExportCopyIdentity(destination.Id, library.Account.Id, sha, ExportVariant.Frame, format, at); + var index = mode == FrameMode.Count ? (int)Math.Clamp(batch[k].Id - firstId, 0, int.MaxValue) : k; + var plan = new FramePlan(identity, ExportFrames.Suffix(mode, target.Actual, index, count), null); + var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false); + if (current is { State: ExportCopyState.Copied }) + { + var (present, gone) = await PresentCopyAsync(x, [current], ct).ConfigureAwait(false); + if (gone is not null) + { + return gone; // nothing of the batch was finished yet + } + + if (present is not null) + { + plans[k] = plan with { Present = present }; + continue; + } + + // A frame asked again is written again (D14): its old row says «Tolto». + await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); + } + else if (current is { State: ExportCopyState.Failed }) + { + plan = plan with { Failed = current }; + } + + plans[k] = plan; + toWrite.Add(k); + } + + async Task EndFollowersAsync(int leader, ExportItem done) + { + foreach (var k in followers[leader]) + { + var follower = done.State is ExportItemState.Copied or ExportItemState.Adopted or ExportItemState.AlreadyCopied && done.CopyId is not null + ? batch[k] with { State = ExportItemState.AlreadyCopied, CopyId = done.CopyId, RelativePath = done.RelativePath, Note = null, LastError = null } + : batch[k] with { State = done.State, Note = done.Note, LastError = done.LastError }; + Account(x, await FinishAsync(follower, 0, follower.RelativePath).ConfigureAwait(false)); + } + } + + for (var k = 0; k < batch.Count; k++) + { + if (plans[k]?.Present is { } present) + { + var done = await FinishAsync(batch[k] with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = null, LastError = null }, 0, present.RelativePath).ConfigureAwait(false); + Account(x, done); + await EndFollowersAsync(k, done.Item!).ConfigureAwait(false); + } + } + + var written = new HashSet(); + var fresh = true; + using (var frames = reader.Decode([.. toWrite.Select(k => targets[k])], ct).GetEnumerator()) + { + while (await Task.Run(frames.MoveNext, ct).ConfigureAwait(false)) + { + using var frame = frames.Current; + var k = frame.Index; + if (!fresh && await BeforeItemAsync(x, ct).ConfigureAwait(false) is { } paused) + { + return paused; + } + + fresh = false; + written.Add(k); + var result = await WriteFrameAsync(x, batch[k], library, plans[k]!, frame, ct).ConfigureAwait(false); + if (result.Pause is { } pause) + { + return pause; + } + + Account(x, result); + await EndFollowersAsync(k, result.Item!).ConfigureAwait(false); + } + } + + // A sample that gave no picture (a damaged stream): no copy row. + foreach (var k in toWrite.Where(k => !written.Contains(k))) + { + var done = await FinishAsync(batch[k] with { State = ExportItemState.Skipped, Note = ExportText.Notes.FrameNotAvailable, LastError = null }, 0, null).ConfigureAwait(false); + Account(x, done); + await EndFollowersAsync(k, done.Item!).ConfigureAwait(false); + } + } + } + + return null; + } + + /// One frame: encoded without metadata (D12 of tappa E3) under the conversion throttle, then written as any copy. + private async Task WriteFrameAsync(RunContext x, ExportItem item, LibraryFile library, FramePlan plan, VideoFrame frame, CancellationToken ct) + { + var format = plan.Identity.Format; + var file = new FileContext(library with { Bytes = 0 }, plan.Identity); + byte[] data; + try + { + var image = MediaConverter.ImageFormatOf(format)!.Value; + data = await _env.Throttle.RunAsync(_ => ImageConverter.Encode(frame.Image, image, null), ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is ImageDecodeException or ArgumentException) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.FrameNotAvailable, LastError = null }, 0, null).ConfigureAwait(false); + } + + var output = new Output( + ExportVariant.Frame, + format, + plan.Identity.FrameAt, + MediaConverter.ExtensionOf(format), + plan.Suffix, + data.Length, + Convert.ToHexStringLower(SHA256.HashData(data)), + (stream, token) => stream.WriteAsync(data, token).AsTask(), + []); + return await WriteAsync(x, item, file, output, plan.Failed, ct).ConfigureAwait(false); + } + + /// + /// e.: the path, the limits of the disk, adoption, the safe write and its record, for any output: the library file + /// byte for byte, a converted file, a frame. + /// + private async Task WriteAsync(RunContext x, ExportItem item, FileContext file, Output output, ExportCopy? failed, CancellationToken ct) { var exports = _env.Storage.Exports; var none = CancellationToken.None; var destination = x.Destination; var root = destination.RootPath; + var library = file.Library; string planned; try { + var name = output.Extension is null && output.Suffix is null ? null : new ExportNameOptions(output.Extension, output.Suffix); planned = ExportPaths.RelativePathFor( destination, - ExportPaths.Segments(destination, x.Naming!, file.Account, file.Entry, file.Media, file.HighlightTitle, file.InHighlight, _env.Clock.LocalZone), - MaxPath); + ExportPaths.Segments(destination, x.Naming!, library.Account, library.Entry, library.Media, library.HighlightTitle, library.InHighlight, _env.Clock.LocalZone, name), + MaxPath, + output.Suffix); } catch (PathTooLongException ex) { return await FailAsync(item, file, failed, ex.Message, null).ConfigureAwait(false); } - if (_env.Disk.MaxFileBytes(root) is { } max && file.Bytes > max) + if (_env.Disk.MaxFileBytes(root) is { } max && output.Length > max) { - return await FailAsync(item, file, failed, ExportText.TooLarge(file.Bytes), ExportText.Notes.TooLargeForFileSystem).ConfigureAwait(false); + return await FailAsync(item, file, failed, ExportText.TooLarge(output.Length), ExportText.Notes.TooLargeForFileSystem).ConfigureAwait(false); } - if (_env.Disk.FreeBytes(root) is { } free && free < file.Bytes + ExportSpace.Margin) + if (_env.Disk.FreeBytes(root) is { } free && free < output.Length + ExportSpace.Margin) { - return ItemResult.Paused(ExportText.NoSpace(destination, free, Path.GetFileName(planned), file.Bytes)); + return ItemResult.Paused(ExportText.NoSpace(destination, free, Path.GetFileName(planned), output.Length)); } - // Adoption by path: the planned file, and after a crash the name it was given («nome (2).jpg», …). - foreach (var candidate in AdoptionCandidates(root, planned, item.RelativePath)) + // Adoption by path (D10 of tappa E3): the planned file, and after a crash the name it was given («nome (2).jpg», + // …), when its length and then its SHA-256 are those of this output. Never by size alone. + string? expected = output.Sha256; + foreach (var candidate in AdoptionCandidates(root, planned, item.RelativePath, output.Suffix)) { var full = LibraryLayout.FullPath(root, candidate); - if (_env.FileSystem.FileLength(full) != file.Bytes - || !string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), file.Sha256, StringComparison.Ordinal)) + if (_env.FileSystem.FileLength(full) != output.Length) + { + continue; + } + + if (expected is null) + { + // A remux: its bytes are known once written, so they are written nowhere first (the length matched). + var (hash, length) = await ExportConversion.HashAsync(output.Produce!, ct).ConfigureAwait(false); + if (length != output.Length) + { + break; + } + + expected = hash; + } + + if (!string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), expected, StringComparison.Ordinal)) { continue; } var holder = await exports.FindCopyByPathAsync(destination.Id, candidate, ct).ConfigureAwait(false); - if (holder is null || (holder.AccountId is null && string.Equals(holder.SourceSha256, file.Sha256, StringComparison.Ordinal))) + if (holder is null || (holder.AccountId is null && SameForm(holder, file, expected))) { - return await RecordAsync(item, file, failed, holder, candidate, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false); + return await RecordAsync(item, file, failed, holder, candidate, output.Length, expected, ExportCopyOrigin.Adopted, Notes(output, null)).ConfigureAwait(false); } if (holder.Identity == file.Identity) @@ -378,10 +832,10 @@ public sealed class ExportCopier(ExportEnvironment env) { // Our own bytes, recorded as superseded (the file came back to the library without the change that // would have revived the row): the copy is copied, not superseded, and must not stay stuck. - return await ReviveAsync(item, file, failed, holder, candidate).ConfigureAwait(false); + return await ReviveAsync(item, file, failed, holder, candidate, output, expected).ConfigureAwait(false); } - return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, file.Bytes, candidate).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, library.Bytes, candidate).ConfigureAwait(false); } // The same bytes, recorded for another copy: not ours to take. @@ -390,7 +844,7 @@ public sealed class ExportCopier(ExportEnvironment env) // The name the record can take: free on the disk and in the database. A path recorded for another copy whose // file is gone is free again («Tolto»); one whose file is there under another letter case (a case-sensitive // disk) is not, and the next numbered name is tried. - var chosen = await ChooseNameAsync(destination, planned, ct).ConfigureAwait(false); + var chosen = await ChooseNameAsync(destination, planned, output.Suffix, ct).ConfigureAwait(false); // The intent, in its own transaction, before the .part exists (WP1.8 cleans only the folders of items). item = item with { RelativePath = planned }; @@ -400,21 +854,50 @@ public sealed class ExportCopier(ExportEnvironment env) try { var directory = planned.Contains('/', StringComparison.Ordinal) ? planned[..planned.LastIndexOf('/')] : string.Empty; - await using var content = _env.FileSystem.OpenRead(file.Source); - saved = (await new SafeFileWriter(MaxPath).SaveAsync( - content, - root, - directory, - (digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal) - ? ValueTask.FromResult(chosen) - : throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."), - new SafeWriteOptions - { - RequireExistingRoot = true, - VerifyFromDisk = true, - LastWriteTime = x.SetFileTime ? file.Entry.PublishedAt : null, - }, - ct).ConfigureAwait(false))!; + var options = new SafeWriteOptions + { + RequireExistingRoot = true, + VerifyFromDisk = true, + LastWriteTime = x.SetFileTime ? library.Entry.PublishedAt : null, + KeepSuffix = output.Suffix, + }; + var writer = new SafeFileWriter(MaxPath); + if (output.Produce is null) + { + await using var content = _env.FileSystem.OpenRead(library.Source); + saved = (await writer.SaveAsync( + content, + root, + directory, + (digest, _) => string.Equals(digest.Sha256, library.Sha256, StringComparison.Ordinal) + ? ValueTask.FromResult(chosen) + : throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."), + options, + ct).ConfigureAwait(false))!; + } + else + { + saved = (await writer.SaveAsync( + output.Produce, + root, + directory, + async (digest, token) => + { + if (output.Sha256 is { } known) + { + return string.Equals(digest.Sha256, known, StringComparison.Ordinal) + ? chosen + : throw new ContentChangedException("Il file scritto non corrisponde alla conversione."); + } + + // A remux was read from the library while written: the library file must still be the one recorded. + return string.Equals(await _env.FileSystem.ComputeSha256Async(library.Source, token).ConfigureAwait(false), library.Sha256, StringComparison.Ordinal) + ? chosen + : throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."); + }, + options, + ct).ConfigureAwait(false))!; + } } catch (ContentChangedException ex) { @@ -425,7 +908,7 @@ public sealed class ExportCopier(ExportEnvironment env) if (IsDiskFull(ex)) { return ItemResult.Paused(_env.Disk.FreeBytes(root) is { } left - ? ExportText.NoSpace(destination, left, Path.GetFileName(planned), file.Bytes) + ? ExportText.NoSpace(destination, left, Path.GetFileName(planned), output.Length) : ExportText.DiskFull(destination)); } @@ -442,21 +925,32 @@ public sealed class ExportCopier(ExportEnvironment env) // The writer moved the file onto a name where no file was: a row still holding that path is stale (decision of // 2026-11-27), also when the name is the one chosen, since a row could appear meanwhile. await ReleaseStalePathAsync(destination, saved.RelativePath, justWritten: true, ct).ConfigureAwait(false); - return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false); + return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, saved.Sha256, ExportCopyOrigin.Written, Notes(output, taken)).ConfigureAwait(false); } + /// An orphan row is adopted only when it records this very copy: same bytes, variant, format and instant (D10). + private static bool SameForm(ExportCopy holder, FileContext file, string copySha256) => + string.Equals(holder.SourceSha256, file.Library.Sha256, StringComparison.Ordinal) + && string.Equals(holder.CopySha256 ?? holder.SourceSha256, copySha256, StringComparison.Ordinal) + && holder.Variant == file.Identity.Variant + && holder.Format == file.Identity.Format + && holder.FrameAt == file.Identity.FrameAt; + + /// The note codes of an item (D19 of tappa E3): those of its output, then «nome occupato». + private static string? Notes(Output output, string? taken) => ExportText.JoinNotes([.. output.Notes, taken]); + /// /// The first of the planned path and its numbered names (numbered as the writer numbers them) that is free on the /// disk and free, or stale, in the database; the planned path when none is found (the writer then decides). /// - private async Task ChooseNameAsync(ExportDestination destination, string planned, CancellationToken ct) + private async Task ChooseNameAsync(ExportDestination destination, string planned, string? keepSuffix, CancellationToken ct) { for (var attempt = 1; attempt <= MaxSiblings; attempt++) { string name; try { - name = ExportPaths.NumberedName(destination.RootPath, planned, attempt, MaxPath); + name = ExportPaths.NumberedName(destination.RootPath, planned, attempt, MaxPath, keepSuffix); } catch (PathTooLongException) { @@ -508,23 +1002,23 @@ public sealed class ExportCopier(ExportEnvironment env) /// A Superseded row of this very identity whose bytes are at its path: it becomes the Copied row again. When the /// identity has a current «Non riuscito» row, that one becomes the Copied row and the old one stays as history. /// - private async Task ReviveAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy holder, string path) + private async Task ReviveAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy holder, string path, Output output, string copySha256) { var exports = _env.Storage.Exports; var none = CancellationToken.None; var now = _env.Clock.Now; if (failed is null && await exports.FindCurrentCopyAsync(file.Identity, none).ConfigureAwait(false) is null) { - await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Copied, SupersededBySha256 = null, MediaId = file.Media.Id, StateChangedAt = now }, none).ConfigureAwait(false); - return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = path, Note = null, LastError = null }, file.Bytes, path).ConfigureAwait(false); + await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Copied, SupersededBySha256 = null, MediaId = file.Library.Media.Id, StateChangedAt = now }, none).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = path, Note = null, LastError = null }, file.Library.Bytes, path).ConfigureAwait(false); } await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Removed, StateChangedAt = now }, none).ConfigureAwait(false); - return await RecordAsync(item, file, failed, null, path, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false); + return await RecordAsync(item, file, failed, null, path, output.Length, copySha256, ExportCopyOrigin.Adopted, Notes(output, null)).ConfigureAwait(false); } /// Files to look at for adoption: the planned path, then the one recorded before a crash and its numbered names. - private IEnumerable AdoptionCandidates(string root, string planned, string? previous) + private IEnumerable AdoptionCandidates(string root, string planned, string? previous, string? keepSuffix) { var seen = new HashSet(StringComparer.OrdinalIgnoreCase); if (seen.Add(planned) && Exists(root, planned)) @@ -542,7 +1036,7 @@ public sealed class ExportCopier(ExportEnvironment env) string name; try { - name = ExportPaths.NumberedName(root, previous, attempt, MaxPath); + name = ExportPaths.NumberedName(root, previous, attempt, MaxPath, keepSuffix); } catch (PathTooLongException) { @@ -561,11 +1055,12 @@ public sealed class ExportCopier(ExportEnvironment env) } } - private async Task RecordAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy? orphan, string path, long bytes, ExportCopyOrigin origin, string? note) + private async Task RecordAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy? orphan, string path, long bytes, string copySha256, ExportCopyOrigin origin, string? note) { var exports = _env.Storage.Exports; var none = CancellationToken.None; var now = _env.Clock.Now; + var identity = file.Identity; ExportCopy copy; try { @@ -577,34 +1072,35 @@ public sealed class ExportCopier(ExportEnvironment env) Origin = origin, RelativePath = path, Bytes = bytes, - CopySha256 = file.Sha256, + CopySha256 = copySha256, CopiedAt = now, StateChangedAt = now, LastError = null, - MediaId = file.Media.Id, + MediaId = file.Library.Media.Id, }; await exports.UpdateCopyAsync(copy, none).ConfigureAwait(false); } else if (orphan is not null) { - copy = await exports.RelinkOrphanCopyAsync(orphan.Id, file.Identity.AccountId, file.Media.Id, now, none).ConfigureAwait(false); + copy = await exports.RelinkOrphanCopyAsync(orphan.Id, identity.AccountId, file.Library.Media.Id, now, none).ConfigureAwait(false); } else { copy = await exports.AddCopyAsync( new ExportCopy { - DestinationId = file.Identity.DestinationId, - AccountId = file.Identity.AccountId, - MediaId = file.Media.Id, - SourceSha256 = file.Sha256, - Variant = ExportVariant.Whole, - Format = ExportFormat.Original, + DestinationId = identity.DestinationId, + AccountId = identity.AccountId, + MediaId = file.Library.Media.Id, + SourceSha256 = identity.SourceSha256, + Variant = identity.Variant, + Format = identity.Format, + FrameAt = identity.FrameAt, State = ExportCopyState.Copied, Origin = origin, RelativePath = path, Bytes = bytes, - CopySha256 = file.Sha256, + CopySha256 = copySha256, CopiedAt = now, }, none).ConfigureAwait(false); @@ -613,11 +1109,11 @@ public sealed class ExportCopier(ExportEnvironment env) catch (DuplicateRecordException) { // Taken meanwhile by another record. The file written stays where it is: nothing is ever removed. - return await FinishAsync(item with { State = ExportItemState.Failed, Note = ExportText.Notes.PathTaken, LastError = ExportText.Note(ExportText.Notes.PathTaken) }, file.Bytes, path).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.Failed, Note = ExportText.Notes.PathTaken, LastError = ExportText.Note(ExportText.Notes.PathTaken) }, file.Library.Bytes, path, bytes).ConfigureAwait(false); } var state = origin == ExportCopyOrigin.Adopted ? ExportItemState.Adopted : ExportItemState.Copied; - return await FinishAsync(item with { State = state, CopyId = copy.Id, RelativePath = path, Note = note, LastError = null }, file.Bytes, path).ConfigureAwait(false); + return await FinishAsync(item with { State = state, CopyId = copy.Id, RelativePath = path, Note = note, LastError = null }, file.Library.Bytes, path, bytes).ConfigureAwait(false); } /// f.: the item fails, and its copy is «Non riuscito» (the viewer shows it), the job goes on. @@ -625,24 +1121,26 @@ public sealed class ExportCopier(ExportEnvironment env) { var exports = _env.Storage.Exports; var none = CancellationToken.None; + var identity = file.Identity; long? copyId = failed?.Id; try { if (failed is not null) { - await exports.UpdateCopyAsync(failed with { LastError = error, StateChangedAt = _env.Clock.Now, MediaId = file.Media.Id }, none).ConfigureAwait(false); + await exports.UpdateCopyAsync(failed with { LastError = error, StateChangedAt = _env.Clock.Now, MediaId = file.Library.Media.Id }, none).ConfigureAwait(false); } else { copyId = (await exports.AddCopyAsync( new ExportCopy { - DestinationId = file.Identity.DestinationId, - AccountId = file.Identity.AccountId, - MediaId = file.Media.Id, - SourceSha256 = file.Sha256, - Variant = ExportVariant.Whole, - Format = ExportFormat.Original, + DestinationId = identity.DestinationId, + AccountId = identity.AccountId, + MediaId = file.Library.Media.Id, + SourceSha256 = identity.SourceSha256, + Variant = identity.Variant, + Format = identity.Format, + FrameAt = identity.FrameAt, State = ExportCopyState.Failed, CopiedAt = _env.Clock.Now, LastError = error, @@ -655,13 +1153,13 @@ public sealed class ExportCopier(ExportEnvironment env) // The identity got a current row meanwhile: that one tells the state. } - return await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error, CopyId = copyId }, file.Bytes, item.RelativePath).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error, CopyId = copyId }, file.Library.Bytes, item.RelativePath).ConfigureAwait(false); } - private async Task FinishAsync(ExportItem item, long bytes, string? path) + private async Task FinishAsync(ExportItem item, long bytes, string? path, long? written = null) { await _env.Storage.Exports.UpdateItemsAsync([item], CancellationToken.None).ConfigureAwait(false); - return new ItemResult(item.State, bytes, path, null); + return new ItemResult(item.State, bytes, path, null, written) { Item = item }; } private async Task<(string? Title, bool InHighlight)> HighlightAsync(Entry entry, CancellationToken ct) @@ -693,14 +1191,87 @@ public sealed class ExportCopier(ExportEnvironment env) && (io.HResult is unchecked((int)0x80070070) or unchecked((int)0x80070027) or 28 || io.Message.Contains("No space left on device", StringComparison.OrdinalIgnoreCase)); - private sealed record FileContext(Account Account, Entry Entry, Media Media, string Source, string Sha256, long Bytes, ExportCopyIdentity Identity, string? HighlightTitle, bool InHighlight); + /// The error of a library file that changed before its frames were taken. + private const string SourceChangedText = "Il file della libreria non corrisponde a quello registrato."; + + /// A library file the job may copy now. + private sealed record LibraryFile(Account Account, Entry Entry, Media Media, string Source, string Sha256, long Bytes, string? HighlightTitle, bool InHighlight); + + /// The library file of an item, or why the item ends ( null). + private sealed record SourceCheck(LibraryFile? File, ExportItemState State, string? Note, long Bytes); + + /// A library file with the identity of the copy it gives (the prediction until the output is known). + private sealed record FileContext(LibraryFile Library, ExportCopyIdentity Identity); + + /// A frame to take: its exact identity, its suffix, a copy already there, a «Non riuscito» row to reuse. + private sealed record FramePlan(ExportCopyIdentity Identity, string Suffix, ExportCopy? Failed) + { + public ExportCopy? Present { get; init; } + } + + /// + /// What is written: the effective form, the name it changes (extension, frame suffix), its length, its SHA-256 when + /// known before writing, how to write it (null: the library file byte for byte, read and checked as in tappa E2), and + /// its notes. + /// + private sealed record Output( + ExportVariant Variant, + ExportFormat Format, + TimeSpan? FrameAt, + string? Extension, + string? Suffix, + long Length, + string? Sha256, + Func? Produce, + IReadOnlyList Notes) + { + public static Output Whole(LibraryFile library, IReadOnlyList notes) => + new(ExportVariant.Whole, ExportFormat.Original, null, null, null, library.Bytes, library.Sha256, null, notes); + } /// What happened to an item; stops the job with the destination paused. - private sealed record ItemResult(ExportItemState State, long Bytes, string? Path, string? Pause) + /// Library bytes, for the progress. + /// Bytes written to the destination, for the group of the probe; null: . + private sealed record ItemResult(ExportItemState State, long Bytes, string? Path, string? Pause, long? Written = null) { + /// The item as stored. + public ExportItem? Item { get; init; } + public static ItemResult Paused(string message) => new(ExportItemState.Pending, 0, null, message); } + /// The pending items of a job, a page at a time, with a look at the next one (a batch may cross pages). + private sealed class PendingItems(IExportStore store, long runId) + { + private readonly Queue _buffer = new(); + private long _after; + private bool _done; + + public async Task PeekAsync(CancellationToken ct) + { + if (_buffer.Count == 0 && !_done) + { + var page = await store.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = _after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + _done = true; + } + else + { + _after = page[^1].Id; + foreach (var item in page) + { + _buffer.Enqueue(item); + } + } + } + + return _buffer.Count > 0 ? _buffer.Peek() : null; + } + + public ExportItem Take() => _buffer.Dequeue(); + } + private sealed class RunContext(ExportRun run, ExportDestination destination, IProgress? progress) { private readonly Dictionary _destinations = []; @@ -717,6 +1288,12 @@ public sealed class ExportCopier(ExportEnvironment env) public bool CopyAgain { get; set; } + /// The frames request of a frames job (mode, and N of «N in tutto»). + public (FrameMode Mode, int Count)? Frames { get; set; } + + /// «Copia di nuovo» of one copy row: only its exact identity is looked up. + public bool Exact { get; set; } + public IReadOnlyDictionary Effective { get; set; } = new Dictionary(); public int FilesDone { get; set; } @@ -727,6 +1304,11 @@ public sealed class ExportCopier(ExportEnvironment env) public long BytesTotal { get; set; } + /// Files of the current group since its probe. + public int GroupFiles { get; set; } + + public long GroupBytes { get; set; } + public Dictionary ByState { get; set; } = []; public async Task DestinationAsync(IFebeStorage storage, long id, CancellationToken ct) diff --git a/src/Febe.Core/Export/ExportDestinations.cs b/src/Febe.Core/Export/ExportDestinations.cs index 52a8131..bc33dd6 100644 --- a/src/Febe.Core/Export/ExportDestinations.cs +++ b/src/Febe.Core/Export/ExportDestinations.cs @@ -15,6 +15,8 @@ namespace Febe.Core.Export; /// Scheme of profile pictures; null: «Come la libreria». /// «Automatica»: stored only in tappa E2 (tappa E5 acts on it). /// «Solo i nuovi» when «Automatica» is turned on. +/// Format of the copies of photos here; null: «Come le impostazioni generali» (tappa E3, D1). +/// Format of the copies of videos here (Original or Mp4); null: «Come le impostazioni generali». public sealed record DestinationSpec( ExportScope Scope, long? AccountId, @@ -25,7 +27,9 @@ public sealed record DestinationSpec( string? HighlightNamingScheme, string? ProfileNamingScheme, bool Automatic = false, - bool OnlyNew = true); + bool OnlyNew = true, + ExportFormat? PhotoFormat = null, + ExportFormat? VideoFormat = null); /// A saved destination and the warnings of its naming schemes (shown, they do not block). public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList Warnings); @@ -347,6 +351,17 @@ public sealed class ExportDestinations(ExportEnvironment env) throw new ArgumentException("Scegli almeno un tipo di contenuto.", nameof(spec)); } + // A change of format is not a new folder: the copies already made stay «già copiato» (D3 of tappa E3). + if (spec.PhotoFormat is { } photo && !ExportFormats.IsPhotoFormat(photo)) + { + throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(spec)); + } + + if (spec.VideoFormat is { } video && !ExportFormats.IsVideoFormat(video)) + { + throw new ArgumentException("Per i video si sceglie Originale o MP4.", nameof(spec)); + } + var errors = new List(); var warnings = new List(); void Check(string? text, NamingSchemeUse use) @@ -392,6 +407,8 @@ public sealed class ExportDestinations(ExportEnvironment env) NamingScheme = Clean(spec.NamingScheme), HighlightNamingScheme = Clean(spec.HighlightNamingScheme), ProfileNamingScheme = Clean(spec.ProfileNamingScheme), + PhotoFormat = spec.PhotoFormat, + VideoFormat = spec.VideoFormat, Automatic = spec.Automatic, CreatedAt = createdAt, }; diff --git a/src/Febe.Core/Export/ExportEnvironment.cs b/src/Febe.Core/Export/ExportEnvironment.cs index ad90087..91bd374 100644 --- a/src/Febe.Core/Export/ExportEnvironment.cs +++ b/src/Febe.Core/Export/ExportEnvironment.cs @@ -2,6 +2,7 @@ using System.Security.Cryptography; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Library; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Export; @@ -61,6 +62,9 @@ public sealed record ExportEnvironment /// …or this many planned bytes, whichever comes first. public long GroupBytes { get; init; } = 1L << 30; + /// One conversion at a time in the process (tappa E3, D16): shared with the library conversion. + public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared; + /// The checker of destination folders of this environment. public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe); @@ -101,6 +105,12 @@ public interface IExportFileSystem /// Opens a file for reading only. Stream OpenRead(string path); + /// + /// Opens a file for reading at any position (a video to remux or to take frames from, tappa E3). By default the + /// stream of , which can seek. + /// + Stream OpenRandomAccess(string path) => OpenRead(path); + /// SHA-256 (lowercase hex) of a file as it is on disk now. Task ComputeSha256Async(string path, CancellationToken ct); @@ -121,8 +131,13 @@ public sealed class ExportFileSystem : IExportFileSystem public static ExportFileSystem Instance { get; } = new(); + // FileShare.Delete: a long read never blocks «Elimina dalla libreria» on Windows (tappa E3). public Stream OpenRead(string path) => - new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); + new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); + + /// As ContainerReader.OpenRead: shared for reading, writing and deleting, read at random positions. + public Stream OpenRandomAccess(string path) => + new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, BufferSize, FileOptions.RandomAccess); public async Task ComputeSha256Async(string path, CancellationToken ct) { diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs index 428e744..67ca130 100644 --- a/src/Febe.Core/Export/ExportModels.cs +++ b/src/Febe.Core/Export/ExportModels.cs @@ -39,8 +39,27 @@ public enum FrameMode /// A request of frames of videos, in a photo format (Jpg, Png or WebpLossless). public sealed record ExportFramesRequest(FrameMode Mode, TimeSpan? At, TimeSpan? Every, int? Count, ExportFormat Format); +/// +/// The formats of «Copia in…» for this request only (tappa E3, D1): null keeps the destination's (or the general +/// settings'). A photo format or Original for photos; Mp4 or Original for videos. +/// +public sealed record ExportFormatChoice(ExportFormat? Photo, ExportFormat? Video); + +/// «Copia di nuovo» of one copy row (tappa E3, D11): the form of that row, looked up only by its exact identity. +/// The instant of a frame row; null otherwise. +public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt); + /// A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked. -public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual); +/// The formats of this request («Copia in…» → «Cambia»); null: those of the destination. +/// Not null: a frames job («Fotogrammi…» → «Nella cartella delle copie»), videos only. +/// «Copia di nuovo» of one copy row, only with a selection of one file. +public sealed record ExportJobRequest( + ExportSelection Selection, + bool CopyAgain = false, + ExportRunOrigin Origin = ExportRunOrigin.Manual, + ExportFormatChoice? Formats = null, + ExportFramesRequest? Frames = null, + ExportCopyRequest? Exact = null); /// /// What a «Copia in…» would do (database only, decisions D3 and D9 of tappa E2). Each file goes to the effective @@ -71,8 +90,35 @@ public sealed record ExportPlan( bool HasDestination = true) { public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []); + + /// + /// Files predicted to be copied as they are, by kind («3 HEIC copiati come sono»): a prediction from the names + /// («circa»), the copy decides on the bytes (tappa E3). + /// + public IReadOnlyList AsIs { get; init; } = []; + + /// Files predicted to be converted. + public int Converted { get; init; } + + /// «Con perdita»: at least one file predicted converted to JPG, or JPG frames (D7 of tappa E3). + public bool Lossy { get; init; } + + /// Frames job: the due videos. + public int Videos { get; init; } + + /// Frames job: the photos of the selection, skipped («Le 4 foto si saltano»). + public int PhotosSkipped { get; init; } + + /// Frames job: the frames to write (also in ); «circa» for a video of unknown length. + public int Frames { get; init; } + + /// Frames job: videos that would give more than frames (the job is refused). + public int OverCap { get; init; } } +/// Files of a plan copied as they are, of one kind («HEIC», «AVIF», «raw», «GIF», «WebM»). +public sealed record ExportPlanAsIs(string Label, int Files); + /// A destination of a plan. /// The account of an own folder; null for the general folder. /// Files to write there. diff --git a/src/Febe.Core/Export/ExportPlanner.cs b/src/Febe.Core/Export/ExportPlanner.cs index f087ef2..1c7a966 100644 --- a/src/Febe.Core/Export/ExportPlanner.cs +++ b/src/Febe.Core/Export/ExportPlanner.cs @@ -6,8 +6,10 @@ namespace Febe.Core.Export; /// /// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the -/// effective destination of its account; a file already copied there is «già copiato»; «Tolti» and «Superati» are -/// skipped unless «Copia di nuovo» was asked. The only look at a destination is whether it answers, for the dialog. +/// effective destination of its account; a file already copied there, in any form but a frame, is «già copiato» +/// (decision D3 of tappa E3); «Tolti» and «Superati» are skipped unless «Copia di nuovo» was asked. The format of each +/// file is resolved and predicted from its name (D1, «circa»); a frames job plans one frame per instant of each due +/// video. The only look at a destination is whether it answers, for the dialog. /// public sealed class ExportPlanner(ExportEnvironment env) { @@ -16,9 +18,11 @@ public sealed class ExportPlanner(ExportEnvironment env) private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); /// The plan of a request, for the «Copia in…» dialog. + /// The request is not valid (Italian message). public async Task PlanAsync(ExportJobRequest request, CancellationToken ct) { ArgumentNullException.ThrowIfNull(request); + Validate(request); var destinations = new ExportDestinations(_env); var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false); var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); @@ -31,10 +35,86 @@ public sealed class ExportPlanner(ExportEnvironment env) return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false); } + /// The checks of a request (tappa E3, WP1.1), with Italian messages. + /// What is wrong. + public static void Validate(ExportJobRequest request) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(request.Selection, nameof(request)); + if (request.Frames is not null && request.Formats is not null) + { + throw new ArgumentException("I fotogrammi non si chiedono insieme ai formati delle copie.", nameof(request)); + } + + if (request.Exact is { } exact) + { + if (request.Selection is not ExportSelection.Media { MediaIds.Count: 1 }) + { + throw new ArgumentException("«Copia di nuovo» di una copia vale per un file solo.", nameof(request)); + } + + if (request.Frames is not null || request.Formats is not null) + { + throw new ArgumentException("«Copia di nuovo» di una copia rifà la sua forma: niente altri formati né fotogrammi.", nameof(request)); + } + + var valid = exact.Variant switch + { + ExportVariant.Whole => exact.Format == ExportFormat.Original && exact.FrameAt is null, + ExportVariant.Converted => exact.Format != ExportFormat.Original && exact.FrameAt is null, + ExportVariant.Frame => IsFrameFormat(exact.Format) && exact.FrameAt is { } at && at >= TimeSpan.Zero, + _ => false, + }; + if (!valid) + { + throw new ArgumentException("La forma della copia da rifare non è valida.", nameof(request)); + } + } + + if (request.Formats is { } formats) + { + if (formats.Photo is { } photo && !ExportFormats.IsPhotoFormat(photo)) + { + throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(request)); + } + + if (formats.Video is { } video && !ExportFormats.IsVideoFormat(video)) + { + throw new ArgumentException("Per i video si sceglie Originale o MP4.", nameof(request)); + } + } + + if (request.Frames is { } frames) + { + if (!IsFrameFormat(frames.Format)) + { + throw new ArgumentException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.", nameof(request)); + } + + switch (frames.Mode) + { + case FrameMode.At when frames.At is not { } at || at < TimeSpan.Zero: + throw new ArgumentException("Scegli l'istante del fotogramma.", nameof(request)); + case FrameMode.Every when frames.Every is not { } every || every < ExportFrames.MinEvery: + throw new ArgumentException("L'intervallo minimo è 0,1 secondi.", nameof(request)); + case FrameMode.Count when frames.Count is not ({ } count and >= 1 and <= ExportFrames.MaxCount): + throw new ArgumentException("Da 1 a 1.000 fotogrammi.", nameof(request)); + case FrameMode.At or FrameMode.Every or FrameMode.Count: + break; + default: + throw new ArgumentException("Modo dei fotogrammi sconosciuto.", nameof(request)); + } + } + } + + /// JPG, PNG or WEBP senza perdita: the formats of a frame. + internal static bool IsFrameFormat(ExportFormat format) => format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless; + /// - /// Every candidate of the request with what to do with it, in media id order. Within one plan the same file of an - /// account in one destination counts once (a story and its highlight entry, two files with the same bytes); with - /// «Una copia sola» the same file counts once across accounts. + /// Every candidate of the request with what to do with it, in media id order (a frames job: one planned file per + /// instant of each video, in instant order). Within one plan the same file of an account in one destination counts + /// once (a story and its highlight entry, two files with the same bytes); with «Una copia sola» the same file counts + /// once across accounts. /// internal async IAsyncEnumerable EnumerateAsync( ExportJobRequest request, @@ -42,6 +122,16 @@ public sealed class ExportPlanner(ExportEnvironment env) ExportSettings settings, [EnumeratorCancellation] CancellationToken ct) { + if (request.Frames is { } frames) + { + await foreach (var frame in EnumerateFramesAsync(request, frames, effective, ct).ConfigureAwait(false)) + { + yield return frame; + } + + yield break; + } + var exports = _env.Storage.Exports; var oneOnly = settings.SamePost == SamePostCopies.OneOnly; var seen = new HashSet<(long Destination, long Account, string Sha256)>(); @@ -70,9 +160,12 @@ public sealed class ExportPlanner(ExportEnvironment env) } var states = new Dictionary>(); - foreach (var (destination, set) in keys) + if (request.Exact is null) { - states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false); + foreach (var (destination, set) in keys) + { + states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false); + } } foreach (var c in page) @@ -91,25 +184,45 @@ public sealed class ExportPlanner(ExportEnvironment env) var sha = c.Sha256!; var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha); - var state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : (ExportCopyState?)null; + var form = Form(c, request, effective[c.AccountId].Destination!, settings); + ExportCopyState? state; + if (request.Exact is { } exact) + { + // «Copia di nuovo» of one row: only its exact identity counts (D11 of tappa E3). + var identity = new ExportCopyIdentity(destination, c.AccountId, sha, exact.Variant, exact.Format, exact.FrameAt); + if (await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false) is { } current) + { + state = current.State; + } + else + { + var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false); + state = latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded } ? latest.State : null; + } + } + else + { + state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : null; + } + PlannedFile planned; if (state == ExportCopyState.Copied) { - planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied); + planned = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied }; } else if (state is ExportCopyState.Removed or ExportCopyState.Superseded) { planned = request.CopyAgain - ? new PlannedFile(c, destination, PlannedCopy.Write, Again: true) - : new PlannedFile(c, destination, PlannedCopy.RemovedOrSuperseded); + ? form with { DestinationId = destination, Action = PlannedCopy.Write, Again = true } + : form with { DestinationId = destination, Action = PlannedCopy.RemovedOrSuperseded }; } - else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, c.AccountId, ct).ConfigureAwait(false) is not null) + else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, c.AccountId, ct).ConfigureAwait(false) is not null) { - planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied); + planned = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied }; } else { - planned = new PlannedFile(c, destination, PlannedCopy.Write); + planned = form with { DestinationId = destination, Action = PlannedCopy.Write }; } if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key)) @@ -122,6 +235,110 @@ public sealed class ExportPlanner(ExportEnvironment env) } } + /// + /// A frames job (D12, D14 of tappa E3): photos are skipped, videos not due are counted as in «Copia in…», each due + /// video gives one planned frame per instant of the request. A video of unknown length gives one planned file + /// without an instant (): its instants are found when the job is recorded. + /// Frames are not checked for «già copiato» here: the copy looks at each one's exact instant. + /// + private async IAsyncEnumerable EnumerateFramesAsync( + ExportJobRequest request, + ExportFramesRequest frames, + IReadOnlyDictionary effective, + [EnumeratorCancellation] CancellationToken ct) + { + var exports = _env.Storage.Exports; + var seen = new HashSet<(long Destination, long Account, string Sha256, long Ticks, ExportFormat Format)>(); + long after = 0; + while (true) + { + var page = await exports.ListCandidatesAsync(request.Selection, after, PageSize, ct).ConfigureAwait(false); + if (page.Count == 0) + { + yield break; + } + + after = page[^1].MediaId; + foreach (var c in page) + { + if (!IsPresent(c)) + { + yield return new PlannedFile(c, null, PlannedCopy.Missing); + continue; + } + + if (c.MediaKind != MediaKind.Video) + { + yield return new PlannedFile(c, null, PlannedCopy.PhotoSkipped); + continue; + } + + if (Due(c, effective) is not { } destination) + { + yield return new PlannedFile(c, null, PlannedCopy.NotExported); + continue; + } + + var frame = new PlannedFile(c, destination, PlannedCopy.Write) + { + Variant = ExportVariant.Frame, + Format = frames.Format, + Prediction = ExportPrediction.Converted, + FirstOfVideo = true, + }; + if (frames.Mode != FrameMode.At && c.Duration is not { } known) + { + yield return frame with { UnknownDuration = true }; + continue; + } + + var duration = c.Duration ?? TimeSpan.Zero; + if (ExportFrames.FrameCount(duration, frames) > ExportFrames.MaxPerVideo) + { + yield return frame with { Action = PlannedCopy.OverCap }; + continue; + } + + var first = true; + foreach (var at in ExportFrames.Instants(duration, frames)) + { + var planned = frame with { FrameAt = at, FirstOfVideo = first }; + first = false; + if (!seen.Add((destination, c.AccountId, c.Sha256!, at.Ticks, frames.Format))) + { + planned = planned with { Action = PlannedCopy.AlreadyCopied }; + } + + yield return planned; + } + } + } + } + + /// The form a file is asked in (D1, D2): the request's identity, and what its name predicts. + private static PlannedFile Form(ExportCandidate c, ExportJobRequest request, ExportDestination destination, ExportSettings settings) + { + if (request.Exact is { } exact) + { + var prediction = exact.Variant == ExportVariant.Whole ? ExportPrediction.Whole : ExportConversions.Predict(c.RelativePath!, c.MediaKind, exact.Format); + return new PlannedFile(c, null, PlannedCopy.Write) + { + Variant = exact.Variant, + Format = exact.Format, + FrameAt = exact.FrameAt, + Prediction = exact.Variant == ExportVariant.Frame ? ExportPrediction.Converted : prediction, + }; + } + + var target = ExportConversions.Resolve(c.MediaKind, request.Formats, destination, settings); + return new PlannedFile(c, null, PlannedCopy.Write) + { + Variant = ExportConversions.VariantOf(target), + Format = target, + Prediction = ExportConversions.Predict(c.RelativePath!, c.MediaKind, target), + }; + } + /// A file present in the library, with its SHA-256 and path. internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath); @@ -135,7 +352,26 @@ public sealed class ExportPlanner(ExportEnvironment env) /// A candidate with what the plan does with it. /// Where it goes; null when not exported or missing. /// Written although «Tolto» or «Superato», because «Copia di nuovo» was asked. -internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false); +internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false) +{ + /// The variant asked (the request, D2 of tappa E3): Whole, Converted or Frame. + public ExportVariant Variant { get; init; } = ExportVariant.Whole; + + /// The format asked. + public ExportFormat Format { get; init; } = ExportFormat.Original; + + /// The instant asked of a frame. + public TimeSpan? FrameAt { get; init; } + + /// What the name predicts («circa»). + public ExportPrediction Prediction { get; init; } = ExportPrediction.Whole; + + /// Frames job: the first planned file of its video (the videos are counted on it). + public bool FirstOfVideo { get; init; } + + /// Frames job: a video of unknown length, without instants yet («circa» one frame). + public bool UnknownDuration { get; init; } +} internal enum PlannedCopy { @@ -144,12 +380,19 @@ internal enum PlannedCopy RemovedOrSuperseded, NotExported, Missing, + + /// Frames job: a photo of the selection. + PhotoSkipped, + + /// Frames job: a video over frames. + OverCap, } /// Counts of a plan while its files go by. internal sealed class PlanTally { private readonly Dictionary _byDestination = []; + private readonly Dictionary _asIs = new(StringComparer.Ordinal); public int Files { get; private set; } @@ -163,8 +406,25 @@ internal sealed class PlanTally public int Missing { get; private set; } + public int Converted { get; private set; } + + public bool Lossy { get; private set; } + + public int Videos { get; private set; } + + public int PhotosSkipped { get; private set; } + + public int Frames { get; private set; } + + public int OverCap { get; private set; } + public void Add(PlannedFile file) { + if (file.FirstOfVideo && file.Action is not (PlannedCopy.OverCap or PlannedCopy.NotExported or PlannedCopy.Missing)) + { + Videos++; + } + switch (file.Action) { case PlannedCopy.Missing: @@ -173,6 +433,13 @@ internal sealed class PlanTally case PlannedCopy.NotExported: NotExported++; return; + case PlannedCopy.PhotoSkipped: + PhotosSkipped++; + return; + case PlannedCopy.OverCap: + OverCap++; + Videos++; + return; case PlannedCopy.AlreadyCopied: AlreadyCopied++; break; @@ -180,7 +447,8 @@ internal sealed class PlanTally RemovedOrSuperseded++; break; case PlannedCopy.Write: - var bytes = file.Candidate.Bytes ?? 0; + var frame = file.Variant == ExportVariant.Frame; + var bytes = frame ? 0 : file.Candidate.Bytes ?? 0; Files++; Bytes += bytes; if (file.Again) @@ -188,6 +456,21 @@ internal sealed class PlanTally RemovedOrSuperseded++; } + if (frame) + { + Frames++; + Lossy |= file.Format == ExportFormat.Jpg; + } + else if (file.Prediction == ExportPrediction.Converted) + { + Converted++; + Lossy |= file.Format == ExportFormat.Jpg; + } + else if (file.Prediction == ExportPrediction.AsIs && ExportConversions.AsIsLabel(file.Candidate.RelativePath!) is { } label) + { + _asIs[label] = _asIs.GetValueOrDefault(label) + 1; + } + var (f, b) = _byDestination.GetValueOrDefault(file.DestinationId!.Value); _byDestination[file.DestinationId.Value] = (f + 1, b + bytes); return; @@ -230,7 +513,16 @@ internal sealed class PlanTally } var any = rows.Count > 0 || (await env.Storage.Exports.ListDestinationsAsync(false, ct).ConfigureAwait(false)).Count > 0; - return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any); + return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any) + { + AsIs = _asIs.OrderByDescending(p => p.Value).ThenBy(p => p.Key, StringComparer.Ordinal).Select(p => new ExportPlanAsIs(p.Key, p.Value)).ToList(), + Converted = Converted, + Lossy = Lossy, + Videos = Videos, + PhotosSkipped = PhotosSkipped, + Frames = Frames, + OverCap = OverCap, + }; } /// Destinations that get a run: those with files to write, already copied, or «tolti o superati». diff --git a/src/Febe.Core/Export/ExportReports.cs b/src/Febe.Core/Export/ExportReports.cs index c8bc328..9fc17c6 100644 --- a/src/Febe.Core/Export/ExportReports.cs +++ b/src/Febe.Core/Export/ExportReports.cs @@ -12,10 +12,24 @@ public sealed record ExportReport( IReadOnlyDictionary ByState, long BytesCopied, IReadOnlyList Accounts, - IReadOnlyList Problems); + IReadOnlyList Problems) +{ + /// + /// Tappa E3: at most files copied or adopted with a note (copied as they + /// are, what a conversion did not keep, a free name). + /// + public IReadOnlyList Notes { get; init; } = []; +} /// The files of one account in a job («Copiato» counts written and adopted files). -public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed); +public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed) +{ + /// + /// Tappa E3: the files copied as they are, by kind («HEIC», «AVIF», «raw», «animata», «video», «altro»): the exact + /// counts of the job, where the plan's are predictions. + /// + public IReadOnlyDictionary AsIs { get; init; } = new Dictionary(); +} /// A file of the report, with its reason in Italian. public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text); @@ -45,6 +59,8 @@ public sealed class ExportReports(ExportEnvironment env) var accounts = new Dictionary(); var problems = new List(); + var notes = new List(); + var asIs = new Dictionary>(); long bytes = 0; long after = 0; while (true) @@ -68,6 +84,21 @@ public sealed class ExportReports(ExportEnvironment env) { case ExportItemState.Copied or ExportItemState.Adopted: row[0]++; + if (AsIsLabel(item.Note) is { } label) + { + if (!asIs.TryGetValue(key, out var kinds)) + { + asIs[key] = kinds = new Dictionary(StringComparer.Ordinal); + } + + kinds[label] = kinds.GetValueOrDefault(label) + 1; + } + + if (item.Note is not null && notes.Count < MaxProblems && ExportText.Note(item.Note) is { } noted) + { + notes.Add(new ExportReportLine(item.Id, Name(item.AccountId), item.RelativePath, item.State, noted)); + } + if (item.CopyId is { } copyId && await exports.GetCopyAsync(copyId, ct).ConfigureAwait(false) is { Bytes: { } b }) { bytes += b; @@ -98,9 +129,42 @@ public sealed class ExportReports(ExportEnvironment env) } var perAccount = accounts - .Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3])) + .Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3]) + { + AsIs = asIs.TryGetValue(a.Key, out var kinds) ? kinds : new Dictionary(), + }) .OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase) .ToList(); - return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems); + return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems) { Notes = notes }; + } + + /// The kind of a file copied as it is, from the codes of its note; null when it was not. + internal static string? AsIsLabel(string? note) + { + if (string.IsNullOrWhiteSpace(note)) + { + return null; + } + + foreach (var code in note.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + var name = code.Split(':', 2)[0]; + var label = name switch + { + ExportText.Notes.AsIsHeif => "HEIC", + ExportText.Notes.AsIsAvif => "AVIF", + ExportText.Notes.AsIsRaw => "raw", + ExportText.Notes.AsIsAnimated => "animata", + ExportText.Notes.AsIsNotRemuxable => "video", + _ when name.StartsWith("AsIs", StringComparison.Ordinal) => "altro", + _ => null, + }; + if (label is not null) + { + return label; + } + } + + return null; } } diff --git a/src/Febe.Core/Export/ExportRunSettings.cs b/src/Febe.Core/Export/ExportRunSettings.cs index de8e04b..f6f6a4b 100644 --- a/src/Febe.Core/Export/ExportRunSettings.cs +++ b/src/Febe.Core/Export/ExportRunSettings.cs @@ -11,6 +11,53 @@ internal static class ExportRunSettings { public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo"); + /// How the frames of a frames job were asked (tappa E3): Istante, Ogni or Numero:N. + public static string FramesKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.fotogrammi"); + + /// «Copia di nuovo» of one copy row: only its exact identity is looked up (decision D11 of tappa E3). + public static string ExactKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.esatta"); + + /// The frames request of a job, or null for a job of whole or converted files. + public static async Task<(FrameMode Mode, int Count)?> GetFramesAsync(ISettingsStore store, long runId, CancellationToken ct) + { + var text = (await store.GetAsync(FramesKey(runId), ct).ConfigureAwait(false))?.Trim(); + if (text is null) + { + return null; + } + + if (string.Equals(text, "Istante", StringComparison.Ordinal)) + { + return (FrameMode.At, 1); + } + + if (string.Equals(text, "Ogni", StringComparison.Ordinal)) + { + return (FrameMode.Every, 0); + } + + return text.StartsWith("Numero:", StringComparison.Ordinal) + && int.TryParse(text.AsSpan("Numero:".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var count) && count > 0 + ? (FrameMode.Count, count) + : null; + } + + public static Task SetFramesAsync(ISettingsStore store, long runId, FrameMode mode, int count, CancellationToken ct) => + store.SetAsync( + FramesKey(runId), + mode switch + { + FrameMode.At => "Istante", + FrameMode.Every => "Ogni", + _ => string.Create(CultureInfo.InvariantCulture, $"Numero:{count}"), + }, + ct); + + public static async Task GetExactAsync(ISettingsStore store, long runId, CancellationToken ct) => + string.Equals((await store.GetAsync(ExactKey(runId), ct).ConfigureAwait(false))?.Trim(), "1", StringComparison.Ordinal); + + public static Task SetExactAsync(ISettingsStore store, long runId, CancellationToken ct) => store.SetAsync(ExactKey(runId), "1", ct); + /// «Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9). public static async Task GetCopyAgainAsync(ISettingsStore store, long runId, CancellationToken ct) { @@ -21,6 +68,14 @@ internal static class ExportRunSettings public static Task SetCopyAgainAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) => store.SetAsync(CopyAgainKey(runId), value ? "1" : null, ct); + /// Every key of the job, in one transaction (a run id can be used again after DeleteRunAsync). public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) => - store.SetAsync(CopyAgainKey(runId), null, ct); + store.SetManyAsync( + new Dictionary + { + [CopyAgainKey(runId)] = null, + [FramesKey(runId)] = null, + [ExactKey(runId)] = null, + }, + ct); } diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs index 16896a1..cec2ba5 100644 --- a/src/Febe.Core/Export/ExportService.cs +++ b/src/Febe.Core/Export/ExportService.cs @@ -15,6 +15,9 @@ namespace Febe.Core.Export; public sealed class ExportService : IAsyncDisposable { private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila."; + + /// A frames request over . + public const string TooManyFramesText = "Più di 20.000 fotogrammi in una richiesta: scegli meno video o un intervallo più lungo"; private const int ItemBatch = 2000; private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250); @@ -114,9 +117,13 @@ public sealed class ExportService : IAsyncDisposable /// recorded and nothing starts. /// /// A copy, an import or a rebuild is running. + /// + /// The request is not valid, or a frames request asks more than 1.000 frames of a video or 20.000 in all (Italian message). + /// public async Task StartAsync(ExportJobRequest request, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); + ExportPlanner.Validate(request); var held = new LeaseHolder(); lock (_gate) { @@ -160,12 +167,32 @@ public sealed class ExportService : IAsyncDisposable var runs = new Dictionary(); var pending = new List(); var exports = _env.Storage.Exports; + if (request.Frames is not null) + { + // Refused before anything is recorded (D12 of tappa E3): a video over 1.000 frames, more than 20.000 in all. + var count = new PlanTally(); + await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false)) + { + count.Add(file); + } + + if (count.OverCap > 0) + { + throw new ArgumentException(ExportFrames.OverCapMessage, nameof(request)); + } + + if (count.Frames > ExportFrames.MaxPerRequest) + { + throw new ArgumentException(TooManyFramesText, nameof(request)); + } + } + try { await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false)) { tally.Add(file); - if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported) + if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap) { continue; } @@ -176,22 +203,28 @@ public sealed class ExportService : IAsyncDisposable new ExportRun { DestinationId = destination, Kind = ExportRunKind.Copy, Origin = request.Origin, State = ExportRunState.Running, StartedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); runs[destination] = run; - if (request.CopyAgain) - { - await ExportRunSettings.SetCopyAgainAsync(_env.Storage.Settings, run.Id, true, CancellationToken.None).ConfigureAwait(false); - } + await RecordRunSettingsAsync(run.Id, request).ConfigureAwait(false); } - pending.Add(new ExportItem + // Frame items of one video are added together, in instant order (the copy takes them as one batch). + IReadOnlyList instants = file.UnknownDuration && request.Frames is { } frames + ? await FrameInstantsAsync(file.Candidate, frames, ct).ConfigureAwait(false) + : [file.FrameAt]; + foreach (var at in instants) { - RunId = run.Id, - MediaId = file.Candidate.MediaId, - AccountId = file.Candidate.AccountId, - SourceSha256 = file.Candidate.Sha256, - Variant = ExportVariant.Whole, - Format = ExportFormat.Original, - State = ExportItemState.Pending, - }); + pending.Add(new ExportItem + { + RunId = run.Id, + MediaId = file.Candidate.MediaId, + AccountId = file.Candidate.AccountId, + SourceSha256 = file.Candidate.Sha256, + Variant = file.Variant, + Format = file.Format, + FrameAt = at, + State = ExportItemState.Pending, + }); + } + if (pending.Count >= ItemBatch) { await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false); @@ -235,6 +268,77 @@ public sealed class ExportService : IAsyncDisposable return new ExportStart(ordered, plan); } + /// + /// The keys of a new job: cleared first (a run id can be used again after DeleteRunAsync), then what a resume + /// needs to know (WP1.2 of tappa E3): «Copia di nuovo», the frames request, the exact identity of «Copia di nuovo» + /// of one copy. + /// + private async Task RecordRunSettingsAsync(long runId, ExportJobRequest request) + { + var store = _env.Storage.Settings; + var none = CancellationToken.None; + await ExportRunSettings.ClearAsync(store, runId, none).ConfigureAwait(false); + if (request.CopyAgain) + { + await ExportRunSettings.SetCopyAgainAsync(store, runId, true, none).ConfigureAwait(false); + } + + if (request.Frames is { } frames) + { + await ExportRunSettings.SetFramesAsync(store, runId, frames.Mode, frames.Count ?? 0, none).ConfigureAwait(false); + } + else if (request.Exact is { Variant: ExportVariant.Frame }) + { + await ExportRunSettings.SetFramesAsync(store, runId, FrameMode.At, 1, none).ConfigureAwait(false); + } + + if (request.Exact is not null) + { + await ExportRunSettings.SetExactAsync(store, runId, none).ConfigureAwait(false); + } + } + + /// + /// The instants of a video whose length the library does not know: its headers are read now (only the library + /// file, never the destination). A video that cannot be read gets one instant, and the copy says «Fotogramma non + /// disponibile per questo video». + /// + private async Task> FrameInstantsAsync(ExportCandidate candidate, ExportFramesRequest frames, CancellationToken ct) + { + TimeSpan? duration = null; + var media = await _env.Storage.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false); + var account = await _env.Storage.Accounts.GetAsync(candidate.AccountId, ct).ConfigureAwait(false); + if (media is not null && account is not null && _env.ResolveSourcePath(account, media) is { } path) + { + try + { + duration = await Task.Run( + () => + { + using var stream = _env.FileSystem.OpenRandomAccess(path); + return VideoFrameReader.ProbeDuration(stream); + }, + ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Not readable now: one instant, the copy tells. + } + } + + if (duration is not { } d || d <= TimeSpan.Zero) + { + return [TimeSpan.Zero]; + } + + if (ExportFrames.FrameCount(d, frames) > ExportFrames.MaxPerVideo) + { + throw new ArgumentException(ExportFrames.OverCapMessage, nameof(frames)); + } + + return [.. ExportFrames.Instants(d, frames).Select(at => (TimeSpan?)at)]; + } + /// /// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a /// paused one checks its destination first and pauses again if it still does not answer). diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs index 384dfc1..ed1edd8 100644 --- a/src/Febe.Core/Export/ExportText.cs +++ b/src/Febe.Core/Export/ExportText.cs @@ -1,5 +1,8 @@ +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.Images; using Febe.Core.Domain; using Febe.Core.Engine; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Export; @@ -24,6 +27,22 @@ public static class ExportText public const string NameTaken = "NameTaken"; public const string PathTaken = "PathTaken"; public const string NotExported = "NotExported"; + + // Tappa E3 (D19): an item's note is a list of codes separated by spaces, «Code» or «Code:Arg». + public const string AsIsHeif = ImageConversionLosses.AsIsHeif; + public const string AsIsAvif = ImageConversionLosses.AsIsAvif; + public const string AsIsRaw = ImageConversionLosses.AsIsRaw; + public const string AsIsAnimated = ImageConversionLosses.AsIsAnimated; + public const string AsIsNotDecodable = ImageConversionLosses.AsIsNotDecodable; + public const string AsIsDeepColor = ImageConversionLosses.AsIsDeepColor; + public const string AsIsCmyk = ImageConversionLosses.AsIsCmyk; + public const string AsIsTooLarge = ImageConversionLosses.AsIsTooLarge; + public const string AsIsNotRemuxable = MediaConversionResult.AsIsNotRemuxable; + public const string FrameNotAvailable = "FrameNotAvailable"; + public const string TransparencyWhite = ImageConversionLosses.TransparencyWhite; + public const string CopiedInAnotherFormat = "CopiedInAnotherFormat"; + public const string LostTracks = Mp4Remuxer.LostTracks; + public const string LostVideoMetadata = Mp4Remuxer.LostVideoMetadata; } /// Name of the state of a file of a job. @@ -49,21 +68,95 @@ public static class ExportText _ => state.ToString(), }; - /// The Italian text of a note code; null for none; an unknown code is shown as it is. - public static string? Note(string? code) => code switch + /// + /// The Italian text of a note: its codes (separated by spaces, D19 of tappa E3) each in Italian, joined with « · »; + /// null for none; an unknown code is shown as it is. + /// + public static string? Note(string? note) + { + if (string.IsNullOrWhiteSpace(note)) + { + return null; + } + + var codes = note.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + return string.Join(" · ", codes.Select(One)); + } + + /// The codes as one note (D19 of tappa E3): the non-empty ones, without repeats, separated by spaces; null for none. + public static string? JoinNotes(IEnumerable codes) + { + ArgumentNullException.ThrowIfNull(codes); + var list = codes.Where(c => !string.IsNullOrWhiteSpace(c)).Select(c => c!.Trim()).Distinct(StringComparer.Ordinal).ToList(); + return list.Count == 0 ? null : string.Join(' ', list); + } + + /// The reason of «non si porta in MP4», from the code of . + private static string RemuxReason(string reason) => reason switch + { + nameof(RemuxRefusal.NotAVideo) => "Febe non lo riconosce come video", + nameof(RemuxRefusal.ContainerNotRemuxable) => "contenitore", + nameof(RemuxRefusal.VideoCodec) => "codec video", + nameof(RemuxRefusal.AudioCodec) => "codec audio", + nameof(RemuxRefusal.MissingConfiguration) => "configurazione del codec mancante", + nameof(RemuxRefusal.EncodedTrack) => "tracce codificate", + nameof(RemuxRefusal.EditList) => "elenco di modifiche", + nameof(RemuxRefusal.NoSamples) => "nessun fotogramma", + nameof(RemuxRefusal.Unreadable) => "file rovinato", + _ => reason, + }; + + private static string One(string code) + { + var colon = code.IndexOf(':', StringComparison.Ordinal); + var name = colon < 0 ? code : code[..colon]; + var arg = colon < 0 ? null : code[(colon + 1)..]; + const string AsIsVideo = "Video copiato com'è: non si porta in MP4 senza ricodificarlo"; + return name switch + { + Notes.AsIsNotRemuxable => arg is { Length: > 0 } ? $"{AsIsVideo} ({RemuxReason(arg)})" : AsIsVideo, + Notes.LostTracks => arg is { Length: > 0 } ? $"Tracce tolte: {arg}" : "Tracce tolte", + _ when arg is null => Note1(code) ?? code, + _ => code, + }; + } + + private static string? Note1(string code) => code switch { - null or "" => null, Notes.SourceMissing => "File non presente in libreria", Notes.AccountRemoved => "L'account è stato rimosso", Notes.Removed => "Tolto dalla destinazione: non si ricopia da solo («Copia di nuovo»)", Notes.Superseded => "Superato da un file nuovo della libreria: non si ricopia da solo", Notes.CopiedForAnotherAccount => "Già copiato per un altro account («Una copia sola»)", - Notes.SourceChanged => "Il file della libreria non corrisponde a quello registrato", + Notes.SourceChanged => "Il file della libreria è cambiato durante la copia", Notes.TooLargeForFileSystem => "Più grande di 4 GB: il disco FAT32 non lo accetta", Notes.NameTaken => "Nome già occupato da un altro file: copiato con un nome libero", Notes.PathTaken => "Percorso preso nel frattempo: riprova", Notes.NotExported => "Non si copia qui: «Esporta questo account» è spento, o il file va in un'altra cartella", - _ => code, + Notes.AsIsHeif => "HEIC copiato com'è", + Notes.AsIsAvif => "AVIF copiato com'è", + Notes.AsIsRaw => "Raw copiato com'è", + Notes.AsIsAnimated => "Immagine animata copiata com'è: convertita perderebbe i fotogrammi dopo il primo", + Notes.AsIsNotDecodable => "Copiato com'è: Febe non riesce a leggere l'immagine", + Notes.AsIsDeepColor => "Copiato com'è: più di 8 bit per colore", + Notes.AsIsCmyk => "Copiato com'è: immagine CMYK", + Notes.AsIsTooLarge => "Copiato com'è: troppo grande per il formato scelto", + Notes.FrameNotAvailable => "Fotogramma non disponibile per questo video", + Notes.TransparencyWhite => "La trasparenza è diventata bianco", + Notes.CopiedInAnotherFormat => "Già copiato in un altro formato", + ImageConversionLosses.LostTexts => "Non tenuti: testi", + ImageConversionLosses.LostColorChunks => "Non tenuti: dati del colore", + ImageConversionLosses.LostIcc => "Non tenuto: profilo ICC", + ImageConversionLosses.LostIccTooLarge => "Non tenuto: profilo ICC troppo grande", + ImageConversionLosses.LostExifTooLarge => "Non tenuto: EXIF troppo grande per JPG", + ImageConversionLosses.LostXmpTooLarge => "Non tenuto: XMP troppo grande", + ImageConversionLosses.LostExifUnreadable => "Non tenuto: EXIF rovinato", + ImageConversionLosses.LostIptc => "Non tenuti: IPTC", + ImageConversionLosses.LostOtherSegments => "Non tenuti: altri blocchi", + ImageConversionLosses.LostCommentTooLarge => "Non tenuto: commento troppo lungo", + ImageConversionLosses.LostExtendedXmp => "Non tenuto: XMP esteso", + Notes.LostVideoMetadata => "Non tenuti: metadati del video", + _ => null, }; /// «1 file copiato», «1.204 file copiati». diff --git a/src/Febe.Core/Library/Conversion/MediaConverter.cs b/src/Febe.Core/Library/Conversion/MediaConverter.cs index 7f3d36f..a5b3c08 100644 --- a/src/Febe.Core/Library/Conversion/MediaConverter.cs +++ b/src/Febe.Core/Library/Conversion/MediaConverter.cs @@ -44,6 +44,9 @@ public static class MediaConverter ".dng", ".cr2", ".cr3", ".nef", ".arw", ".raf", ".orf", ".rw2", ".pef", ".srw", }; + /// A raw camera format by its extension (with its dot), copied as it is. + public static bool IsRawExtension(string extension) => RawExtensions.Contains(extension); + /// /// Prepares (only its name is used) in . /// opens the source for reading, seekable; it may be called more than once. diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs index c8f1b81..3241720 100644 --- a/src/Febe.Core/Storage/IExportStore.cs +++ b/src/Febe.Core/Storage/IExportStore.cs @@ -162,6 +162,12 @@ public interface IExportStore Task GetItemAsync(long itemId, CancellationToken ct = default); + /// + /// The first item of a library file in a job with this variant and format, any state; null when none. The frames of + /// a video are added together in instant order, so an item's position among them is its id minus this one. + /// + Task FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default); + /// Items of a job, by key, with an optional state. Task> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default); @@ -177,22 +183,40 @@ public interface IExportStore Task> ListAccountExportSwitchesAsync(CancellationToken ct = default); /// - /// The newest Superseded or Removed row of (destination, account) whose is - /// this SHA-256: the library file that took the place of a copied one, never copied again by itself. + /// The newest Superseded or Removed row, not a frame, of (destination, account) whose + /// is this SHA-256: the library file that took the place of a copied one, + /// never copied again by itself (a superseded frame never makes the file «Superato»). /// Task FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default); /// - /// «Una copia sola»: the newest Copied row of this original, variant and format in a destination in use (the general - /// folder or the own folder of an account still in Febe), of an account still in Febe; with - /// , of an account other than that one, so a newer row of the account itself never - /// hides the copy of another account (decision of 2026-11-27: «una copia altrove conta solo se è di un altro account»). + /// «Una copia sola»: the newest Copied row of this original, in any form but a frame (whole or converted, decision D3 + /// of tappa E3), in a destination in use (the general folder or the own folder of an account still in Febe), of an + /// account still in Febe; with , of an account other than that one, so a newer row + /// of the account itself never hides the copy of another account (decision of 2026-11-27: «una copia altrove conta + /// solo se è di un altro account»). /// - Task FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default); + Task FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default); /// - /// The state of whole copies (, ) of (account, - /// SHA-256) pairs in one destination, for the plan: the current row (Copied or Failed) first, else the newest row + /// The current (Copied or Failed) rows of an original for an account in a destination, in any form but a frame, + /// newest first: «già copiato» looks at the file, not at its format (decision D3 of tappa E3). + /// + Task> ListCurrentCopiesAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default); + + /// The newest row, in any state and any form but a frame, of an original for an account in a destination (D3 of tappa E3). + Task FindLatestCopyAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default); + + /// + /// After a copy of an original succeeded: its other current «Non riuscito» rows in any form but a frame, for the + /// account in the destination, are deleted (they have no file; the identity is kept). + /// Returns the rows deleted. + /// + Task ClearFailedAsync(long destinationId, long accountId, string sha256, ExportCopyIdentity except, CancellationToken ct = default); + + /// + /// The state of the copies of (account, SHA-256) pairs in one destination, in any form but a frame (decision D3 of + /// tappa E3), for the plan: Copied when a current row is Copied, else Failed when one is Failed, else the newest row /// when Removed or Superseded, else Removed or Superseded when a row was replaced by this SHA-256 /// (). Pairs without any are absent. /// @@ -227,7 +251,7 @@ public interface IExportStore /// Task> GetEntryCopyCountsAsync(IReadOnlyList entryIds, CancellationToken ct = default); - /// The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent. + /// The mark of single files («Tutte le foto»): Copied, FrameOnly or None; files that are not due are absent. Task> GetFileMarksAsync(IReadOnlyList mediaIds, CancellationToken ct = default); /// The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2). @@ -246,7 +270,8 @@ public sealed record ExportCandidate( long? Bytes, string? RelativePath, int Position, - bool InHighlight); + bool InHighlight, + TimeSpan? Duration = null); /// The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato». public enum ExportMark @@ -254,13 +279,21 @@ public enum ExportMark None, Partly, Copied, + + /// «Solo fotogrammi»: no due file is copied, at least one has a frame copied (decision D4 of tappa E3). + FrameOnly, } -/// The due files of an entry and how many are copied (decision D3 of tappa E2). -public sealed record ExportEntryCopies(int Due, int Copied) +/// +/// The due files of an entry and how many are copied (decision D3 of tappa E2): a frame never makes a file copied; a +/// file with only frames copied counts in (decision D4 of tappa E3). +/// +public sealed record ExportEntryCopies(int Due, int Copied, int FrameOnly = 0) { - /// «Non ancora copiato» (none), «Copiato in parte», «Copiato». - public ExportMark Mark => Copied <= 0 ? ExportMark.None : Copied >= Due ? ExportMark.Copied : ExportMark.Partly; + /// «Non ancora copiato» (none), «Solo fotogrammi», «Copiato in parte», «Copiato». + public ExportMark Mark => Copied <= 0 + ? FrameOnly > 0 ? ExportMark.FrameOnly : ExportMark.None + : Copied >= Due ? ExportMark.Copied : ExportMark.Partly; } /// Counts of the due files of an account (decision D3 of tappa E2). diff --git a/src/Febe.Data/Stores/ExportFilterSql.cs b/src/Febe.Data/Stores/ExportFilterSql.cs index 82983b4..20b1c5f 100644 --- a/src/Febe.Data/Stores/ExportFilterSql.cs +++ b/src/Febe.Data/Stores/ExportFilterSql.cs @@ -137,10 +137,21 @@ internal static class ExportFilterSql private static string OneOnlyMatch(ExportFilterContext x) => $"((c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id) OR (c.account_id IS NOT NULL AND c.account_id <> e.account_id))"; - /// The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again. + /// + /// The last copy of the file in its effective destination failed («Non riuscito»), in any form but a frame: «Copia + /// in…» tries again. + /// public static string Failed(ExportFilterContext x) => !x.HasFailed ? "0" - : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed')"; + : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed' AND c.variant <> 'Frame')"; + + /// + /// A frame of the file is copied in its effective destination (decision D4 of tappa E3): it never makes the file + /// copied, only the mark «Solo fotogrammi» of a file not copied otherwise. «Una copia sola» does not apply to frames. + /// + public static string FrameCopied(ExportFilterContext x) => !x.HasCopies + ? "0" + : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Copied' AND c.variant = 'Frame')"; /// /// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was @@ -286,9 +297,9 @@ internal static class ExportFilterSql { var destination = DestinationOf(x); var removed = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " - + "AND c.state IN ('Removed', 'Superseded'))"; + + "AND c.state IN ('Removed', 'Superseded') AND c.variant <> 'Frame')"; var superseded = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " - + "AND c.state IN ('Superseded', 'Removed'))"; + + "AND c.state IN ('Superseded', 'Removed') AND c.variant <> 'Frame')"; if (!bulk) { return $"({removed} OR {superseded})"; diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs index fbde21a..e0fadc7 100644 --- a/src/Febe.Data/Stores/ExportStore.cs +++ b/src/Febe.Data/Stores/ExportStore.cs @@ -826,6 +826,16 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore public Task GetItemAsync(long itemId, CancellationToken ct = default) => db.ReadAsync(c => ReadFirst(c.Command($"SELECT {ItemColumns} FROM export_item WHERE id = @id").With("@id", itemId), ReadItem), ct); + /// The first item of a file of a job in a form (ux_export_item_file). + internal const string FirstItemSql = "SELECT min(id) FROM export_item WHERE run_id = @r AND media_id = @m AND variant = @v AND format = @f"; + + public Task FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default) => + db.ReadAsync( + c => c.Command(FirstItemSql).With("@r", runId).With("@m", mediaId).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).ExecuteScalar() is long id + ? id + : (long?)null, + ct); + public Task> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(query); @@ -878,13 +888,37 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore internal const string ReplacedCopySql = $""" SELECT {CopyColumns} FROM export_copy - WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed') + WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed') AND variant <> 'Frame' ORDER BY id DESC LIMIT 1 """; + /// + /// The current rows of an original, any form but a frame (decision D3 of tappa E3; @h, @d, @a). INDEXED BY keeps + /// it on ix_export_copy_sha256 (a few rows, sorted): for «ORDER BY id» the planner would read a whole destination. + /// + internal const string CurrentCopiesAnyFormSql = $""" + SELECT {CopyColumns} FROM export_copy INDEXED BY ix_export_copy_sha256 + WHERE source_sha256 = @h AND destination_id = @d AND account_id = @a AND variant <> 'Frame' AND state IN ('Copied', 'Failed') + ORDER BY id DESC + """; + + /// The newest row of an original, any state and any form but a frame (@h, @d, @a). + internal const string LatestCopyAnyFormSql = $""" + SELECT {CopyColumns} FROM export_copy INDEXED BY ix_export_copy_sha256 + WHERE source_sha256 = @h AND destination_id = @d AND account_id = @a AND variant <> 'Frame' + ORDER BY id DESC LIMIT 1 + """; + + /// The «Non riuscito» rows of an original that a success leaves stale (@h, @d, @a; the kept identity @v, @f). + internal const string ClearFailedSql = """ + DELETE FROM export_copy + WHERE source_sha256 = @h AND destination_id = @d AND account_id = @a AND variant <> 'Frame' AND state = 'Failed' + AND NOT (variant = @v AND format = @f) + """; + internal const string CopiedElsewhereSql = $""" SELECT {CopyColumns} FROM export_copy - WHERE source_sha256 = @h AND variant = @v AND format = @f AND state = 'Copied' AND account_id IS NOT NULL + WHERE source_sha256 = @h AND variant <> 'Frame' AND state = 'Copied' AND account_id IS NOT NULL AND (@a IS NULL OR account_id <> @a) AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL AND (scope = 'General' OR account_id IS NOT NULL)) ORDER BY id DESC LIMIT 1 @@ -892,10 +926,13 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore internal const string RecentRunsSql = $"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC LIMIT @limit"; - /// The whole copies of a destination for some originals (ix_export_copy_sha256); @d and the list of SHA-256. + /// + /// The copies of a destination for some originals, in any form but a frame (ix_export_copy_sha256; decision D3 of + /// tappa E3); @d and the list of SHA-256. + /// internal static string CopyStatesSql(string shaList) => $""" SELECT account_id, source_sha256, state, id FROM export_copy - WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant = 'Whole' AND format = 'Original' + WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant <> 'Frame' """; /// @@ -906,11 +943,12 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore internal static string ReplacedStatesSql(string shaList) => $""" SELECT account_id, superseded_by_sha256, state, id FROM export_copy WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND +state IN ('Superseded', 'Removed') + AND variant <> 'Frame' """; private const string CandidateColumns = "m.id, m.entry_id, e.account_id, e.kind, m.kind, m.state, m.sha256, m.bytes, m.relative_path, m.position, " - + "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id)"; + + "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id), m.duration_ms"; private static ExportCandidate ReadCandidate(SqliteDataReader r) => new( r.GetInt64(0), @@ -923,7 +961,8 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore r.GetInt64OrNull(7), r.GetTextOrNull(8), r.GetInt32(9), - r.GetBool(10)); + r.GetBool(10), + r.GetDurationOrNull(11)); public Task> ListAccountExportSwitchesAsync(CancellationToken ct = default) => db.ReadAsync>( @@ -948,16 +987,44 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore ct); } - public Task FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default) + public Task FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default) { var sha = ExportValues.Sha(sha256, nameof(sha256)); return db.ReadAsync( c => ReadFirst( - c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).With("@a", Sql.Int(exceptAccountId)), + c.Command(CopiedElsewhereSql).With("@h", sha).With("@a", Sql.Int(exceptAccountId)), ReadCopy), ct); } + public Task> ListCurrentCopiesAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default) + { + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.ReadAsync>( + c => ReadAll(c.Command(CurrentCopiesAnyFormSql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy), + ct); + } + + public Task FindLatestCopyAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default) + { + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.ReadAsync( + c => ReadFirst(c.Command(LatestCopyAnyFormSql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy), + ct); + } + + public Task ClearFailedAsync(long destinationId, long accountId, string sha256, ExportCopyIdentity except, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(except); + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.WriteAsync( + w => w.Command(ClearFailedSql) + .With("@h", sha).With("@d", destinationId).With("@a", accountId) + .With("@v", Sql.Enum(except.Variant)).With("@f", Sql.Enum(except.Format)) + .ExecuteNonQuery(), + ct); + } + public Task> GetCopyStatesAsync( long destinationId, IReadOnlyCollection<(long AccountId, string Sha256)> keys, @@ -968,8 +1035,9 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore return db.ReadAsync>( c => { - // Per pair: the current row (Copied or Failed), else the newest row when Removed or Superseded, else a row - // replaced by this file. Rows of other accounts that share a SHA-256 are read and dropped here. + // Per pair, over every form but a frame (D3 of tappa E3): a Copied row, else a Failed one, else the newest + // row when Removed or Superseded, else a row replaced by this file. Rows of other accounts that share a + // SHA-256 are read and dropped here. var current = new Dictionary<(long, string), ExportCopyState>(); var newest = new Dictionary<(long, string), (long Id, ExportCopyState State)>(); var replaced = new Dictionary<(long, string), (long Id, ExportCopyState State)>(); @@ -1000,7 +1068,7 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore { Read(CopyStatesSql, chunk, (key, state, id) => { - if (state is ExportCopyState.Copied or ExportCopyState.Failed) + if (state == ExportCopyState.Copied || (state == ExportCopyState.Failed && !current.ContainsKey(key))) { current[key] = state; } @@ -1134,12 +1202,15 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore return marks; } + var copied = ExportFilterSql.Copied(x); + var frames = ExportFilterSql.FrameCopied(x); foreach (var chunk in entryIds.Distinct().Chunk(IdChunk)) { using var command = c.Command(string.Empty); var list = command.AddList("x", chunk); command.CommandText = $""" - SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END) + SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {copied} THEN 1 ELSE 0 END), + SUM(CASE WHEN NOT {copied} AND {frames} THEN 1 ELSE 0 END) FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.entry_id IN ({list}) AND {ExportFilterSql.DueFile(x)} GROUP BY m.entry_id @@ -1147,7 +1218,7 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore using var r = command.ExecuteReader(); while (r.Read()) { - marks[r.GetInt64(0)] = new ExportEntryCopies(r.GetInt32(1), r.GetInt32(2)); + marks[r.GetInt64(0)] = new ExportEntryCopies(r.GetInt32(1), r.GetInt32(2), r.GetInt32(3)); } } @@ -1174,13 +1245,13 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore using var command = c.Command(string.Empty); var list = command.AddList("x", chunk); command.CommandText = $""" - SELECT m.id, {ExportFilterSql.Copied(x)} FROM media m JOIN entry e ON e.id = m.entry_id + SELECT m.id, {ExportFilterSql.Copied(x)}, {ExportFilterSql.FrameCopied(x)} FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.id IN ({list}) AND {ExportFilterSql.DueFile(x)} """; using var r = command.ExecuteReader(); while (r.Read()) { - marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : ExportMark.None; + marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : r.GetInt64(2) != 0 ? ExportMark.FrameOnly : ExportMark.None; } } diff --git a/tests/Febe.Tests/Data/ExportConstraintTests.cs b/tests/Febe.Tests/Data/ExportConstraintTests.cs index 8109321..542e81c 100644 --- a/tests/Febe.Tests/Data/ExportConstraintTests.cs +++ b/tests/Febe.Tests/Data/ExportConstraintTests.cs @@ -603,6 +603,7 @@ public sealed class ExportConstraintTests ("ListItemsAsync", ExportStore.ItemsOfRunSql(false), [("@r", run), ("@after", 0L), ("@limit", 500L)], false), ("ListItemsAsync (stato)", ExportStore.ItemsOfRunSql(true), [("@r", run), ("@s", "Pending"), ("@after", 0L), ("@limit", 500L)], false), ("ListPendingAsync", MediaConversionStore.PendingSql, [("@after", 0L), ("@limit", 500L)], false), + ("FirstItemIdAsync", ExportStore.FirstItemSql, [("@r", run), ("@m", 1L), ("@v", "Frame"), ("@f", "Png")], false), }; var problems = new List(); foreach (var (name, sql, parameters, sortAllowed) in lookups) @@ -637,7 +638,12 @@ public sealed class ExportConstraintTests var lookupsE2 = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[] { ("FindReplacedCopyAsync", ExportStore.ReplacedCopySql, [("@h", Make.Sha(5008)), ("@d", w.General), ("@a", w.Marta)], false), - ("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@v", "Whole"), ("@f", "Original"), ("@a", w.Marta)], true), + ("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@a", w.Marta)], true), + + // Tappa E3 (D3): the lookups of a file in any form but a frame sort the few rows of one SHA-256. + ("ListCurrentCopiesAnyFormAsync", ExportStore.CurrentCopiesAnyFormSql, [("@h", Make.Sha(17)), ("@d", w.General), ("@a", w.Marta)], true), + ("FindLatestCopyAnyFormAsync", ExportStore.LatestCopyAnyFormSql, [("@h", Make.Sha(17)), ("@d", w.General), ("@a", w.Marta)], true), + ("ClearFailedAsync", ExportStore.ClearFailedSql, [("@h", Make.Sha(17)), ("@d", w.General), ("@a", w.Marta), ("@v", "Converted"), ("@f", "Png")], false), ("GetCopyStatesAsync", ExportStore.CopyStatesSql(shas), Shas(("@d", w.General)), false), ("GetCopyStatesAsync (sostituiti)", ExportStore.ReplacedStatesSql(shas), Shas(("@d", w.General)), false), }; diff --git a/tests/Febe.Tests/Data/ExportStoreTests.cs b/tests/Febe.Tests/Data/ExportStoreTests.cs index fbb28fb..55508c8 100644 --- a/tests/Febe.Tests/Data/ExportStoreTests.cs +++ b/tests/Febe.Tests/Data/ExportStoreTests.cs @@ -534,26 +534,37 @@ public sealed class ExportStoreTests using var temp = new TempFolder(); await using var db = await TestDatabase.OpenAsync(temp); var w = await CreateAsync(db); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original)); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1))); var own = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own)); var general = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia)); await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Removed }); - Assert.AreEqual(general.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id, "the newest Copied row"); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Jpg), "another format"); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(2), ExportVariant.Whole, ExportFormat.Original)); + Assert.AreEqual(general.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1)))!.Id, "the newest Copied row"); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(2))); + + // Tappa E3 (D3): a file copied in any form but a frame counts; a frame never does. + var converted = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/c.jpg", account: w.Luca, media: w.LucaMedia) with + { + SourceSha256 = Make.Sha(3), CopySha256 = Make.Sha(4), Variant = ExportVariant.Converted, Format = ExportFormat.Jpg, + }); + Assert.AreEqual(converted.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(3)))!.Id, "a Converted Jpg copy counts"); + await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/f_t0m01s000.png", account: w.Luca, media: w.LucaMedia) with + { + SourceSha256 = Make.Sha(7), CopySha256 = Make.Sha(8), Variant = ExportVariant.Frame, Format = ExportFormat.Png, FrameAt = TimeSpan.FromSeconds(1), + }); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(7)), "a frame does not count"); await db.Exports.RetireDestinationAsync(w.General, Make.T0.AddDays(1)); - Assert.AreEqual(own.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id); + Assert.AreEqual(own.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1)))!.Id); await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1)); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original), "a retired folder is not in use"); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1)), "a retired folder is not in use"); // A copy whose account was removed has no account to be «per un altro account». var third = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, @"G:\Nuova")); var orphan = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg", destination: third.Id)); await db.Accounts.DeleteAsync(w.Marta); Assert.IsNull((await db.Exports.GetCopyAsync(orphan.Id))!.AccountId); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original)); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1))); } [TestMethod] diff --git a/tests/Febe.Tests/Export/ExportConversionTests.cs b/tests/Febe.Tests/Export/ExportConversionTests.cs new file mode 100644 index 0000000..539fe68 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportConversionTests.cs @@ -0,0 +1,95 @@ +using System.Security.Cryptography; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Tests.Codecs.Containers; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The copy job of tappa E3 on real folders (WP1.7): a converted copy and a frame copy. The full set of cases is WP6a's; +/// the media are built by the tests. +/// +[TestClass] +public sealed class ExportConversionTests +{ + private static readonly byte[] PngSignature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task APhotoIsConvertedAndThenCountsAsCopiedInAnyForm() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "960", 31); + var media = post.Media[0]; + await bed.GeneralAsync(ct: ct); + + var start = await bed.CopyAsync( + new ExportJobRequest(new ExportSelection.Media([media.Id]), Formats: new ExportFormatChoice(ExportFormat.Png, null)), ct); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportVariant.Converted, ExportFormat.Png), (item.State, item.Variant, item.Format)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png, media.Sha256), (copy.Variant, copy.Format, copy.SourceSha256)); + Assert.AreEqual("marta.demo/" + Path.ChangeExtension(media.RelativePath!, ".png"), copy.RelativePath); + + var file = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)); + var bytes = await File.ReadAllBytesAsync(file, ct); + CollectionAssert.AreEqual(PngSignature, bytes[..8]); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(bytes)), copy.CopySha256); + Assert.AreNotEqual(media.Sha256, copy.CopySha256); + Assert.AreEqual(bytes.Length, copy.Bytes); + Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Marta, media)), "no byte copy next to it"); + + // «Già copiato» is any form but a frame (D3): a copy of the account in Originale writes nothing more. + var again = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var second = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, copy.Id, ExportText.Notes.CopiedInAnotherFormat), (second.State, second.CopyId, second.Note)); + Assert.AreEqual("Già copiato in un altro formato", ExportText.Note(second.Note)); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task AFrameIsWrittenWithItsInstantAndLeavesTheVideoToCopy() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D")); + var post = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "961", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")]); + var video = post.Media[0]; + await bed.GeneralAsync(ct: ct); + + var frames = new ExportFramesRequest(FrameMode.At, TimeSpan.Zero, null, null, ExportFormat.Png); + var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: frames), ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Completed, run.State); + var item = (await bed.ItemsAsync(run.Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportVariant.Frame, ExportFormat.Png, (TimeSpan?)TimeSpan.Zero), (item.State, item.Variant, item.Format, item.FrameAt)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Frame, ExportFormat.Png, video.Sha256), (copy.Variant, copy.Format, copy.SourceSha256)); + Assert.IsNotNull(copy.FrameAt); + StringAssert.Contains(copy.RelativePath, "_t0m00s"); + StringAssert.EndsWith(copy.RelativePath, ".png"); + + var bytes = await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)), ct); + CollectionAssert.AreEqual(PngSignature, bytes[..8]); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(bytes)), copy.CopySha256); + + // A frame never makes the file copied (D4): the mark says so, and «Copia in…» copies the video itself. + Assert.AreEqual(ExportMark.FrameOnly, (await bed.Db.Exports.GetFileMarksAsync([video.Id], ct))[video.Id]); + var whole = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var copied = (await bed.ItemsAsync(whole.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportVariant.Whole), (copied.State, copied.Variant)); + Assert.AreEqual(ExportMark.Copied, (await bed.Db.Exports.GetFileMarksAsync([video.Id], ct))[video.Id]); + + // The same instant asked again is «Già copiato» (its exact identity, D12). + var repeat = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: frames), ct); + var same = (await bed.ItemsAsync(repeat.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, copy.Id), (same.State, same.CopyId)); + Assert.HasCount(2, Fingerprint.Of(bed.Usb)); + } +} diff --git a/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs b/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs index 1902b26..ac0d597 100644 --- a/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs +++ b/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs @@ -100,7 +100,7 @@ public sealed class ExportCopiesFilterTests Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyStatesAsync(w.Own, [(w.Marta, Make.Sha(1))], ct))[(w.Marta, Make.Sha(1))]); Assert.IsNotNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Luca, Make.Sha(1), ct)); Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.Own, w.Luca, Make.Sha(1), ct)); - Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, ct: ct))!.Id); + Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ct: ct))!.Id); var byAccount = await db.Exports.ListCandidatesAsync(new ExportSelection.Account(w.Marta), 0, 10, ct); Assert.AreEqual(w.MartaMedia, byAccount.Single().MediaId);