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

+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>