E3: conversione della libreria in sottofondo con righe sempre vere

La libreria può ora tenere accanto a ogni originale una copia nel
formato scelto, preparata in sottofondo senza mai sostituire o
cancellare l'originale.

- LongWorkGate ha un permesso di sottofondo che il lavoro in primo
  piano (importazione, copie, ricostruzione) interrompe; il
  salvataggio in corso si aspetta al più CommitWait.
- La coda e il lavoratore: nuovi file accodati all'arrivo, quelli già
  in libreria solo su richiesta, pausa, nuovo tentativo, attesa
  durante una sessione del motore o con poco spazio, nomi liberi e
  adozione di un file identico già presente.
- Le righe di media_conversion restano vere in ogni via: eliminazione
  (Ricorda e Consenti il ritorno, con RemoveWithConversionsAsync per
  il vincolo RESTRICT), perdente del ripasso dei doppioni, file
  cambiato (superate e riaccodate), ricostruzione (conta e riconosce
  i convertiti, accoda solo Pending), importazione (una copia
  convertita o un fotogramma non rientra come file nuovo).
- FebeApp avvia il lavoratore con InBackground; la demo mai.
  _febe.jsonl non cambia.

La prova RecordsCannotBeDeletedFromUnderTheirCopies usa ora una riga
Converted: RemoveAsync toglie da sé le righe senza file, e il vincolo
si verifica sia in SQL sia attraverso il magazzino.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 23:57:48 +01:00
1 parent b746aff45d
commit 724c5bda6f
25 files changed
+2621 -38

No files matched your search

