E3: formati e fotogrammi nella copia verso le cartelle esterne

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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 23:08:38 +01:00
1 parent 704c1ed9cf
commit b746aff45d
19 files changed
+1941 -257

No files matched your search

+87
View File
@@ -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;
/// <summary>
/// The conversion of a library file for a copy (tappa E3, WP1.6b): <see cref="MediaConverter"/> with the files of the
/// export environment, and the hash of content that is only known once written (a remux).
/// </summary>
internal static class ExportConversion
{
/// <summary>Prepares the library file at <paramref name="source"/> in <paramref name="target"/> (never Original).</summary>
/// <exception cref="ContentChangedException">A photo's bytes are not those of <paramref name="sha256"/>.</exception>
public static Task<MediaConversionResult> 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);
/// <summary>The SHA-256 (lowercase hex) and length of what <paramref name="produce"/> writes, written nowhere.</summary>
public static async Task<(string Sha256, long Length)> HashAsync(Func<Stream, CancellationToken, Task> produce, CancellationToken ct)
{
await using var sink = new HashingSink();
await produce(sink, ct).ConfigureAwait(false);
return (sink.Finish(), sink.Length);
}
/// <summary>A stream that only hashes and counts what is written to it.</summary>
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<byte> buffer)
{
hash.AppendData(buffer);
length += buffer.Length;
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> 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);
}
}
}
+99
View File
@@ -0,0 +1,99 @@
using Febe.Core.Domain;
using Febe.Core.Library.Conversion;
namespace Febe.Core.Export;
/// <summary>What the plan expects of a file in a format, from its name only (tappa E3: the copy decides on the bytes).</summary>
public enum ExportPrediction
{
/// <summary>Copied byte for byte: Original, or already in the format asked.</summary>
Whole,
/// <summary>Converted into the format asked.</summary>
Converted,
/// <summary>Copied as it is with a note (HEIC, AVIF, raw, GIF, WebM).</summary>
AsIs,
}
/// <summary>
/// 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.
/// </summary>
public static class ExportConversions
{
/// <summary>
/// The format of a file of <paramref name="kind"/>: 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.
/// </summary>
public static ExportFormat Resolve(MediaKind kind, ExportFormatChoice? request, ExportDestination destination, ExportSettings settings)
{
ArgumentNullException.ThrowIfNull(destination);
ArgumentNullException.ThrowIfNull(settings);
Func<ExportFormat, bool> 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;
}
/// <summary>The variant a format asks for: Whole for Original, Converted otherwise.</summary>
public static ExportVariant VariantOf(ExportFormat format) => format == ExportFormat.Original ? ExportVariant.Whole : ExportVariant.Converted;
/// <summary>
/// What the plan expects, by extension («circa»): Original, or the same format (<c>.jpg/.jpeg</c>, <c>.png</c>,
/// <c>.webp</c>, <c>.mp4</c>) → Whole; HEIC, HEIF, AVIF, raw, GIF and WebM → AsIs; anything else → Converted.
/// </summary>
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;
}
/// <summary>The kind of a file copied as it is, for «3 HEIC copiati come sono»: «HEIC», «AVIF», «raw», «GIF», «WebM»; null otherwise.</summary>
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,
};
}
/// <summary>The effective identity the plan expects (D2): (Converted, format) when predicted converted, else (Whole, Original).</summary>
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);
}
File diff suppressed because it is too large. Load diff
+18 -1
View File
@@ -15,6 +15,8 @@ namespace Febe.Core.Export;
/// <param name="ProfileNamingScheme">Scheme of profile pictures; null: «Come la libreria».</param>
/// <param name="Automatic">«Automatica»: stored only in tappa E2 (tappa E5 acts on it).</param>
/// <param name="OnlyNew">«Solo i nuovi» when «Automatica» is turned on.</param>
/// <param name="PhotoFormat">Format of the copies of photos here; null: «Come le impostazioni generali» (tappa E3, D1).</param>
/// <param name="VideoFormat">Format of the copies of videos here (Original or Mp4); null: «Come le impostazioni generali».</param>
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);
/// <summary>A saved destination and the warnings of its naming schemes (shown, they do not block).</summary>
public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList<string> 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<string>();
var warnings = new List<string>();
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,
};
+16 -1
View File
@@ -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
/// <summary>…or this many planned bytes, whichever comes first.</summary>
public long GroupBytes { get; init; } = 1L << 30;
/// <summary>One conversion at a time in the process (tappa E3, D16): shared with the library conversion.</summary>
public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
/// <summary>The checker of destination folders of this environment.</summary>
public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe);
@@ -101,6 +105,12 @@ public interface IExportFileSystem
/// <summary>Opens a file for reading only.</summary>
Stream OpenRead(string path);
/// <summary>
/// Opens a file for reading at any position (a video to remux or to take frames from, tappa E3). By default the
/// stream of <see cref="OpenRead"/>, which can seek.
/// </summary>
Stream OpenRandomAccess(string path) => OpenRead(path);
/// <summary>SHA-256 (lowercase hex) of a file as it is on disk now.</summary>
Task<string> 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);
/// <summary>As <c>ContainerReader.OpenRead</c>: shared for reading, writing and deleting, read at random positions.</summary>
public Stream OpenRandomAccess(string path) =>
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, BufferSize, FileOptions.RandomAccess);
public async Task<string> ComputeSha256Async(string path, CancellationToken ct)
{
+47 -1
View File
@@ -39,8 +39,27 @@ public enum FrameMode
/// <summary>A request of frames of videos, in a photo format (Jpg, Png or WebpLossless).</summary>
public sealed record ExportFramesRequest(FrameMode Mode, TimeSpan? At, TimeSpan? Every, int? Count, ExportFormat Format);
/// <summary>
/// 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.
/// </summary>
public sealed record ExportFormatChoice(ExportFormat? Photo, ExportFormat? Video);
/// <summary>«Copia di nuovo» of one copy row (tappa E3, D11): the form of that row, looked up only by its exact identity.</summary>
/// <param name="FrameAt">The instant of a frame row; null otherwise.</param>
public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt);
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual);
/// <param name="Formats">The formats of this request («Copia in…» → «Cambia»); null: those of the destination.</param>
/// <param name="Frames">Not null: a frames job («Fotogrammi…» → «Nella cartella delle copie»), videos only.</param>
/// <param name="Exact">«Copia di nuovo» of one copy row, only with a selection of one file.</param>
public sealed record ExportJobRequest(
ExportSelection Selection,
bool CopyAgain = false,
ExportRunOrigin Origin = ExportRunOrigin.Manual,
ExportFormatChoice? Formats = null,
ExportFramesRequest? Frames = null,
ExportCopyRequest? Exact = null);
/// <summary>
/// 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, []);
/// <summary>
/// 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).
/// </summary>
public IReadOnlyList<ExportPlanAsIs> AsIs { get; init; } = [];
/// <summary>Files predicted to be converted.</summary>
public int Converted { get; init; }
/// <summary>«Con perdita»: at least one file predicted converted to JPG, or JPG frames (D7 of tappa E3).</summary>
public bool Lossy { get; init; }
/// <summary>Frames job: the due videos.</summary>
public int Videos { get; init; }
/// <summary>Frames job: the photos of the selection, skipped («Le 4 foto si saltano»).</summary>
public int PhotosSkipped { get; init; }
/// <summary>Frames job: the frames to write (also in <see cref="Files"/>); «circa» for a video of unknown length.</summary>
public int Frames { get; init; }
/// <summary>Frames job: videos that would give more than <see cref="ExportFrames.MaxPerVideo"/> frames (the job is refused).</summary>
public int OverCap { get; init; }
}
/// <summary>Files of a plan copied as they are, of one kind («HEIC», «AVIF», «raw», «GIF», «WebM»).</summary>
public sealed record ExportPlanAsIs(string Label, int Files);
/// <summary>A destination of a plan.</summary>
/// <param name="Username">The account of an own folder; null for the general folder.</param>
/// <param name="Files">Files to write there.</param>
+309 -17
View File
@@ -6,8 +6,10 @@ namespace Febe.Core.Export;
/// <summary>
/// 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.
/// </summary>
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));
/// <summary>The plan of a request, for the «Copia in…» dialog.</summary>
/// <exception cref="ArgumentException">The request is not valid (Italian message).</exception>
public async Task<ExportPlan> 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);
}
/// <summary>The checks of a request (tappa E3, WP1.1), with Italian messages.</summary>
/// <exception cref="ArgumentException">What is wrong.</exception>
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));
}
}
}
/// <summary>JPG, PNG or WEBP senza perdita: the formats of a frame.</summary>
internal static bool IsFrameFormat(ExportFormat format) => format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless;
/// <summary>
/// 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.
/// </summary>
internal async IAsyncEnumerable<PlannedFile> 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<long, IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>();
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)
}
}
/// <summary>
/// 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 (<see cref="PlannedFile.UnknownDuration"/>): 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.
/// </summary>
private async IAsyncEnumerable<PlannedFile> EnumerateFramesAsync(
ExportJobRequest request,
ExportFramesRequest frames,
IReadOnlyDictionary<long, EffectiveDestination> 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;
}
}
}
}
/// <summary>The form a file is asked in (D1, D2): the request's identity, and what its name predicts.</summary>
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),
};
}
/// <summary>A file present in the library, with its SHA-256 and path.</summary>
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)
/// <summary>A candidate with what the plan does with it.</summary>
/// <param name="DestinationId">Where it goes; null when not exported or missing.</param>
/// <param name="Again">Written although «Tolto» or «Superato», because «Copia di nuovo» was asked.</param>
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)
{
/// <summary>The variant asked (the request, D2 of tappa E3): Whole, Converted or Frame.</summary>
public ExportVariant Variant { get; init; } = ExportVariant.Whole;
/// <summary>The format asked.</summary>
public ExportFormat Format { get; init; } = ExportFormat.Original;
/// <summary>The instant asked of a frame.</summary>
public TimeSpan? FrameAt { get; init; }
/// <summary>What the name predicts («circa»).</summary>
public ExportPrediction Prediction { get; init; } = ExportPrediction.Whole;
/// <summary>Frames job: the first planned file of its video (the videos are counted on it).</summary>
public bool FirstOfVideo { get; init; }
/// <summary>Frames job: a video of unknown length, without instants yet («circa» one frame).</summary>
public bool UnknownDuration { get; init; }
}
internal enum PlannedCopy
{
@@ -144,12 +380,19 @@ internal enum PlannedCopy
RemovedOrSuperseded,
NotExported,
Missing,
/// <summary>Frames job: a photo of the selection.</summary>
PhotoSkipped,
/// <summary>Frames job: a video over <see cref="ExportFrames.MaxPerVideo"/> frames.</summary>
OverCap,
}
/// <summary>Counts of a plan while its files go by.</summary>
internal sealed class PlanTally
{
private readonly Dictionary<long, (int Files, long Bytes)> _byDestination = [];
private readonly Dictionary<string, int> _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,
};
}
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
+68 -4
View File
@@ -12,10 +12,24 @@ public sealed record ExportReport(
IReadOnlyDictionary<ExportItemState, int> ByState,
long BytesCopied,
IReadOnlyList<ExportReportAccount> Accounts,
IReadOnlyList<ExportReportLine> Problems);
IReadOnlyList<ExportReportLine> Problems)
{
/// <summary>
/// Tappa E3: at most <see cref="ExportReports.MaxProblems"/> files copied or adopted with a note (copied as they
/// are, what a conversion did not keep, a free name).
/// </summary>
public IReadOnlyList<ExportReportLine> Notes { get; init; } = [];
}
/// <summary>The files of one account in a job («Copiato» counts written and adopted files).</summary>
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)
{
/// <summary>
/// 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.
/// </summary>
public IReadOnlyDictionary<string, int> AsIs { get; init; } = new Dictionary<string, int>();
}
/// <summary>A file of the report, with its reason in Italian.</summary>
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<long, int[]>();
var problems = new List<ExportReportLine>();
var notes = new List<ExportReportLine>();
var asIs = new Dictionary<long, Dictionary<string, int>>();
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<string, int>(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<string, int>(),
})
.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 };
}
/// <summary>The kind of a file copied as it is, from the codes of its note; null when it was not.</summary>
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;
}
}
+56 -1
View File
@@ -11,6 +11,53 @@ internal static class ExportRunSettings
{
public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo");
/// <summary>How the frames of a frames job were asked (tappa E3): <c>Istante</c>, <c>Ogni</c> or <c>Numero:N</c>.</summary>
public static string FramesKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.fotogrammi");
/// <summary>«Copia di nuovo» of one copy row: only its exact identity is looked up (decision D11 of tappa E3).</summary>
public static string ExactKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.esatta");
/// <summary>The frames request of a job, or null for a job of whole or converted files.</summary>
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<bool> 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);
/// <summary>«Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9).</summary>
public static async Task<bool> 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);
/// <summary>Every key of the job, in one transaction (a run id can be used again after <c>DeleteRunAsync</c>).</summary>
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
store.SetAsync(CopyAgainKey(runId), null, ct);
store.SetManyAsync(
new Dictionary<string, string?>
{
[CopyAgainKey(runId)] = null,
[FramesKey(runId)] = null,
[ExactKey(runId)] = null,
},
ct);
}
+118 -14
View File
@@ -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.";
/// <summary>A frames request over <see cref="ExportFrames.MaxPerRequest"/>.</summary>
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.
/// </summary>
/// <exception cref="InvalidOperationException">A copy, an import or a rebuild is running.</exception>
/// <exception cref="ArgumentException">
/// 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).
/// </exception>
public async Task<ExportStart> 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<long, ExportRun>();
var pending = new List<ExportItem>();
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<TimeSpan?> 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);
}
/// <summary>
/// The keys of a new job: cleared first (a run id can be used again after <c>DeleteRunAsync</c>), 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.
/// </summary>
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);
}
}
/// <summary>
/// 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».
/// </summary>
private async Task<IReadOnlyList<TimeSpan?>> 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)];
}
/// <summary>
/// «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).
+98 -5
View File
@@ -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;
}
/// <summary>Name of the state of a file of a job.</summary>
@@ -49,21 +68,95 @@ public static class ExportText
_ => state.ToString(),
};
/// <summary>The Italian text of a note code; null for none; an unknown code is shown as it is.</summary>
public static string? Note(string? code) => code switch
/// <summary>
/// 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.
/// </summary>
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));
}
/// <summary>The codes as one note (D19 of tappa E3): the non-empty ones, without repeats, separated by spaces; null for none.</summary>
public static string? JoinNotes(IEnumerable<string?> 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);
}
/// <summary>The reason of «non si porta in MP4», from the code of <see cref="RemuxRefusal"/>.</summary>
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,
};
/// <summary>«1 file copiato», «1.204 file copiati».</summary>
@@ -44,6 +44,9 @@ public static class MediaConverter
".dng", ".cr2", ".cr3", ".nef", ".arw", ".raf", ".orf", ".rw2", ".pef", ".srw",
};
/// <summary>A raw camera format by its extension (with its dot), copied as it is.</summary>
public static bool IsRawExtension(string extension) => RawExtensions.Contains(extension);
/// <summary>
/// Prepares <paramref name="relativePath"/> (only its name is used) in <paramref name="target"/>.
/// <paramref name="openRandomAccess"/> opens the source for reading, seekable; it may be called more than once.
+48 -15
View File
@@ -162,6 +162,12 @@ public interface IExportStore
Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default);
/// <summary>
/// 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.
/// </summary>
Task<long?> FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default);
/// <summary>Items of a job, by key, with an optional state.</summary>
Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default);
@@ -177,22 +183,40 @@ public interface IExportStore
Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default);
/// <summary>
/// The newest Superseded or Removed row of (destination, account) whose <see cref="ExportCopy.SupersededBySha256"/> 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
/// <see cref="ExportCopy.SupersededBySha256"/> 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»).
/// </summary>
Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
/// <summary>
/// «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
/// <paramref name="exceptAccountId"/>, 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 <paramref name="exceptAccountId"/>, 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»).
/// </summary>
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default);
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default);
/// <summary>
/// The state of whole copies (<see cref="ExportVariant.Whole"/>, <see cref="ExportFormat.Original"/>) 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).
/// </summary>
Task<IReadOnlyList<ExportCopy>> ListCurrentCopiesAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
/// <summary>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).</summary>
Task<ExportCopy?> FindLatestCopyAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
/// <summary>
/// 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 <paramref name="except"/> is kept).
/// Returns the rows deleted.
/// </summary>
Task<int> ClearFailedAsync(long destinationId, long accountId, string sha256, ExportCopyIdentity except, CancellationToken ct = default);
/// <summary>
/// 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
/// (<see cref="FindReplacedCopyAsync"/>). Pairs without any are absent.
/// </summary>
@@ -227,7 +251,7 @@ public interface IExportStore
/// </summary>
Task<IReadOnlyDictionary<long, ExportEntryCopies>> GetEntryCopyCountsAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
/// <summary>The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent.</summary>
/// <summary>The mark of single files («Tutte le foto»): Copied, FrameOnly or None; files that are not due are absent.</summary>
Task<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default);
/// <summary>The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2).</summary>
@@ -246,7 +270,8 @@ public sealed record ExportCandidate(
long? Bytes,
string? RelativePath,
int Position,
bool InHighlight);
bool InHighlight,
TimeSpan? Duration = null);
/// <summary>The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato».</summary>
public enum ExportMark
@@ -254,13 +279,21 @@ public enum ExportMark
None,
Partly,
Copied,
/// <summary>«Solo fotogrammi»: no due file is copied, at least one has a frame copied (decision D4 of tappa E3).</summary>
FrameOnly,
}
/// <summary>The due files of an entry and how many are copied (decision D3 of tappa E2).</summary>
public sealed record ExportEntryCopies(int Due, int Copied)
/// <summary>
/// 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 <paramref name="FrameOnly"/> (decision D4 of tappa E3).
/// </summary>
public sealed record ExportEntryCopies(int Due, int Copied, int FrameOnly = 0)
{
/// <summary>«Non ancora copiato» (none), «Copiato in parte», «Copiato».</summary>
public ExportMark Mark => Copied <= 0 ? ExportMark.None : Copied >= Due ? ExportMark.Copied : ExportMark.Partly;
/// <summary>«Non ancora copiato» (none), «Solo fotogrammi», «Copiato in parte», «Copiato».</summary>
public ExportMark Mark => Copied <= 0
? FrameOnly > 0 ? ExportMark.FrameOnly : ExportMark.None
: Copied >= Due ? ExportMark.Copied : ExportMark.Partly;
}
/// <summary>Counts of the due files of an account (decision D3 of tappa E2).</summary>
+15 -4
View File
@@ -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))";
/// <summary>The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again.</summary>
/// <summary>
/// The last copy of the file in its effective destination failed («Non riuscito»), in any form but a frame: «Copia
/// in…» tries again.
/// </summary>
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')";
/// <summary>
/// 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.
/// </summary>
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')";
/// <summary>
/// «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})";
+86 -15
View File
@@ -826,6 +826,16 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
public Task<ExportItem?> 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);
/// <summary>The first item of a file of a job in a form (ux_export_item_file).</summary>
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<long?> 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<IReadOnlyList<ExportItem>> 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
""";
/// <summary>
/// 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.
/// </summary>
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
""";
/// <summary>The newest row of an original, any state and any form but a frame (@h, @d, @a).</summary>
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
""";
/// <summary>The «Non riuscito» rows of an original that a success leaves stale (@h, @d, @a; the kept identity @v, @f).</summary>
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";
/// <summary>The whole copies of a destination for some originals (ix_export_copy_sha256); @d and the list of SHA-256.</summary>
/// <summary>
/// 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.
/// </summary>
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'
""";
/// <summary>
@@ -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<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<long, bool>>(
@@ -948,16 +987,44 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
ct);
}
public Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default)
public Task<ExportCopy?> 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<IReadOnlyList<ExportCopy>> ListCurrentCopiesAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync<IReadOnlyList<ExportCopy>>(
c => ReadAll(c.Command(CurrentCopiesAnyFormSql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy),
ct);
}
public Task<ExportCopy?> 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<int> 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<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>> GetCopyStatesAsync(
long destinationId,
IReadOnlyCollection<(long AccountId, string Sha256)> keys,
@@ -968,8 +1035,9 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
return db.ReadAsync<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>(
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;
}
}
@@ -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<string>();
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),
};
+18 -7
View File
@@ -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]
@@ -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;
/// <summary>
/// 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.
/// </summary>
[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));
}
}
@@ -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);