using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
namespace Febe.Core.Library.Conversion;
/// What «Anche i N già in libreria» would queue: files and the bytes of their originals («circa», D17).
public sealed record LibraryConversionPreview(int Files, long Bytes);
///
/// The queue of the conversion for the library (tappa E3, D15, WP2.2): what enters it and when. A new file enters after
/// its line of _febe.jsonl (); the files already in the library
/// only when Alberto answers «Anche i N già in libreria» to the question asked when the conversion is turned on (Q29);
/// a format turned off or changed empties its queue, the converted files stay where they are.
///
public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
{
/// «In pausa» (1): the worker converts nothing until it is resumed.
public const string PausedKey = "esportazione.libreria-sospesa";
///
/// Since when (Unix milliseconds) the library format of photos is the one set now: «Solo i nuovi» means the files
/// stored in the library from then on (), the others only with «Anche i N».
///
public const string PhotoSinceKey = "esportazione.libreria-formato-foto-dal";
/// As , for videos.
public const string VideoSinceKey = "esportazione.libreria-formato-video-dal";
private static readonly Lock SignalGate = new();
private static TaskCompletionSource _signal = NewSignal();
/// The files «Anche i N già in libreria» would queue for the library formats of .
public Task PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
return PreviewExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
}
///
/// The files «Anche i N già in libreria» would queue in these formats, one per kind (null: that kind is not asked
/// about, as when only the other one is being turned on).
///
public async Task PreviewExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
{
var (files, bytes) = await storage.Conversions.CountExistingAsync(photo, video, ct).ConfigureAwait(false);
return new LibraryConversionPreview(files, bytes);
}
/// «Anche i N già in libreria» for both library formats of . Returns how many.
public Task EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
return EnqueueExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
}
///
/// «Anche i N già in libreria»: queues the present files that convert, in one statement per kind, only for the kinds
/// given (null: that kind keeps what was answered for it, «Solo i nuovi» included). Returns how many.
///
public async Task EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
{
var added = await storage.Conversions.EnqueueExistingAsync(photo, video, clock.Now, ct).ConfigureAwait(false);
if (added > 0)
{
Signal();
}
return added;
}
///
/// Saves the settings (they were ) with what a change of a library
/// format brings, in one transaction: the format, since when it is set () and the
/// emptied queue of the format it replaces. A request aborted, a crash or a file stored at that moment never sees
/// the new format without its «dal» key, nor the old failures left behind (D17, Q29).
/// Turning one on queues nothing here: the interface asks, then calls only for
/// «Anche i N già in libreria».
///
public Task SaveSettingsAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
var values = after.Values();
var (since, formats) = Changes(before, after);
foreach (var (key, value) in since)
{
values[key] = value;
}
return storage.Conversions.SaveSettingsAndDeleteQueuesAsync(values, formats, ct);
}
///
/// The settings were saved by another way: a library format turned off or changed loses its queue and its failures
/// that «Riprova» would put back (its converted files and rows stay), and its «dal» key is set, in one transaction.
/// stores the settings with them.
///
public Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
var (since, formats) = Changes(before, after);
return since.Count == 0 ? Task.CompletedTask : storage.Conversions.SaveSettingsAndDeleteQueuesAsync(since, formats, ct);
}
///
/// For each kind whose library format changes: its «dal» key (now, or removed when it goes back to «Originale») and
/// the format replaced, whose queue goes.
///
private (Dictionary Since, List Formats) Changes(ExportSettings before, ExportSettings after)
{
var since = new Dictionary(StringComparer.Ordinal);
var formats = new List();
foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video })
{
var old = LibraryConversionRules.FormatFor(kind, before);
var now = LibraryConversionRules.FormatFor(kind, after);
if (old == now)
{
continue;
}
if (old is { } format)
{
formats.Add(format);
}
// The files of the library before now are «già in libreria»: only «Anche i N» queues them.
since[SinceKey(kind)] = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
}
return (since, formats);
}
///
/// «Riprova»: the failed files of the library formats set now go back to the queue, except those that never convert
/// (AsIs*). Returns how many.
///
public async Task RetryFailedAsync(CancellationToken ct = default)
{
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var formats = new[] { MediaKind.Photo, MediaKind.Video }
.Select(kind => LibraryConversionRules.FormatFor(kind, settings))
.OfType()
.ToList();
var reset = await storage.Conversions.ResetFailedAsync(formats, clock.Now, ct).ConfigureAwait(false);
if (reset > 0)
{
Signal();
}
return reset;
}
/// «In pausa» or not.
public static async Task IsPausedAsync(ISettingsStore settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
return await settings.GetAsync(PausedKey, ct).ConfigureAwait(false) == "1";
}
/// «Sospendi» / «Riprendi» the conversion for the library.
public async Task SetPausedAsync(bool paused, CancellationToken ct = default)
{
await storage.Settings.SetAsync(PausedKey, paused ? "1" : "0", ct).ConfigureAwait(false);
if (!paused)
{
Signal();
}
}
///
/// Queues the new files of an entry by the library formats set now, after its journal line (the hook of
/// ): those stored in the library since the format was set (),
/// not the files an old entry already had when a late one arrives (they had their answer, «Solo i nuovi» included).
/// Nothing when both formats are «Originale». Returns how many rows were added.
///
public static async Task EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList media, DateTimeOffset at, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(media);
// One read: the formats and their «dal» keys as one change stored them, never a format with an older key.
var values = await storage.Settings.GetAllAsync(ct).ConfigureAwait(false);
var settings = ExportSettings.From(values);
if (!settings.ConvertsLibrary)
{
return 0;
}
var photoSince = Since(values, MediaKind.Photo);
var videoSince = Since(values, MediaKind.Video);
var requests = LibraryConversionRules.RequestsFor(
media.Where(m => (m.Kind == MediaKind.Video ? videoSince : photoSince) is not { } since
|| (m.DownloadedAt is { } stored && stored.ToUnixTimeMilliseconds() >= since)),
settings);
if (requests.Count == 0)
{
return 0;
}
var added = await storage.Conversions.EnqueueAsync(requests, at, ct).ConfigureAwait(false);
if (added > 0)
{
Signal();
}
return added;
}
private static string SinceKey(MediaKind kind) => kind == MediaKind.Video ? VideoSinceKey : PhotoSinceKey;
/// Since when the library format of this kind is set (Unix ms); null: not recorded, every file is new.
private static long? Since(IReadOnlyDictionary values, MediaKind kind) =>
long.TryParse(values.GetValueOrDefault(SinceKey(kind)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null;
/// Wakes the worker: something entered the queue (or the pause ended).
public static void Signal()
{
TaskCompletionSource fired;
lock (SignalGate)
{
fired = _signal;
_signal = NewSignal();
}
fired.TrySetResult();
}
/// A task that completes at the next .
internal static Task NextSignal()
{
lock (SignalGate)
{
return _signal.Task;
}
}
private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
}