using System.Runtime.CompilerServices; using Febe.Core.Domain; using Febe.Core.Storage; namespace Febe.Core.Export; /// /// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the /// effective destination of its account; a file already copied there, in any form but a frame, is «già copiato» /// (decision D3 of tappa E3); «Tolti» and «Superati» are skipped unless «Copia di nuovo» was asked. The format of each /// file is resolved and predicted from its name (D1, «circa»); a frames job plans one frame per instant of each due /// video. The only look at a destination is whether it answers, for the dialog. /// public sealed class ExportPlanner(ExportEnvironment env) { private const int PageSize = 2000; private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); /// The plan of a request, for the «Copia in…» dialog. /// The request is not valid (Italian message). public async Task PlanAsync(ExportJobRequest request, CancellationToken ct) { ArgumentNullException.ThrowIfNull(request); Validate(request); var destinations = new ExportDestinations(_env); var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false); var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); var tally = new PlanTally(); await foreach (var file in EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false)) { tally.Add(file); } return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false); } /// The checks of a request (tappa E3, WP1.1), with Italian messages. /// What is wrong. public static void Validate(ExportJobRequest request) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Selection, nameof(request)); if (request.Frames is not null && request.Formats is not null) { throw new ArgumentException("I fotogrammi non si chiedono insieme ai formati delle copie.", nameof(request)); } if (request.Exact is { } exact) { if (request.Selection is not ExportSelection.Media { MediaIds.Count: 1 }) { throw new ArgumentException("«Copia di nuovo» di una copia vale per un file solo.", nameof(request)); } if (request.Frames is not null || request.Formats is not null) { throw new ArgumentException("«Copia di nuovo» di una copia rifà la sua forma: niente altri formati né fotogrammi.", nameof(request)); } var valid = exact.Variant switch { ExportVariant.Whole => exact.Format == ExportFormat.Original && exact.FrameAt is null, ExportVariant.Converted => exact.Format != ExportFormat.Original && exact.FrameAt is null, ExportVariant.Frame => IsFrameFormat(exact.Format) && exact.FrameAt is { } at && at >= TimeSpan.Zero, _ => false, }; if (!valid) { throw new ArgumentException("La forma della copia da rifare non è valida.", nameof(request)); } } if (request.Formats is { } formats) { if (formats.Photo is { } photo && !ExportFormats.IsPhotoFormat(photo)) { throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(request)); } if (formats.Video is { } video && !ExportFormats.IsVideoFormat(video)) { throw new ArgumentException("Per i video si sceglie Originale o MP4.", nameof(request)); } } if (request.Frames is { } frames) { if (!IsFrameFormat(frames.Format)) { throw new ArgumentException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.", nameof(request)); } switch (frames.Mode) { case FrameMode.At when frames.At is not { } at || at < TimeSpan.Zero: throw new ArgumentException("Scegli l'istante del fotogramma.", nameof(request)); case FrameMode.Every when frames.Every is not { } every || every < ExportFrames.MinEvery: throw new ArgumentException("L'intervallo minimo è 0,1 secondi.", nameof(request)); case FrameMode.Count when frames.Count is not ({ } count and >= 1 and <= ExportFrames.MaxCount): throw new ArgumentException("Da 1 a 1.000 fotogrammi.", nameof(request)); case FrameMode.At or FrameMode.Every or FrameMode.Count: break; default: throw new ArgumentException("Modo dei fotogrammi sconosciuto.", nameof(request)); } } } /// JPG, PNG or WEBP senza perdita: the formats of a frame. internal static bool IsFrameFormat(ExportFormat format) => format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless; /// /// Every candidate of the request with what to do with it, in media id order (a frames job: one planned file per /// instant of each video, in instant order). Within one plan the same file of an account in one destination counts /// once (a story and its highlight entry, two files with the same bytes); with «Una copia sola» the same file counts /// once across accounts. /// internal async IAsyncEnumerable EnumerateAsync( ExportJobRequest request, IReadOnlyDictionary effective, 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)>(); 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; var keys = new Dictionary>(); foreach (var c in page) { if (Due(c, effective) is { } destination) { if (!keys.TryGetValue(destination, out var set)) { keys[destination] = set = []; } set.Add((c.AccountId, c.Sha256!)); } } var states = new Dictionary>(); if (request.Exact is null) { foreach (var (destination, set) in keys) { states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false); } } foreach (var c in page) { if (!IsPresent(c)) { yield return new PlannedFile(c, null, PlannedCopy.Missing); continue; } if (Due(c, effective) is not { } destination) { yield return new PlannedFile(c, null, PlannedCopy.NotExported); continue; } var sha = c.Sha256!; var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha); 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 = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied }; } else if (state is ExportCopyState.Removed or ExportCopyState.Superseded) { planned = request.CopyAgain ? form with { DestinationId = destination, Action = PlannedCopy.Write, Again = true } : form with { DestinationId = destination, Action = PlannedCopy.RemovedOrSuperseded }; } else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, c.AccountId, ct).ConfigureAwait(false) is not null) { planned = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied }; } else { planned = form with { DestinationId = destination, Action = PlannedCopy.Write }; } if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key)) { planned = planned with { Action = PlannedCopy.AlreadyCopied, Again = false }; } yield return planned; } } } /// /// A frames job (D12, D14 of tappa E3): photos are skipped, videos not due are counted as in «Copia in…», each due /// video gives one planned frame per instant of the request. A video of unknown length gives one planned file /// without an instant (): its instants are found when the job is recorded. /// Frames are not checked for «già copiato» here: the copy looks at each one's exact instant. /// private async IAsyncEnumerable EnumerateFramesAsync( ExportJobRequest request, ExportFramesRequest frames, IReadOnlyDictionary effective, [EnumeratorCancellation] CancellationToken ct) { var exports = _env.Storage.Exports; var seen = new HashSet<(long Destination, long Account, string Sha256, long Ticks, ExportFormat Format)>(); long after = 0; while (true) { var page = await exports.ListCandidatesAsync(request.Selection, after, PageSize, ct).ConfigureAwait(false); if (page.Count == 0) { yield break; } after = page[^1].MediaId; foreach (var c in page) { if (!IsPresent(c)) { yield return new PlannedFile(c, null, PlannedCopy.Missing); continue; } if (c.MediaKind != MediaKind.Video) { yield return new PlannedFile(c, null, PlannedCopy.PhotoSkipped); continue; } if (Due(c, effective) is not { } destination) { yield return new PlannedFile(c, null, PlannedCopy.NotExported); continue; } var frame = new PlannedFile(c, destination, PlannedCopy.Write) { Variant = ExportVariant.Frame, Format = frames.Format, Prediction = ExportPrediction.Converted, FirstOfVideo = true, }; if (frames.Mode != FrameMode.At && c.Duration is not { } known) { yield return frame with { UnknownDuration = true }; continue; } var duration = c.Duration ?? TimeSpan.Zero; if (ExportFrames.FrameCount(duration, frames) > ExportFrames.MaxPerVideo) { yield return frame with { Action = PlannedCopy.OverCap }; continue; } var first = true; foreach (var at in ExportFrames.Instants(duration, frames)) { var planned = frame with { FrameAt = at, FirstOfVideo = first }; first = false; if (!seen.Add((destination, c.AccountId, c.Sha256!, at.Ticks, frames.Format))) { planned = planned with { Action = PlannedCopy.AlreadyCopied }; } yield return planned; } } } } /// The form a file is asked in (D1, D2): the request's identity, and what its name predicts. private static PlannedFile Form(ExportCandidate c, ExportJobRequest request, ExportDestination destination, ExportSettings settings) { if (request.Exact is { } exact) { var prediction = exact.Variant == ExportVariant.Whole ? ExportPrediction.Whole : ExportConversions.Predict(c.RelativePath!, c.MediaKind, exact.Format); return new PlannedFile(c, null, PlannedCopy.Write) { Variant = exact.Variant, Format = exact.Format, FrameAt = exact.FrameAt, Prediction = exact.Variant == ExportVariant.Frame ? ExportPrediction.Converted : prediction, }; } var target = ExportConversions.Resolve(c.MediaKind, request.Formats, destination, settings); return new PlannedFile(c, null, PlannedCopy.Write) { Variant = ExportConversions.VariantOf(target), Format = target, Prediction = ExportConversions.Predict(c.RelativePath!, c.MediaKind, target), }; } /// A file present in the library, with its SHA-256 and path. internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath); /// The destination a present file goes to (D3), or null when it is not exported. private static long? Due(ExportCandidate c, IReadOnlyDictionary effective) => IsPresent(c) && effective.TryGetValue(c.AccountId, out var e) && e.Wants(ExportPaths.TypeOf(c.EntryKind, c.MediaKind, c.InHighlight)) ? e.Destination!.Id : null; } /// A candidate with what the plan does with it. /// Where it goes; null when not exported or missing. /// Written although «Tolto» or «Superato», because «Copia di nuovo» was asked. internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false) { /// The variant asked (the request, D2 of tappa E3): Whole, Converted or Frame. public ExportVariant Variant { get; init; } = ExportVariant.Whole; /// The format asked. public ExportFormat Format { get; init; } = ExportFormat.Original; /// The instant asked of a frame. public TimeSpan? FrameAt { get; init; } /// What the name predicts («circa»). public ExportPrediction Prediction { get; init; } = ExportPrediction.Whole; /// Frames job: the first planned file of its video (the videos are counted on it). public bool FirstOfVideo { get; init; } /// Frames job: a video of unknown length, without instants yet («circa» one frame). public bool UnknownDuration { get; init; } } internal enum PlannedCopy { Write, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, /// Frames job: a photo of the selection. PhotoSkipped, /// Frames job: a video over frames. OverCap, } /// Counts of a plan while its files go by. internal sealed class PlanTally { private readonly Dictionary _byDestination = []; private readonly Dictionary _asIs = new(StringComparer.Ordinal); public int Files { get; private set; } public long Bytes { get; private set; } public int AlreadyCopied { get; private set; } public int RemovedOrSuperseded { get; private set; } public int NotExported { get; private set; } 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: Missing++; return; case PlannedCopy.NotExported: NotExported++; return; case PlannedCopy.PhotoSkipped: PhotosSkipped++; return; case PlannedCopy.OverCap: OverCap++; Videos++; return; case PlannedCopy.AlreadyCopied: AlreadyCopied++; break; case PlannedCopy.RemovedOrSuperseded: RemovedOrSuperseded++; break; case PlannedCopy.Write: var frame = file.Variant == ExportVariant.Frame; var bytes = frame ? 0 : file.Candidate.Bytes ?? 0; Files++; Bytes += bytes; if (file.Again) { 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; } _byDestination.TryAdd(file.DestinationId!.Value, (0, 0)); } /// The plan. With each destination is asked whether it answers now. public async Task BuildAsync( ExportEnvironment env, ExportDestinations destinations, IReadOnlyDictionary effective, bool checkDestinations, CancellationToken ct) { var rows = effective.Values.Where(e => e.Destination is not null).Select(e => e.Destination!).DistinctBy(d => d.Id).ToDictionary(d => d.Id); var accounts = (await env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); var list = new List(); foreach (var (id, (files, bytes)) in _byDestination.OrderBy(d => rows.TryGetValue(d.Key, out var r) && r.Scope == ExportScope.General ? 0 : 1).ThenBy(d => d.Key)) { var d = rows.TryGetValue(id, out var row) ? row : await env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false); if (d is null) { continue; } string? problem = null; long? free = null; if (checkDestinations) { var status = await destinations.StatusAsync(id, ct).ConfigureAwait(false); problem = status.Problem; free = status.FreeBytes; } problem ??= d.PausedAt is not null ? d.LastError : null; var username = d.AccountId is { } a ? accounts.GetValueOrDefault(a) : null; list.Add(new ExportPlanDestination(d.Id, ExportDestinations.Label(d), d.RootPath, d.Scope, username, files, bytes, d.PausedAt is not null, problem, free)); } 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) { AsIs = _asIs.OrderByDescending(p => p.Value).ThenBy(p => p.Key, StringComparer.Ordinal).Select(p => new ExportPlanAsIs(p.Key, p.Value)).ToList(), Converted = Converted, Lossy = Lossy, Videos = Videos, PhotosSkipped = PhotosSkipped, Frames = Frames, OverCap = OverCap, }; } /// Destinations that get a run: those with files to write, already copied, or «tolti o superati». public IReadOnlyCollection Destinations => _byDestination.Keys; }