@@ -0,0 +1,148 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
namespace Febe.Core.Library.Conversion;
/// <summary>What «Anche i N già in libreria» would queue: files and the bytes of their originals («circa», D17).</summary>
public sealed record LibraryConversionPreview(int Files, long Bytes);
/// <summary>
/// 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 <c>_febe.jsonl</c> (<see cref="LibraryIngest.AppendJournalAsync"/>); 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.
/// </summary>
public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
{
/// <summary>«In pausa» (<c>1</c>): the worker converts nothing until it is resumed.</summary>
public const string PausedKey = "esportazione.libreria-sospesa";
private static readonly Lock SignalGate = new();
private static TaskCompletionSource _signal = NewSignal();
/// <summary>The files «Anche i N già in libreria» would queue for the library formats of <paramref name="settings"/>.</summary>
public async Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
var (files, bytes) = await storage.Conversions.CountExistingAsync(
LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct).ConfigureAwait(false);
return new LibraryConversionPreview(files, bytes);
}
/// <summary>«Anche i N già in libreria»: queues the present files that convert, in one statement per kind. Returns how many.</summary>
public async Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
var added = await storage.Conversions.EnqueueExistingAsync(
LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), clock.Now, ct).ConfigureAwait(false);
if (added > 0)
{
Signal();
}
return added;
}
/// <summary>
/// The settings changed: a library format turned off or changed loses its queue (its converted files and rows stay).
/// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for
/// «Anche i N già in libreria».
/// </summary>
public async Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video })
{
var old = LibraryConversionRules.FormatFor(kind, before);
if (old is { } format && old != LibraryConversionRules.FormatFor(kind, after))
{
await storage.Conversions.DeletePendingAsync(format, ct).ConfigureAwait(false);
}
}
}
/// <summary>«Riprova»: the failed files go back to the queue, except those that never convert (<c>AsIs*</c>). Returns how many.</summary>
public async Task<int> RetryFailedAsync(CancellationToken ct = default)
{
var reset = await storage.Conversions.ResetFailedAsync(clock.Now, ct).ConfigureAwait(false);
if (reset > 0)
{
Signal();
}
return reset;
}
/// <summary>«In pausa» or not.</summary>
public static async Task<bool> IsPausedAsync(ISettingsStore settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
return await settings.GetAsync(PausedKey, ct).ConfigureAwait(false) == "1";
}
/// <summary>«Sospendi» / «Riprendi» the conversion for the library.</summary>
public async Task SetPausedAsync(bool paused, CancellationToken ct = default)
{
await storage.Settings.SetAsync(PausedKey, paused ? "1" : "0", ct).ConfigureAwait(false);
if (!paused)
{
Signal();
}
}
/// <summary>
/// Queues the present files of an entry by the library formats set now, after its journal line (the hook of
/// <see cref="LibraryIngest"/>). Nothing when both formats are «Originale». Returns how many rows were added.
/// </summary>
public static async Task<int> EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList<Media> media, DateTimeOffset at, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(media);
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
if (!settings.ConvertsLibrary)
{
return 0;
}
var requests = LibraryConversionRules.RequestsFor(media, settings);
if (requests.Count == 0)
{
return 0;
}
var added = await storage.Conversions.EnqueueAsync(requests, at, ct).ConfigureAwait(false);
if (added > 0)
{
Signal();
}
return added;
}
/// <summary>Wakes the worker: something entered the queue (or the pause ended).</summary>
public static void Signal()
{
TaskCompletionSource fired;
lock (SignalGate)
{
fired = _signal;
_signal = NewSignal();
}
fired.TrySetResult();
}
/// <summary>A task that completes at the next <see cref="Signal"/>.</summary>
internal static Task NextSignal()
{
lock (SignalGate)
{
return _signal.Task;
}
}
private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
}
@@ -0,0 +1,66 @@
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
namespace Febe.Core.Library.Conversion;
/// <summary>
/// Which library files the conversion for the library queues (tappa E3, D15, WP2.2): a present file whose extension
/// says it converts into the format chosen for its kind (<see cref="ExportConversions.Predict"/> is Converted). A file
/// already in that format, HEIC, HEIF, AVIF, raw, GIF and WebM are never queued. The same rule is written in SQL by the
/// store (<see cref="ExcludedExtensions"/>).
/// </summary>
public static class LibraryConversionRules
{
/// <summary>The format of the conversion for the library of a kind; null when it is off («Originale»).</summary>
public static ExportFormat? FormatFor(MediaKind kind, ExportSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
var format = kind == MediaKind.Photo ? settings.LibraryPhotoFormat : settings.LibraryVideoFormat;
var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format);
return format != ExportFormat.Original && fits ? format : null;
}
/// <summary>True when a file at <paramref name="relativePath"/> of <paramref name="kind"/> is queued for <paramref name="format"/>.</summary>
public static bool Converts(string relativePath, MediaKind kind, ExportFormat format)
{
ArgumentNullException.ThrowIfNull(relativePath);
var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format);
return format != ExportFormat.Original && fits && ExportConversions.Predict(relativePath, kind, format) == ExportPrediction.Converted;
}
/// <summary>
/// The extensions (with their dot, lower case) of the files that are not queued for <paramref name="format"/>: the
/// format's own and the ones copied as they are. Equivalent to <see cref="Converts"/> on the extension.
/// </summary>
public static IReadOnlyList<string> ExcludedExtensions(ExportFormat format)
{
var own = format switch
{
ExportFormat.Jpg => new[] { ".jpg", ".jpeg" },
ExportFormat.Png => [".png"],
ExportFormat.WebpLossless => [".webp"],
ExportFormat.Mp4 => [".mp4"],
_ => throw new ArgumentOutOfRangeException(nameof(format), "La conversione della libreria ha un formato diverso dall'originale."),
};
return [.. own, ".heic", ".heif", ".avif", ".gif", ".webm", .. MediaConverter.RawExtensionList.Select(e => e.ToLowerInvariant()).Order(StringComparer.Ordinal)];
}
/// <summary>The conversions to queue for the present files of an entry, by the settings now.</summary>
public static IReadOnlyList<MediaConversionRequest> RequestsFor(IEnumerable<Media> media, ExportSettings settings)
{
ArgumentNullException.ThrowIfNull(media);
ArgumentNullException.ThrowIfNull(settings);
var list = new List<MediaConversionRequest>();
foreach (var m in media)
{
if (EntryStateRules.IsPresent(m.State) && m.Sha256 is { Length: 64 } sha && m.RelativePath is { } path
&& FormatFor(m.Kind, settings) is { } format && Converts(path, m.Kind, format))
{
list.Add(new MediaConversionRequest(m.Id, format, sha));
}
}
return list;
}
}
@@ -0,0 +1,72 @@
using Febe.Core.Codecs.Images;
using Febe.Core.Export;
namespace Febe.Core.Library.Conversion;
/// <summary>
/// The codes of <c>media_conversion.last_error</c> (tappa E3, D19) and their Italian texts. A Failed row carries why it
/// failed (an <c>AsIs*</c> code first when the file never converts); a Converted row carries what was not kept.
/// </summary>
public static class LibraryConversionText
{
/// <summary>The original is not in the library folder.</summary>
public const string SourceMissing = ExportText.Notes.SourceMissing;
/// <summary>The original's bytes are not the ones recorded.</summary>
public const string SourceChanged = ExportText.Notes.SourceChanged;
/// <summary>The account folder is not there (an unplugged disk): it is never created.</summary>
public const string AccountFolderMissing = "AccountFolderMissing";
/// <summary>The prefix of an unexpected failure; the exception's type name follows the colon.</summary>
public const string Error = "Error";
/// <summary>The prefix of the codes of files that never convert.</summary>
public const string AsIsPrefix = "AsIs";
/// <summary>«In pausa» for low space (D17).</summary>
public const string LowSpace = "Spazio libero sotto la soglia: la conversione della libreria è in pausa";
/// <summary>Waiting for the end of an engine session.</summary>
public const string InSession = "Il motore è in sessione: la conversione della libreria riprende dopo";
/// <summary>Waiting for an import, a copy or a rebuild.</summary>
public const string LongWork = "Un'importazione, una copia o una ricostruzione è al lavoro: la conversione della libreria riprende dopo";
/// <summary>True when the codes of a Failed row say the file never converts.</summary>
public static bool IsAsIs(string? codes) => codes is not null && codes.TrimStart().StartsWith(AsIsPrefix, StringComparison.Ordinal);
/// <summary>The Italian text of a list of codes («·» between them); unknown codes are shown as they are.</summary>
public static string? Note(string? codes)
{
if (string.IsNullOrWhiteSpace(codes))
{
return null;
}
return string.Join(" · ", codes.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(One));
}
private static string One(string code)
{
var colon = code.IndexOf(':', StringComparison.Ordinal);
var name = colon < 0 ? code : code[..colon];
return name switch
{
SourceMissing => "File non presente in libreria",
SourceChanged => "Il file della libreria non è quello registrato",
AccountFolderMissing => "La cartella dell'account non c'è: ricollega il disco e riprova",
Error => "Conversione non riuscita: riprova",
ImageConversionLosses.AsIsHeif => "Non si converte: HEIC",
ImageConversionLosses.AsIsAvif => "Non si converte: AVIF",
ImageConversionLosses.AsIsRaw => "Non si converte: raw",
ImageConversionLosses.AsIsAnimated => "Non si converte: immagine animata (perderebbe i fotogrammi dopo il primo)",
ImageConversionLosses.AsIsNotDecodable => "Non si converte: Febe non riesce a leggere l'immagine",
ImageConversionLosses.AsIsDeepColor => "Non si converte: più di 8 bit per colore",
ImageConversionLosses.AsIsCmyk => "Non si converte: immagine CMYK",
ImageConversionLosses.AsIsTooLarge => "Non si converte: troppo grande per il formato scelto",
MediaConversionResult.AsIsNotRemuxable => "Non si porta in MP4 senza ricodificarlo" + (ExportText.Note(code) is { } t && t.IndexOf('(', StringComparison.Ordinal) is var i and >= 0 ? " " + t[i..] : string.Empty),
_ => ExportText.Note(code) ?? code,
};
}
}
@@ -0,0 +1,532 @@
using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
namespace Febe.Core.Library.Conversion;
/// <summary>What the conversion for the library needs from the rest of Febe (tappa E3, WP2.2).</summary>
public sealed record LibraryConversionEnvironment
{
public required IFebeStorage Storage { get; init; }
/// <summary>The library folder and account folders now (on Windows it can change while Febe runs).</summary>
public required Func<LibraryLayout> Layout { get; init; }
public required IClock Clock { get; init; }
/// <summary>Shared with import, export, rebuild and frame download, which pre-empt the conversion. Null: nothing to yield to (tests).</summary>
public LongWorkGate? Gate { get; init; }
/// <summary>The conversion never runs during an engine session.</summary>
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
/// <summary>One conversion at a time in the process (D16): shared with the copies to external folders.</summary>
public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
/// <summary>The free space of the disk of an account folder.</summary>
public IFreeSpaceProbe FreeSpace { get; init; } = new DriveFreeSpaceProbe();
/// <summary>Below this, once the file is written, the conversion pauses (D17): the alerts' «quasi pieno».</summary>
public DiskThresholds Thresholds { get; init; } = DiskThresholds.Default;
/// <summary>How long the worker sleeps when nothing wakes it.</summary>
public TimeSpan Idle { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>How often it looks again while it waits for an engine session or a long work to end.</summary>
public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>Rows read from the queue at a time.</summary>
public int BatchSize { get; init; } = 50;
/// <summary>One line for the log: only Italian text and exception type names, never paths or messages.</summary>
public Action<string>? Log { get; init; }
/// <summary>Test seam: runs once the converted file is on disk, before its record.</summary>
public Func<MediaConversion, CancellationToken, Task>? AfterWrite { get; init; }
}
/// <summary>The conversion for the library as the interface shows it.</summary>
/// <param name="Pending">Files in the queue.</param>
/// <param name="Converted">Files converted.</param>
/// <param name="Failed">Files that failed and can be tried again («Riprova»).</param>
/// <param name="AsIs">Files that never convert («non si convertono»).</param>
/// <param name="Paused">«In pausa» by Alberto.</param>
/// <param name="Waiting">Why it waits now (an engine session, a long work, low space), or null.</param>
/// <param name="CurrentMediaId">The library file being converted now, or null.</param>
public sealed record LibraryConversionStatus(int Pending, int Converted, int Failed, int AsIs, bool Paused, string? Waiting, long? CurrentMediaId);
/// <summary>What one pass over the queue did.</summary>
/// <param name="Converted">Files converted (or adopted).</param>
/// <param name="Done">Rows settled: converted, dropped (already in the format), failed.</param>
/// <param name="Again">True when the pass stopped early and should look again soon (session, long work, pre-emption).</param>
public sealed record LibraryConversionPass(int Converted, int Done, bool Again);
/// <summary>
/// The conversion for the library (tappa E3, spec §4.10, D15-D18): adds, next to an original, the same file in the
/// format chosen for its kind, as a new file with the same stem and a free name. The original, its record, its
/// thumbnail, perceptual hash and journal line stay as they are; the converted file is only a <c>media_conversion</c>
/// row. It runs in the background through <see cref="RunAsync"/> (started by the composition, never in the demo),
/// yields to import, export, rebuild and frame download (<see cref="LongWorkGate.BackgroundLease"/>), never runs during
/// an engine session and pauses when the disk is almost full.
/// </summary>
public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
{
private readonly LibraryConversionEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
private volatile string? _waiting;
private long _current;
/// <summary>The counts of the store with what the worker is doing now.</summary>
public async Task<LibraryConversionStatus> StatusAsync(CancellationToken ct = default)
{
var counts = await _env.Storage.Conversions.CountByStateAsync(ct).ConfigureAwait(false);
var paused = await LibraryConversionQueue.IsPausedAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
var current = Interlocked.Read(ref _current);
return new LibraryConversionStatus(counts.Pending, counts.Converted, counts.Failed, counts.AsIs, paused, paused ? null : _waiting, current == 0 ? null : current);
}
/// <summary>
/// The loop: a pass over the queue, then a wait for <see cref="LibraryConversionQueue.Signal"/> or
/// <see cref="LibraryConversionEnvironment.Idle"/>. A failure of a pass is logged by type and the loop goes on; it
/// ends with <paramref name="ct"/>.
/// </summary>
public async Task RunAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
var wait = _env.Idle;
try
{
var pass = await RunOnceAsync(ct).ConfigureAwait(false);
if (pass.Again)
{
wait = _env.Poll;
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
_env.Log?.Invoke($"La conversione della libreria si è fermata per un errore ({ex.GetType().Name}): riprova fra poco.");
}
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
var signal = LibraryConversionQueue.NextSignal();
var delay = _env.Clock.Delay(wait, stop.Token);
await Task.WhenAny(signal, delay).ConfigureAwait(false);
await stop.CancelAsync().ConfigureAwait(false);
}
}
/// <summary>One pass over the queue, in order, until it is empty or something stops it.</summary>
public async Task<LibraryConversionPass> RunOnceAsync(CancellationToken ct = default)
{
var storage = _env.Storage;
if (await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false))
{
_waiting = null;
return new LibraryConversionPass(0, 0, false);
}
if (_env.Session.InSession)
{
_waiting = LibraryConversionText.InSession;
return new LibraryConversionPass(0, 0, true);
}
if ((await storage.Conversions.ListPendingAsync(0, 1, ct).ConfigureAwait(false)).Count == 0)
{
_waiting = null;
return new LibraryConversionPass(0, 0, false);
}
LongWorkGate.BackgroundLease? lease = null;
if (_env.Gate is { } gate && !gate.TryEnterBackground(out lease))
{
_waiting = LibraryConversionText.LongWork;
return new LibraryConversionPass(0, 0, true);
}
using (lease)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease?.Preempted ?? CancellationToken.None);
var token = linked.Token;
_waiting = null;
var converted = 0;
var done = 0;
var after = 0L;
while (true)
{
var rows = await storage.Conversions.ListPendingAsync(after, _env.BatchSize, ct).ConfigureAwait(false);
if (rows.Count == 0)
{
return new LibraryConversionPass(converted, done, false);
}
foreach (var row in rows)
{
after = row.Id;
if (token.IsCancellationRequested || _env.Session.InSession
|| await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false))
{
ct.ThrowIfCancellationRequested();
return new LibraryConversionPass(converted, done, true);
}
var outcome = await ConvertOneAsync(row, lease, token, ct).ConfigureAwait(false);
switch (outcome)
{
case Outcome.Converted:
converted++;
done++;
break;
case Outcome.Settled:
done++;
break;
case Outcome.LowSpace:
_waiting = LibraryConversionText.LowSpace;
return new LibraryConversionPass(converted, done, false);
case Outcome.Stopped:
ct.ThrowIfCancellationRequested();
return new LibraryConversionPass(converted, done, true);
}
}
}
}
}
private enum Outcome
{
Converted,
Settled,
Skipped,
LowSpace,
Stopped,
}
private async Task<Outcome> ConvertOneAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token, CancellationToken ct)
{
Interlocked.Exchange(ref _current, row.MediaId);
try
{
return await ConvertAsync(row, lease, token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
// Pre-empted, or Febe stops: our temporary file is gone, the row stays in the queue.
return Outcome.Stopped;
}
catch (Exception ex)
{
// One file never stops the queue: the reason goes to the row (codes, D19), the log gets the type only.
_env.Log?.Invoke($"Un file non si è convertito per la libreria ({ex.GetType().Name}).");
await FailAsync(row, $"{LibraryConversionText.Error}:{ex.GetType().Name}").ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
return Outcome.Settled;
}
finally
{
Interlocked.Exchange(ref _current, 0);
}
}
private async Task<Outcome> ConvertAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token)
{
var storage = _env.Storage;
var media = await storage.Media.GetAsync(row.MediaId, token).ConfigureAwait(false);
if (media is null || !EntryStateRules.IsPresent(media.State) || media.RelativePath is null || media.Sha256 is not { Length: 64 })
{
// Not in the library (deleted meanwhile, or never stored): nothing to convert.
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
return Outcome.Skipped;
}
var entry = await storage.Entries.GetAsync(media.EntryId, token).ConfigureAwait(false);
var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, token).ConfigureAwait(false);
if (entry is null || account is null)
{
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
return Outcome.Skipped;
}
var layout = _env.Layout();
var folder = layout.AccountFolder(account);
if (!Directory.Exists(folder))
{
// An unplugged disk of an account folder outside the library: never created again here.
await FailAsync(row, LibraryConversionText.AccountFolderMissing).ConfigureAwait(false);
return Outcome.Settled;
}
var original = LibraryLayout.FullPath(folder, media.RelativePath);
if (!File.Exists(original))
{
await FailAsync(row, LibraryConversionText.SourceMissing).ConfigureAwait(false);
return Outcome.Settled;
}
var source = media.Sha256.ToLowerInvariant();
if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal))
{
row = row with { SourceSha256 = source, StateChangedAt = _env.Clock.Now };
await storage.Conversions.UpdateAsync(row, CancellationToken.None).ConfigureAwait(false);
}
if (media.Kind == MediaKind.Video && !string.Equals(await HashAsync(original, token).ConfigureAwait(false), source, StringComparison.Ordinal))
{
// A remux reads the file in pieces: its bytes are checked first (a photo is checked by the converter).
await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false);
return Outcome.Settled;
}
MediaConversionResult result;
try
{
result = await MediaConverter.PrepareAsync(() => OpenRead(original), media.RelativePath, media.Kind, row.Format, source, _env.Throttle, token)
.ConfigureAwait(false);
}
catch (ContentChangedException)
{
await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false);
return Outcome.Settled;
}
using (result)
{
if (result.Variant == ExportVariant.Whole)
{
if (result.Notes.Count == 0)
{
// Already in the format by its bytes (a «.png» that is a JPEG, to JPG): there is no file to add.
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
}
else
{
// Animated, not decodable, CMYK, too large, not remuxable…: it never converts (terminal).
await FailAsync(row, ExportText.JoinNotes(result.Notes)).ConfigureAwait(false);
}
return Outcome.Settled;
}
if (_env.FreeSpace.Measure(folder) is { } space
&& _env.Thresholds.IsLow(space with { AvailableBytes = space.AvailableBytes - result.Length }))
{
return Outcome.LowSpace;
}
return await WriteAsync(row, media, entry, account, folder, layout, result, lease, token).ConfigureAwait(false);
}
}
private async Task<Outcome> WriteAsync(MediaConversion row, Media media, Entry entry, Account account, string folder, LibraryLayout layout,
MediaConversionResult result, LongWorkGate.BackgroundLease? lease, CancellationToken token)
{
var storage = _env.Storage;
var relative = LibraryLayout.ToStored(media.RelativePath!);
var slash = relative.LastIndexOf('/');
var directory = slash < 0 ? string.Empty : relative[..slash];
var stem = WindowsFileNames.SplitExtension(relative[(slash + 1)..]).Stem;
var setTime = await SetFileTimeAsync(token).ConfigureAwait(false);
FileDigest written = default;
string? adopted = null;
var preempted = false;
IDisposable? commit = null;
try
{
var writer = new SafeFileWriter(layout.MaxPathLength);
var saved = await writer.SaveAsync(
result.Produce,
folder,
directory,
async (digest, t) =>
{
written = digest;
adopted = await FindAdoptableAsync(account, folder, layout, directory, stem, result.Extension, digest, t).ConfigureAwait(false);
if (lease is not null && !lease.TryBeginCommit(out commit))
{
preempted = true;
return null;
}
return adopted is null ? Join(directory, stem + result.Extension) : null;
},
new SafeWriteOptions
{
RequireExistingRoot = true,
VerifyFromDisk = true,
LastWriteTime = setTime ? entry.PublishedAt : null,
},
token).ConfigureAwait(false);
if (preempted)
{
return Outcome.Stopped;
}
var path = adopted ?? saved!.RelativePath;
if (_env.AfterWrite is { } after)
{
await after(row, CancellationToken.None).ConfigureAwait(false);
}
MediaConversionCommitOutcome outcome;
try
{
outcome = await storage.Conversions.CommitAsync(
new MediaConversionCommit(row.Id, media.Id, row.Format, row.SourceSha256, path, written.Bytes, written.Sha256, _env.Clock.Now,
ExportText.JoinNotes(result.Notes)),
CancellationToken.None).ConfigureAwait(false);
}
catch when (adopted is null)
{
DiscardOwn(folder, path, written.Sha256);
throw;
}
if (outcome is MediaConversionCommitOutcome.Recorded or MediaConversionCommitOutcome.Upserted)
{
return Outcome.Converted;
}
if (adopted is null)
{
// The entry was deleted (or the original replaced) while the file was written: the file just written
// belongs to nothing. It is this operation's own file, never one of the library: it goes.
DiscardOwn(folder, path, written.Sha256);
}
return Outcome.Settled;
}
finally
{
commit?.Dispose();
}
}
/// <summary>
/// A file already at the path (or at one of its free names) with the conversion's SHA-256 that no library file and
/// no other conversion records: a conversion of an earlier run (or of a lost database) whose record is missing. Null
/// when there is none: the file is written with the next free name. Never by size alone (D10).
/// </summary>
private async Task<string?> FindAdoptableAsync(Account account, string folder, LibraryLayout layout, string directory, string stem, string extension,
FileDigest digest, CancellationToken ct)
{
for (var attempt = 1; attempt <= 50; attempt++)
{
var name = attempt == 1 ? stem + extension : string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
var segments = Join(directory, WindowsFileNames.SanitizeSegment(name)).Split('/', StringSplitOptions.RemoveEmptyEntries);
var relative = string.Join('/', WindowsFileNames.FitPath(folder, segments, layout.MaxPathLength));
string full;
try
{
full = LibraryLayout.FullPath(folder, relative);
}
catch (ArgumentException)
{
return null;
}
var info = new FileInfo(full);
if (!info.Exists)
{
return null;
}
if (info.Length == digest.Bytes
&& string.Equals(await HashAsync(full, ct).ConfigureAwait(false), digest.Sha256, StringComparison.Ordinal)
&& !await IsRecordedAsync(account, relative, digest.Sha256, ct).ConfigureAwait(false))
{
return relative;
}
}
return null;
}
/// <summary>A library file of the account, or a live conversion of one, records this path (another entry's «x.jpg»).</summary>
private async Task<bool> IsRecordedAsync(Account account, string relative, string sha, CancellationToken ct)
{
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
var media = await _env.Storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false);
if (media.Any(m => m.Entry.AccountId == account.Id && m.Media.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), relative, comparison)))
{
return true;
}
foreach (var conversion in await _env.Storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false))
{
if (conversion.State is MediaConversionState.Converted or MediaConversionState.Superseded
&& conversion.RelativePath is { } path && string.Equals(path, relative, comparison))
{
var owner = await _env.Storage.Media.GetAsync(conversion.MediaId, ct).ConfigureAwait(false);
var entry = owner is null ? null : await _env.Storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false);
if (entry?.AccountId == account.Id)
{
return true;
}
}
}
return false;
}
/// <summary>Deletes the file this conversion just wrote, only if it still has the bytes written (precedent: LibraryIngest).</summary>
private void DiscardOwn(string folder, string relative, string sha)
{
try
{
var full = LibraryLayout.FullPath(folder, relative);
if (File.Exists(full) && string.Equals(HashFile(full), sha, StringComparison.Ordinal))
{
File.Delete(full);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
_env.Log?.Invoke($"Un file convertito per un elemento eliminato non si è potuto togliere ({ex.GetType().Name}).");
}
}
private async Task FailAsync(MediaConversion row, string? codes)
{
try
{
await _env.Storage.Conversions.UpdateAsync(
row with { State = MediaConversionState.Failed, LastError = codes, StateChangedAt = _env.Clock.Now, RelativePath = null, Bytes = null, Sha256 = null, ConvertedAt = null },
CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is KeyNotFoundException or DuplicateRecordException)
{
// The row went or changed meanwhile (a deletion, the setting turned off): nothing to record.
}
}
private async Task<bool> SetFileTimeAsync(CancellationToken ct)
{
var text = await _env.Storage.Settings.GetAsync(SettingKeys.SetFileTimeToPublication, ct).ConfigureAwait(false);
return text is null || !bool.TryParse(text, out var parsed) || parsed;
}
private static string Join(string directory, string name) => directory.Length == 0 ? name : directory + "/" + name;
private static FileStream OpenRead(string path) =>
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess);
private static async Task<string> HashAsync(string path, CancellationToken ct)
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024,
FileOptions.Asynchronous | FileOptions.SequentialScan);
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
}
private static string HashFile(string path)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.SequentialScan);
return Convert.ToHexStringLower(SHA256.HashData(stream));
}
}
@@ -47,6 +47,9 @@ public static class MediaConverter
/// <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>The raw camera extensions (with their dot, lower case), for rules written in SQL.</summary>
public static IReadOnlyCollection<string> RawExtensionList => RawExtensions;
/// <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.
@@ -282,7 +282,15 @@ public sealed class DownloadDuplicateReview(
}
var folder = layout.AccountFolder(account);
// Its converted files of the library (tappa E3) go with it: the queue and the failures are dropped, the rows
// with a file become «Tolto». No supersession for the loser.
var conversions = await storage.Conversions.ListByMediaAsync(media.Id, ct).ConfigureAwait(false);
var withFiles = conversions
.Where(c => c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null)
.ToList();
await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false);
await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false);
await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false);
hashIndex?.Remove(media.Id);
var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList();
@@ -312,6 +320,14 @@ public sealed class DownloadDuplicateReview(
}
}
var failedConverted = new List<string>();
await LibraryDeletion.DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, [], [], failedConverted, ct).ConfigureAwait(false);
if (failedConverted.Count > 0)
{
var more = $"@{side.Username}, file convertiti: {string.Join("; ", failedConverted)}.";
problem = problem is null ? more : problem + " " + more;
}
if (thumbnails is not null && media.Sha256 is { } sha)
{
var users = await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false);
+95 -3
View File
@@ -31,6 +31,9 @@ public sealed record DeletionResult(
IReadOnlyList<string> FailedFiles)
{
public bool Complete => Found && FailedFiles.Count == 0;
/// <summary>Converted files of the library (tappa E3) deleted with the originals; they are in <see cref="DeletedFiles"/> too.</summary>
public int ConvertedFiles { get; init; }
}
/// <summary>
@@ -62,6 +65,9 @@ public sealed class LibraryDeletion(
var folder = layout.AccountFolder(account);
var present = stored.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList();
// The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
var conversions = await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
// From here the deletion goes to the end: a half-done deletion is worse than a late one.
@@ -69,13 +75,15 @@ public sealed class LibraryDeletion(
await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none)
.ConfigureAwait(false);
IReadOnlyList<MediaConversion> withFiles;
if (mode == DeletionMode.Remember)
{
await storage.Entries.MarkDeletedAsync(entryId, clock.Now, none).ConfigureAwait(false);
withFiles = conversions.Where(HasFile).ToList();
await storage.Entries.MarkDeletedAsync(entryId, clock.Now, withFiles.Select(c => c.Id).ToList(), none).ConfigureAwait(false);
}
else
{
await storage.Entries.RemoveAsync(entryId, none).ConfigureAwait(false);
withFiles = (await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false)).Where(HasFile).ToList();
}
foreach (var media in stored.Media)
@@ -108,6 +116,8 @@ public sealed class LibraryDeletion(
}
}
var converted = await DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, deleted, missing, failed, none).ConfigureAwait(false);
if (thumbnails is not null)
{
foreach (var sha in stored.Media.Select(m => m.Sha256).OfType<string>().Distinct(StringComparer.Ordinal))
@@ -127,7 +137,89 @@ public sealed class LibraryDeletion(
}
}
return new DeletionResult(entryId, true, deleted, missing, failed);
return new DeletionResult(entryId, true, deleted, missing, failed) { ConvertedFiles = converted };
}
/// <summary>A conversion whose file is (or was last known to be) on disk.</summary>
private static bool HasFile(MediaConversion c) =>
c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null;
/// <summary>
/// Deletes the converted files of conversions just removed or marked «Tolto», each only if no library file and no
/// live conversion still records its path and it still has the bytes recorded: a file replaced by Alberto stays and
/// is listed among the failures with its reason. Returns how many were deleted.
/// </summary>
internal static async Task<int> DeleteConvertedFilesAsync(IFebeStorage storage, long accountId, string folder, IReadOnlyList<MediaConversion> conversions,
List<string> deleted, List<string> missing, List<string> failed, CancellationToken ct)
{
var count = 0;
foreach (var conversion in conversions)
{
var relative = conversion.RelativePath!;
try
{
var path = LibraryLayout.FullPath(folder, relative);
if (!File.Exists(path))
{
missing.Add(relative);
continue;
}
if (await IsStillRecordedAsync(storage, accountId, conversion, ct).ConfigureAwait(false))
{
continue; // another file of the library has that name now: it is not this conversion's to delete
}
if (!string.Equals(HashFile(path), conversion.Sha256, StringComparison.OrdinalIgnoreCase))
{
failed.Add($"{relative}: il file convertito è cambiato dopo la conversione, quindi resta dov'è.");
continue;
}
File.Delete(path);
deleted.Add(relative);
count++;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
failed.Add($"{relative}: {ex.Message}");
}
}
return count;
}
private static async Task<bool> IsStillRecordedAsync(IFebeStorage storage, long accountId, MediaConversion conversion, CancellationToken ct)
{
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
var sha = conversion.Sha256!;
foreach (var m in await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false))
{
if (m.Entry.AccountId == accountId && EntryStateRules.IsPresent(m.Media.State) && m.Media.RelativePath is { } p
&& string.Equals(LibraryLayout.ToStored(p), conversion.RelativePath, comparison))
{
return true;
}
}
foreach (var other in await storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false))
{
if (other.Id != conversion.Id && other.State is MediaConversionState.Converted or MediaConversionState.Superseded
&& string.Equals(other.RelativePath, conversion.RelativePath, comparison)
&& await storage.Media.GetAsync(other.MediaId, ct).ConfigureAwait(false) is { } owner
&& (await storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false))?.AccountId == accountId)
{
return true;
}
}
return false;
}
private static string HashFile(string path)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, FileOptions.SequentialScan);
return Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(stream));
}
/// <summary>Multiple selection: deletes each entry in turn.</summary>
+4
View File
@@ -3,6 +3,7 @@ using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library.Conversion;
using Febe.Core.Storage;
namespace Febe.Core.Library;
@@ -371,6 +372,9 @@ public sealed class LibraryIngest(
stored.Media,
highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(),
ct).ConfigureAwait(false);
// The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line.
await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
+162 -13
View File
@@ -1,7 +1,9 @@
using System.Globalization;
using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library.Conversion;
using Febe.Core.Storage;
namespace Febe.Core.Library;
@@ -61,6 +63,15 @@ public sealed record RebuildReport
/// <summary>Files in account folders that no journal line mentions: left untouched, not added.</summary>
public int UntrackedFiles { get; init; }
/// <summary>
/// Converted files of the library without a record (tappa E3): next to a file of the journal, with its name and in a
/// target format. Left untouched; queued again when the conversion for their kind is on with that format.
/// </summary>
public int ConversionsFound { get; init; }
/// <summary>Converted files of the library still on disk for entries deleted «ricordando la scelta»: left untouched.</summary>
public int ConversionsOfDeletedEntries { get; init; }
public int InvalidLines { get; init; }
/// <summary>A few examples of what needs attention (Italian), for the report screen.</summary>
@@ -152,7 +163,7 @@ public sealed class LibraryRebuilder(
var allItems = Fold(journal.Lines, report);
// Entries already in the database are left as they are (deletions excepted): no hashing, no change.
var items = await SplitPresentAsync(account, allItems, report, ct).ConfigureAwait(false);
var items = await SplitPresentAsync(account, folder, allItems, report, ct).ConfigureAwait(false);
// Verify files in parallel: hashing dominates the time.
var live = items.Where(i => !i.Deleted).ToList();
@@ -198,11 +209,11 @@ public sealed class LibraryRebuilder(
batch.Add((item, new NewEntry(entry, media)));
if (batch.Count >= BatchSize)
{
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false);
}
}
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false);
// Files whose bytes on disk differ from the journal: their copies in external folders are «Superato» (spec §4.10).
foreach (var (old, now) in report.Changed)
@@ -211,14 +222,14 @@ public sealed class LibraryRebuilder(
}
report.Changed.Clear();
CountUntracked(folder, allItems, report);
await CountUntrackedAsync(account, folder, allItems, report, ct).ConfigureAwait(false);
}
/// <summary>
/// Returns the items that are not in the database yet. Items already present are counted; a remembered deletion
/// is applied to them if the database still shows them.
/// </summary>
private async Task<List<Item>> SplitPresentAsync(Account account, List<Item> items, Accumulator report, CancellationToken ct)
private async Task<List<Item>> SplitPresentAsync(Account account, string folder, List<Item> items, Accumulator report, CancellationToken ct)
{
var paths = await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false);
var known = new HashSet<(EntryKind, string)>();
@@ -253,7 +264,7 @@ public sealed class LibraryRebuilder(
: null;
if (existing is not null && existing.State != EntryState.Deleted)
{
await storage.Entries.MarkDeletedAsync(existing.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false);
await MarkDeletedAsync(folder, existing.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false);
}
}
}
@@ -582,7 +593,7 @@ public sealed class LibraryRebuilder(
};
}
private async Task FlushAsync(Account account, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct)
private async Task FlushAsync(Account account, string folder, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct)
{
if (batch.Count == 0)
{
@@ -604,7 +615,7 @@ public sealed class LibraryRebuilder(
report.EntriesAlreadyPresent++;
if (item.Deleted && stored.Entry.State != EntryState.Deleted)
{
await storage.Entries.MarkDeletedAsync(stored.Entry.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false);
await MarkDeletedAsync(folder, stored.Entry.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false);
}
}
@@ -661,11 +672,98 @@ public sealed class LibraryRebuilder(
State = MediaState.Deleted,
};
private static void CountUntracked(string folder, List<Item> items, Accumulator report)
/// <summary>
/// A remembered deletion found by the rebuild (tappa E3, WP2.4): the entry's conversions whose converted file is
/// missing become «Tolto»; those whose file is still on disk stay as they are (the rebuild never deletes a file) and
/// are counted.
/// </summary>
private async Task MarkDeletedAsync(string folder, long entryId, DateTimeOffset at, Accumulator report, CancellationToken ct)
{
var missing = new List<long>();
foreach (var conversion in await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false))
{
if (conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded) || conversion.RelativePath is not { } relative)
{
continue;
}
if (ExistsIn(folder, relative))
{
report.ConversionsOfDeletedEntries++;
}
else
{
missing.Add(conversion.Id);
}
}
await storage.Entries.MarkDeletedAsync(entryId, at, missing, ct).ConfigureAwait(false);
}
private static bool ExistsIn(string folder, string relative)
{
try
{
return File.Exists(LibraryLayout.FullPath(folder, relative));
}
catch (ArgumentException)
{
return false;
}
}
/// <summary>The format a converted file of the library has, by its extension; null for any other file.</summary>
private static ExportFormat? ConvertedFormatOf(string extension) => extension.ToLowerInvariant() switch
{
".jpg" or ".jpeg" => ExportFormat.Jpg,
".png" => ExportFormat.Png,
".webp" => ExportFormat.WebpLossless,
".mp4" => ExportFormat.Mp4,
_ => null,
};
/// <summary>«nome (2)» → «nome»: the free names the conversion for the library gives.</summary>
private static string WithoutNumber(string stem)
{
var open = stem.LastIndexOf(" (", StringComparison.Ordinal);
if (open > 0 && stem.EndsWith(')')
&& int.TryParse(stem.AsSpan(open + 2, stem.Length - open - 3), NumberStyles.None, CultureInfo.InvariantCulture, out _))
{
return stem[..open];
}
return stem;
}
/// <summary>
/// Counts the files of the account folder that no journal line mentions (left untouched). The converted files of the
/// library (tappa E3) are not unknown: those with a row are skipped; one without a row, next to a file of the
/// journal with its stem and in a target format, is counted apart and, when the conversion for that kind is on with
/// that format, its file is queued again (a Pending row: the worker adopts the file by its SHA-256). Nothing is
/// converted during the rebuild.
/// </summary>
private async Task CountUntrackedAsync(Account account, string folder, List<Item> items, Accumulator report, CancellationToken ct)
{
var comparer = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
var known = new HashSet<string>(
items.SelectMany(i => i.Files.Values.Concat(i.Removed.Values)).Select(f => LibraryLayout.ToStored(f.Path)),
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
comparer);
foreach (var path in await storage.Conversions.ListPathsByAccountAsync(account.Id, ct).ConfigureAwait(false))
{
known.Add(path);
}
// Files of the journal by folder and stem, for the converted files next to them.
var byStem = new Dictionary<string, JournalFile>(comparer);
foreach (var file in items.Where(i => !i.Deleted).SelectMany(i => i.Files.Values))
{
var stored = LibraryLayout.ToStored(file.Path);
var slash = stored.LastIndexOf('/');
byStem.TryAdd((slash < 0 ? string.Empty : stored[..(slash + 1)]) + WindowsFileNames.SplitExtension(stored[(slash + 1)..]).Stem, file);
}
ExportSettings? settings = null;
IReadOnlyDictionary<string, long>? paths = null;
foreach (var file in Directory.EnumerateFiles(folder, "*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true }))
{
var name = Path.GetFileName(file);
@@ -675,11 +773,56 @@ public sealed class LibraryRebuilder(
}
var relative = LibraryLayout.ToStored(Path.GetRelativePath(folder, file));
if (!known.Contains(relative))
if (known.Contains(relative))
{
report.UntrackedFiles++;
report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}");
continue;
}
var slash = relative.LastIndexOf('/');
var (stem, extension) = WindowsFileNames.SplitExtension(relative[(slash + 1)..]);
var key = (slash < 0 ? string.Empty : relative[..(slash + 1)]) + WithoutNumber(stem);
if (ConvertedFormatOf(extension) is { } format && byStem.TryGetValue(key, out var original))
{
report.ConversionsFound++;
try
{
settings ??= await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
paths ??= await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false);
await QueueFoundAsync(original, format, settings, paths, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DuplicateRecordException or KeyNotFoundException or ArgumentException)
{
// Counted, never thrown: the worker or a later rebuild finds it again.
}
continue;
}
report.UntrackedFiles++;
report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}");
}
}
/// <summary>Queues the journal file <paramref name="original"/> in <paramref name="format"/> when its conversion is on with that format.</summary>
private async Task QueueFoundAsync(JournalFile original, ExportFormat format, ExportSettings settings, IReadOnlyDictionary<string, long> paths, CancellationToken ct)
{
var stored = LibraryLayout.ToStored(original.Path);
if (!paths.TryGetValue(stored, out var entryId))
{
return;
}
var media = (await storage.Media.ListByEntryAsync(entryId, ct).ConfigureAwait(false))
.FirstOrDefault(m => m.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), stored, StringComparison.Ordinal));
if (media is null || LibraryConversionRules.FormatFor(media.Kind, settings) != format)
{
return;
}
var requests = LibraryConversionRules.RequestsFor([media], settings);
if (requests.Count > 0)
{
await storage.Conversions.EnqueueAsync(requests, clock.Now, ct).ConfigureAwait(false);
}
}
@@ -746,6 +889,10 @@ public sealed class LibraryRebuilder(
public int UntrackedFiles { get; set; }
public int ConversionsFound { get; set; }
public int ConversionsOfDeletedEntries { get; set; }
public int InvalidLines { get; set; }
/// <summary>(journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato».</summary>
@@ -773,6 +920,8 @@ public sealed class LibraryRebuilder(
FilesUnreadable = FilesUnreadable,
HashMismatches = HashMismatches,
UntrackedFiles = UntrackedFiles,
ConversionsFound = ConversionsFound,
ConversionsOfDeletedEntries = ConversionsOfDeletedEntries,
InvalidLines = InvalidLines,
Notes = _notes,
};