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:
1 parent
b746aff45d
commit
724c5bda6f
25 files changed
+2621
-38
No files matched your search
+22
-1
@@ -14,6 +14,7 @@ using Febe.Core.Engine;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Import;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Security;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
@@ -194,9 +195,12 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
DataFolder = data.Root,
|
||||
Gate = longWork,
|
||||
});
|
||||
var idleConversion = new LibraryConversionWorker(new LibraryConversionEnvironment { Storage = Database, Layout = () => library.Layout, Clock = Clock, Gate = longWork });
|
||||
await StartWebAsync(hooks, services =>
|
||||
{
|
||||
services.AddSingleton(longWork);
|
||||
services.AddSingleton(idleConversion);
|
||||
services.AddSingleton(new LibraryConversionQueue(Database, Clock));
|
||||
services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false));
|
||||
services.AddSingleton<IFebeStorage>(Database);
|
||||
services.AddSingleton(library);
|
||||
@@ -336,12 +340,28 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
_telegram = new TelegramClient(hooks.TelegramHandler);
|
||||
var telegramChannel = new TelegramAlertChannel(_telegram);
|
||||
|
||||
// The conversion for the library (tappa E3, spec §4.10): one worker, started below in the background; it yields
|
||||
// to import, copies and rebuild through the gate and never runs during an engine session. Never in the demo.
|
||||
var sessionState = new RuntimeSessionState(services.Runtime);
|
||||
var conversion = new LibraryConversionWorker(new LibraryConversionEnvironment
|
||||
{
|
||||
Storage = Database,
|
||||
Layout = () => library.Layout,
|
||||
Clock = Clock,
|
||||
Gate = longWork,
|
||||
Session = sessionState,
|
||||
FreeSpace = hooks.FreeSpace ?? new DriveFreeSpaceProbe(),
|
||||
Log = message => Log.Write(LogLevel.Warning, "conversione", message),
|
||||
});
|
||||
|
||||
await StartWebAsync(hooks, s =>
|
||||
{
|
||||
s.AddSingleton(longWork);
|
||||
s.AddSingleton(conversion);
|
||||
s.AddSingleton(new LibraryConversionQueue(Database, Clock));
|
||||
s.AddSingleton(exportRoot);
|
||||
s.AddSingleton<IExportDisk>(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts));
|
||||
s.AddSingleton<IEngineSessionState>(new RuntimeSessionState(services.Runtime));
|
||||
s.AddSingleton<IEngineSessionState>(sessionState);
|
||||
s.AddSingleton<IFebeStorage>(Database);
|
||||
s.AddSingleton(library);
|
||||
s.AddSingleton<IClock>(Clock);
|
||||
@@ -398,6 +418,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime));
|
||||
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime));
|
||||
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
|
||||
InBackground(() => conversion.RunAsync(lifetime));
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> in the background; the stop waits for it.</summary>
|
||||
|
||||
@@ -13,19 +13,38 @@ public enum LongWorkKind
|
||||
|
||||
/// <summary>«Ricostruisci il database dalla libreria» (spec §8.5).</summary>
|
||||
Rebuild,
|
||||
|
||||
/// <summary>
|
||||
/// The conversion for the library (tappa E3, spec §4.10): held only as a <see cref="LongWorkGate.BackgroundLease"/>,
|
||||
/// which any of the others pre-empts.
|
||||
/// </summary>
|
||||
LibraryConversion,
|
||||
|
||||
/// <summary>A zip of 21 to 500 frames being prepared for «Scarica» (tappa E3, D14).</summary>
|
||||
FrameDownload,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lets only one of import, export and rebuild run at a time, in both directions. One instance is shared by the whole
|
||||
/// process (the composition registers it once). A lease is taken when a job starts and disposed when it ends; disposing
|
||||
/// it twice releases nothing more.
|
||||
/// Lets only one of import, export, rebuild and frame download run at a time, in both directions. One instance is
|
||||
/// shared by the whole process (the composition registers it once). A lease is taken when a job starts and disposed when
|
||||
/// it ends; disposing it twice releases nothing more.
|
||||
/// <para>
|
||||
/// The conversion for the library takes a <see cref="BackgroundLease"/> instead (tappa E3, WP2.1): it runs only while
|
||||
/// no foreground lease is held, and a foreground <see cref="TryEnter"/> pre-empts it. Outside a commit the conversion
|
||||
/// only reads an original and writes its own temporary file, so it simply stops; a commit (one rename and one
|
||||
/// transaction) is waited for, at most <see cref="CommitWait"/>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class LongWorkGate
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
private Lease? _holder;
|
||||
private BackgroundLease? _background;
|
||||
|
||||
/// <summary>Who holds the gate, or null when it is free.</summary>
|
||||
/// <summary>How long a foreground <see cref="TryEnter"/> waits for a commit of the background work to end.</summary>
|
||||
public TimeSpan CommitWait { get; init; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>Who holds the gate in the foreground, or null when it is free. The background lease does not count.</summary>
|
||||
public LongWorkKind? Busy
|
||||
{
|
||||
get
|
||||
@@ -37,12 +56,34 @@ public sealed class LongWorkGate
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while the background lease (the conversion for the library) is held and not pre-empted.</summary>
|
||||
public bool BackgroundRunning
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _background is not null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the gate for <paramref name="kind"/>. False, with <paramref name="busyWith"/> set, when another job (of any
|
||||
/// kind, the same one included) holds it.
|
||||
/// kind, the same one included) holds it in the foreground. A background lease is pre-empted: its token is
|
||||
/// cancelled and, if it is committing a file, the commit is waited for (at most <see cref="CommitWait"/>; past it,
|
||||
/// false with <see cref="LongWorkKind.LibraryConversion"/>).
|
||||
/// </summary>
|
||||
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
|
||||
{
|
||||
if (kind == LongWorkKind.LibraryConversion)
|
||||
{
|
||||
throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind));
|
||||
}
|
||||
|
||||
Lease taken;
|
||||
BackgroundLease? preempted;
|
||||
bool committing;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_holder is { } holder)
|
||||
@@ -52,10 +93,47 @@ public sealed class LongWorkGate
|
||||
return false;
|
||||
}
|
||||
|
||||
var taken = new Lease(this, kind);
|
||||
taken = new Lease(this, kind);
|
||||
_holder = taken;
|
||||
lease = taken;
|
||||
busyWith = null;
|
||||
preempted = _background;
|
||||
_background = null;
|
||||
committing = preempted?.MarkPreempted() ?? false;
|
||||
}
|
||||
|
||||
if (preempted is not null)
|
||||
{
|
||||
// Outside the lock: the token's callbacks run synchronously and may take the gate's lock.
|
||||
preempted.CancelPreempted();
|
||||
if (committing && !preempted.WaitForCommit(CommitWait))
|
||||
{
|
||||
taken.Dispose();
|
||||
lease = null;
|
||||
busyWith = LongWorkKind.LibraryConversion;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
lease = taken;
|
||||
busyWith = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the gate in the background for the conversion for the library. False while any foreground lease, or
|
||||
/// another background lease, is held.
|
||||
/// </summary>
|
||||
public bool TryEnterBackground([NotNullWhen(true)] out BackgroundLease? lease)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_holder is not null || _background is not null)
|
||||
{
|
||||
lease = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
lease = new BackgroundLease(this);
|
||||
_background = lease;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -68,14 +146,20 @@ public sealed class LongWorkGate
|
||||
(LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.",
|
||||
(_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
||||
(_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
||||
_ => "La ricostruzione del database è in corso: aspetta che finisca.",
|
||||
(_, LongWorkKind.LibraryConversion) => "La conversione della libreria sta salvando un file: riprova fra un attimo.",
|
||||
(_, LongWorkKind.FrameDownload) => $"Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi {Verb(wanted)}.",
|
||||
(_, LongWorkKind.Rebuild) => "La ricostruzione del database è in corso: aspetta che finisca.",
|
||||
_ => "Un altro lavoro lungo è in corso: aspetta che finisca.",
|
||||
};
|
||||
|
||||
private static string Verb(LongWorkKind kind) => kind switch
|
||||
{
|
||||
LongWorkKind.Import => "importa",
|
||||
LongWorkKind.Export => "copia",
|
||||
_ => "ricostruisci",
|
||||
LongWorkKind.Rebuild => "ricostruisci",
|
||||
LongWorkKind.FrameDownload => "scarica i fotogrammi",
|
||||
LongWorkKind.LibraryConversion => "converti",
|
||||
_ => "riprova",
|
||||
};
|
||||
|
||||
private void Release(Lease lease)
|
||||
@@ -89,6 +173,17 @@ public sealed class LongWorkGate
|
||||
}
|
||||
}
|
||||
|
||||
private void Release(BackgroundLease lease)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (ReferenceEquals(_background, lease))
|
||||
{
|
||||
_background = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
@@ -103,4 +198,112 @@ public sealed class LongWorkGate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The background lease of the conversion for the library. <see cref="Preempted"/> is cancelled when a foreground
|
||||
/// job wants the gate; a commit (<see cref="TryBeginCommit"/>) is waited for by that job, and none begins once
|
||||
/// pre-empted or disposed.
|
||||
/// </summary>
|
||||
public sealed class BackgroundLease : IDisposable
|
||||
{
|
||||
private readonly LongWorkGate _gate;
|
||||
|
||||
// Neither is disposed: a foreground TryEnter may cancel or wait on them after the lease ended, and without a
|
||||
// timer or a wait handle asked for they hold nothing but memory.
|
||||
private readonly CancellationTokenSource _preempted = new();
|
||||
private readonly ManualResetEventSlim _noCommit = new(initialState: true);
|
||||
private bool _isPreempted;
|
||||
private bool _committing;
|
||||
private int _disposed;
|
||||
|
||||
internal BackgroundLease(LongWorkGate gate)
|
||||
{
|
||||
_gate = gate;
|
||||
Preempted = _preempted.Token;
|
||||
}
|
||||
|
||||
/// <summary>Cancelled when a foreground job takes the gate.</summary>
|
||||
public CancellationToken Preempted { get; }
|
||||
|
||||
/// <summary>True once a foreground job asked for the gate (or the lease ended).</summary>
|
||||
public bool IsPreempted
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate._lock)
|
||||
{
|
||||
return _isPreempted;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begins a commit (a rename and its record) that a foreground job waits for. False once pre-empted or disposed,
|
||||
/// or while another commit of this lease runs: then nothing may be renamed or recorded.
|
||||
/// </summary>
|
||||
public bool TryBeginCommit([NotNullWhen(true)] out IDisposable? commit)
|
||||
{
|
||||
lock (_gate._lock)
|
||||
{
|
||||
if (_isPreempted || _disposed != 0 || _committing)
|
||||
{
|
||||
commit = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
_committing = true;
|
||||
_noCommit.Reset();
|
||||
commit = new Commit(this);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
EndCommit();
|
||||
_gate.Release(this);
|
||||
lock (_gate._lock)
|
||||
{
|
||||
_isPreempted = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Under the gate's lock: marks the lease pre-empted and tells whether a commit is running.</summary>
|
||||
internal bool MarkPreempted()
|
||||
{
|
||||
_isPreempted = true;
|
||||
return _committing;
|
||||
}
|
||||
|
||||
internal void CancelPreempted() => _preempted.Cancel();
|
||||
|
||||
internal bool WaitForCommit(TimeSpan timeout) => _noCommit.Wait(timeout);
|
||||
|
||||
private void EndCommit()
|
||||
{
|
||||
lock (_gate._lock)
|
||||
{
|
||||
_committing = false;
|
||||
_noCommit.Set();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Commit(BackgroundLease lease) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 0)
|
||||
{
|
||||
lease.EndCommit();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
@@ -25,6 +26,7 @@ public static class ExportSupersession
|
||||
}
|
||||
|
||||
var old = oldSha256.ToLowerInvariant();
|
||||
await LibraryConversionsChangedAsync(storage, accountId, old, newSha256.ToLowerInvariant(), at).ConfigureAwait(false);
|
||||
var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false);
|
||||
if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State)))
|
||||
{
|
||||
@@ -33,4 +35,31 @@ public static class ExportSupersession
|
||||
|
||||
return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The conversions for the library of the account's file that now has <paramref name="newSha256"/> (tappa E3,
|
||||
/// WP2.4): a converted file of the old bytes is «Superato» (it stays), the queue and the failures take the new bytes,
|
||||
/// and the file is queued again in the library formats set now.
|
||||
/// </summary>
|
||||
private static async Task LibraryConversionsChangedAsync(IFebeStorage storage, long accountId, string oldSha256, string newSha256, DateTimeOffset at)
|
||||
{
|
||||
var none = CancellationToken.None;
|
||||
var changed = await storage.Conversions.SupersedeAsync(accountId, oldSha256, newSha256, at, none).ConfigureAwait(false);
|
||||
if (changed.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var media = new List<Media>();
|
||||
foreach (var id in changed)
|
||||
{
|
||||
if (await storage.Media.GetAsync(id, none).ConfigureAwait(false) is { } m)
|
||||
{
|
||||
media.Add(m);
|
||||
}
|
||||
}
|
||||
|
||||
await LibraryConversionQueue.EnqueueEntryAsync(storage, media, at, none).ConfigureAwait(false);
|
||||
LibraryConversionQueue.Signal();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,9 @@ namespace Febe.Core.Import;
|
||||
/// <summary>What the comparison decided for one file.</summary>
|
||||
internal sealed record Comparison(ImportOutcome Outcome, long? MatchedMediaId, DuplicatePair? Pair, string? Note);
|
||||
|
||||
/// <summary>A file of the source that is a converted copy of a library file; its original when known.</summary>
|
||||
internal sealed record ConvertedCopyMatch(long? MediaId);
|
||||
|
||||
/// <summary>
|
||||
/// The comparison with the library (spec §9.3), for one analysis session. In this order:
|
||||
/// <list type="number">
|
||||
@@ -39,6 +42,9 @@ internal sealed class ImportComparer
|
||||
private readonly Dictionary<string, long> _sourceIdentity = new(StringComparer.Ordinal);
|
||||
private readonly PerceptualHashIndex _sourceHashes = new();
|
||||
|
||||
// The SHA-256 of the converted copies and frames written in destinations (one read per run, tappa E3, Q37).
|
||||
private IReadOnlySet<string> _copyShas = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
private ImportComparer(IFebeStorage storage, PerceptualHashIndex library, Func<DateTimeOffset> now)
|
||||
{
|
||||
_storage = storage;
|
||||
@@ -69,6 +75,7 @@ internal sealed class ImportComparer
|
||||
}
|
||||
|
||||
var comparer = new ImportComparer(storage, library, now);
|
||||
comparer._copyShas = await storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false);
|
||||
var identifiers = await storage.Imports.LoadLibraryIdentifiersAsync(ct).ConfigureAwait(false);
|
||||
foreach (var entry in identifiers.Entries)
|
||||
{
|
||||
@@ -141,6 +148,13 @@ internal sealed class ImportComparer
|
||||
return new Comparison(ImportOutcome.AlreadyInLibrary, deleted.Media.Id, null, ImportText.NoteDeletedByAlberto);
|
||||
}
|
||||
|
||||
// A converted file of the library, or a converted copy or a frame of a destination: already in the library as
|
||||
// its original, never a probable duplicate of it (tappa E3, Q37).
|
||||
if (await IsConvertedCopyAsync(_storage, _copyShas, file.Sha256, ct).ConfigureAwait(false) is { } converted)
|
||||
{
|
||||
return new Comparison(ImportOutcome.AlreadyInLibrary, converted.MediaId, null, ImportText.NoteConvertedCopy);
|
||||
}
|
||||
|
||||
// 2. Same bytes earlier in the source.
|
||||
if (_sourceSha.TryGetValue(file.Sha256, out var twin) && twin.Id != file.Id)
|
||||
{
|
||||
@@ -177,6 +191,21 @@ internal sealed class ImportComparer
|
||||
return new Comparison(ImportOutcome.New, null, null, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="sha256"/> is the SHA-256 of a converted file of the library (with its original's media
|
||||
/// id) or of a converted copy or frame written in a destination (media id null); null when it is neither.
|
||||
/// </summary>
|
||||
internal static async Task<ConvertedCopyMatch?> IsConvertedCopyAsync(IFebeStorage storage, IReadOnlySet<string> copyShas, string sha256, CancellationToken ct)
|
||||
{
|
||||
var conversions = await storage.Conversions.FindBySha256Async(sha256, ct).ConfigureAwait(false);
|
||||
if (conversions.Count > 0)
|
||||
{
|
||||
return new ConvertedCopyMatch(conversions[0].MediaId);
|
||||
}
|
||||
|
||||
return copyShas.Contains(sha256) ? new ConvertedCopyMatch(null) : null;
|
||||
}
|
||||
|
||||
private async Task<Comparison?> MatchIdentityAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct)
|
||||
{
|
||||
var candidates = new List<(EntryIdentity Entry, long? MediaId)>();
|
||||
|
||||
@@ -258,6 +258,14 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = twin.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// A converted copy of a library file written since the analysis (tappa E3, Q37): never imported as a new file.
|
||||
context.CopyShas ??= await env.Storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false);
|
||||
if (file.EntryId is null && await ImportComparer.IsConvertedCopyAsync(env.Storage, context.CopyShas, file.Sha256!, ct).ConfigureAwait(false) is { } converted)
|
||||
{
|
||||
tally.Skipped++;
|
||||
return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = converted.MediaId, LastError = ImportText.NoteConvertedCopy }).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var account = await env.Storage.Accounts.GetAsync(file.TargetAccountId!.Value, ct).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException("L'account di destinazione non esiste più: associa di nuovo la cartella.");
|
||||
var hints = context.Recognizers.Recognize(new ImportFileContext(context.Layout, file.RelativePath));
|
||||
@@ -790,7 +798,11 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest);
|
||||
private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest)
|
||||
{
|
||||
/// <summary>The SHA-256 of converted copies and frames in destinations, read once per run when first needed.</summary>
|
||||
public IReadOnlySet<string>? CopyShas { get; set; }
|
||||
}
|
||||
|
||||
private sealed class Tally
|
||||
{
|
||||
|
||||
@@ -139,6 +139,9 @@ public static class ImportText
|
||||
internal const string NoteLargerInSource = "Hai scelto di tenere il più grande: è un altro file della sorgente, che prende il posto di quello in libreria.";
|
||||
internal const string NoteNotRecognized = "Né foto né video: ignorato.";
|
||||
internal const string NoteAlreadyInLibrary = "Identico a un file già in libreria: saltato.";
|
||||
|
||||
/// <summary>A converted file of the library, a converted copy or a frame written in a destination (tappa E3, Q37).</summary>
|
||||
internal const string NoteConvertedCopy = "È una copia convertita (o un fotogramma) di un file già in libreria.";
|
||||
internal const string NoteReplaced = "Ha sostituito il file più piccolo della libreria, come hai scelto.";
|
||||
internal const string NoteChanged = "Il file è cambiato dopo l'analisi: non è stato copiato. Per prenderlo avvia una nuova importazione della cartella.";
|
||||
internal const string NoteNotVerified = "La copia in libreria non corrisponde all'originale: l'originale resta al suo posto. Controlla il disco della libreria.";
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -58,11 +58,28 @@ public interface IEntryStore
|
||||
/// «Eliminato»: the entry stays without files so it is not downloaded again (spec §4.6). Its files become
|
||||
/// <see cref="MediaState.Deleted"/> and lose their path and perceptual hash; SHA-256 and size are kept. Deleting files on disk is the caller's job.
|
||||
/// </summary>
|
||||
Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default);
|
||||
Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct);
|
||||
|
||||
/// <summary>«Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade).</summary>
|
||||
/// <summary>
|
||||
/// As <see cref="MarkDeletedAsync(long, DateTimeOffset, CancellationToken)"/>, and in the same transaction the
|
||||
/// conversions for the library of its files: the queue and the failures (Pending, Failed) go, and the rows of
|
||||
/// <paramref name="removedConversionIds"/> (whose converted file goes or is gone) become «Tolto». Other converted rows stay.
|
||||
/// </summary>
|
||||
Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). Conversions
|
||||
/// without a file left (Pending, Failed, Removed) go with it; a Converted or Superseded one makes it fail with
|
||||
/// <see cref="InvalidOperationException"/> (its file would be forgotten): use <see cref="RemoveWithConversionsAsync"/>.
|
||||
/// </summary>
|
||||
Task RemoveAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Eliminalo e lascia che torni» from «Elimina dalla libreria»: removes the record and every conversion of its files
|
||||
/// in one transaction, and returns the conversions removed (their converted files are the caller's to delete).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaConversion>> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Entries of an account ordered by publication time, newest first (account tabs, collection pipeline).</summary>
|
||||
Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default);
|
||||
|
||||
|
||||
@@ -198,6 +198,13 @@ public interface IExportStore
|
||||
/// </summary>
|
||||
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The SHA-256 of every file written converted or as a frame in a destination (any state, any destination): an
|
||||
/// import recognises them as copies of library files (tappa E3, Q37). No index on <c>copy_sha256</c>: one read per
|
||||
/// import run, bounded by the converted copies.
|
||||
/// </summary>
|
||||
Task<IReadOnlySet<string>> LoadConvertedCopyShasAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The current (Copied or Failed) rows of an original for an account in a destination, in any form but a frame,
|
||||
/// newest first: «già copiato» looks at the file, not at its format (decision D3 of tappa E3).
|
||||
|
||||
@@ -25,9 +25,119 @@ public interface IMediaConversionStore
|
||||
/// <summary>The conversions of one library file, in creation order.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> ListByMediaAsync(long mediaId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The conversions of the files of one entry, by file and creation order.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> ListByEntryAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The conversions of these library files, by file and creation order.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> ListByMediaIdsAsync(IReadOnlyCollection<long> mediaIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The paths (relative to the account folder) that conversions of the account's files record: Converted,
|
||||
/// Superseded and Removed rows (a rebuild does not count them as unknown files).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<string>> ListPathsByAccountAsync(long accountId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The conversions of the account's files that record this path (any state with a path), by key.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Conversions whose converted file has this SHA-256 (a converted file found again is never a duplicate).</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> FindBySha256Async(string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The queue of the conversion, in order, by key.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default);
|
||||
|
||||
/// <summary>«Tolto»: these Converted or Superseded rows lost their file with their entry. Returns the rows changed.</summary>
|
||||
Task<int> MarkRemovedAsync(IReadOnlyCollection<long> ids, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// A library file left its entry («Tieni il più grande» on a file of a series): its queue and failures go, its rows
|
||||
/// with a file become «Tolto», in one transaction. Returns the rows marked «Tolto».
|
||||
/// </summary>
|
||||
Task<int> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The account's file changed from <paramref name="oldSha256"/> to <paramref name="newSha256"/> (spec §4.10
|
||||
/// «Superato»): the conversions made from the old bytes of the account's files that now have the new ones become
|
||||
/// Superseded (their files stay); Pending and retryable Failed rows take the new SHA-256. Returns the media ids of the
|
||||
/// files concerned (to queue them again).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<long>> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The setting of a format went off or changed: its queue is emptied (Converted rows and their files stay).</summary>
|
||||
Task<int> DeletePendingAsync(ExportFormat format, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending.</summary>
|
||||
Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default);
|
||||
|
||||
/// <summary>How many rows are in each state; Failed rows with an <c>AsIs*</c> code are counted apart.</summary>
|
||||
Task<MediaConversionCounts> CountByStateAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Queues these files in these formats (Pending, <c>source_sha256</c> = the given SHA-256). A file that already has a
|
||||
/// current conversion in the format (Pending, Converted, or Failed, which holds the slot) is left as it is. Returns
|
||||
/// how many rows were added.
|
||||
/// </summary>
|
||||
Task<int> EnqueueAsync(IReadOnlyList<MediaConversionRequest> requests, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Anche i N già in libreria»: queues, in one statement, every present library file of each kind whose extension
|
||||
/// says it converts into the format given for its kind (null: that kind is not queued). Returns how many were added.
|
||||
/// </summary>
|
||||
Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>What <see cref="EnqueueExistingAsync"/> would queue: files and their bytes.</summary>
|
||||
Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Records a converted file just written (or adopted) for a Pending row, in one transaction (WP2.2 step 4): the row
|
||||
/// becomes Converted only if it is still Pending with <paramref name="sourceSha256"/> and its library file is still
|
||||
/// present with that SHA-256. Otherwise, with the file still present and unchanged, the current conversion of that
|
||||
/// file and format becomes Converted with this file, or a new row is added; with the file gone or changed nothing is
|
||||
/// recorded.
|
||||
/// </summary>
|
||||
Task<MediaConversionCommitOutcome> CommitAsync(MediaConversionCommit commit, CancellationToken ct = default);
|
||||
|
||||
/// <summary>«Riprova»: Failed rows go back to Pending, except those with an <c>AsIs*</c> code (they never convert). Returns how many.</summary>
|
||||
Task<int> ResetFailedAsync(DateTimeOffset at, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>One file to queue in one format, made from these bytes.</summary>
|
||||
public sealed record MediaConversionRequest(long MediaId, ExportFormat Format, string SourceSha256);
|
||||
|
||||
/// <summary>The rows of the conversion for the library, by state.</summary>
|
||||
/// <param name="Pending">In the queue.</param>
|
||||
/// <param name="Converted">Converted files.</param>
|
||||
/// <param name="Failed">Failed, to try again («Riprova»).</param>
|
||||
/// <param name="AsIs">Failed for good: animated, not decodable, CMYK… («non si convertono»).</param>
|
||||
/// <param name="Superseded">Converted from bytes the library no longer has.</param>
|
||||
/// <param name="Removed">Their file went with the entry.</param>
|
||||
public sealed record MediaConversionCounts(int Pending, int Converted, int Failed, int AsIs, int Superseded, int Removed);
|
||||
|
||||
/// <summary>A converted file written for <paramref name="ConversionId"/>.</summary>
|
||||
/// <param name="ConversionId">The Pending row it was written for.</param>
|
||||
/// <param name="MediaId">Its library file.</param>
|
||||
/// <param name="Format">The format.</param>
|
||||
/// <param name="SourceSha256">The SHA-256 of the original it was made from.</param>
|
||||
/// <param name="RelativePath">Path relative to the account folder.</param>
|
||||
/// <param name="Bytes">Its size.</param>
|
||||
/// <param name="Sha256">Its SHA-256.</param>
|
||||
/// <param name="At">When it was converted.</param>
|
||||
/// <param name="Notes">What the conversion could not keep (loss codes, D19), or null.</param>
|
||||
public sealed record MediaConversionCommit(long ConversionId, long MediaId, ExportFormat Format, string SourceSha256,
|
||||
string RelativePath, long Bytes, string Sha256, DateTimeOffset At, string? Notes);
|
||||
|
||||
/// <summary>What <see cref="IMediaConversionStore.CommitAsync"/> did.</summary>
|
||||
public enum MediaConversionCommitOutcome
|
||||
{
|
||||
/// <summary>The Pending row is now Converted.</summary>
|
||||
Recorded,
|
||||
|
||||
/// <summary>The row had changed meanwhile; the file is recorded in the current row of its format, or a new one.</summary>
|
||||
Upserted,
|
||||
|
||||
/// <summary>Nothing recorded: the library file was deleted or changed meanwhile.</summary>
|
||||
SourceGone,
|
||||
|
||||
/// <summary>Nothing recorded: another converted file already holds the format of this library file.</summary>
|
||||
SlotTaken,
|
||||
}
|
||||
@@ -148,8 +148,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
|
||||
public Task<EntryState> RecomputeStateAsync(long entryId, CancellationToken ct = default) =>
|
||||
db.WriteAsync(w => RecomputeState(w, entryId), ct);
|
||||
|
||||
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct);
|
||||
|
||||
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(removedConversionIds);
|
||||
var removed = removedConversionIds.Distinct().ToList();
|
||||
return db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id")
|
||||
@@ -163,11 +168,69 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
|
||||
UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL
|
||||
WHERE entry_id = @id
|
||||
""").With("@id", entryId).ExecuteNonQuery();
|
||||
|
||||
// The conversions for the library of its files (tappa E3): nothing left to convert or retry; the
|
||||
// converted files that go (or are gone) are «Tolto», the others stay as they are.
|
||||
w.Command("""
|
||||
DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed') AND media_id IN (SELECT id FROM media WHERE entry_id = @id)
|
||||
""").With("@id", entryId).ExecuteNonQuery();
|
||||
if (removed.Count > 0)
|
||||
{
|
||||
var own = new HashSet<long>();
|
||||
using (var r = w.Command("SELECT mc.id FROM media_conversion mc JOIN media m ON m.id = mc.media_id WHERE m.entry_id = @id")
|
||||
.With("@id", entryId).ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
own.Add(r.GetInt64(0));
|
||||
}
|
||||
}
|
||||
|
||||
MediaConversionStore.MarkRemoved(w, removed.Where(own.Contains).ToList(), at);
|
||||
}
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
MediaConversionStore.DeleteRowsWithoutFile(w, entryId);
|
||||
try
|
||||
{
|
||||
w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery();
|
||||
}
|
||||
catch (SqliteException ex) when (ex.IsConstraintViolation())
|
||||
{
|
||||
// ON DELETE RESTRICT of media_conversion: a converted file of the library would lose its record.
|
||||
throw new InvalidOperationException(
|
||||
"L'elemento ha file convertiti nella libreria: eliminalo con «Elimina dalla libreria», che toglie anche quelli.", ex);
|
||||
}
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
|
||||
db.WriteAsync(w => w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(), ct);
|
||||
public Task<IReadOnlyList<MediaConversion>> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default) =>
|
||||
db.WriteAsync<IReadOnlyList<MediaConversion>>(
|
||||
w =>
|
||||
{
|
||||
var list = new List<MediaConversion>();
|
||||
using (var r = w.Command($"""
|
||||
SELECT {MediaConversionStore.JoinedColumnList} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
|
||||
WHERE m.entry_id = @id ORDER BY mc.media_id, mc.id
|
||||
""").With("@id", entryId).ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add(MediaConversionStore.ReadRow(r));
|
||||
}
|
||||
}
|
||||
|
||||
w.Command("DELETE FROM media_conversion WHERE media_id IN (SELECT id FROM media WHERE entry_id = @id)").With("@id", entryId).ExecuteNonQuery();
|
||||
w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery();
|
||||
return list;
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -829,6 +829,22 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
||||
/// <summary>The first item of a file of a job in a form (ux_export_item_file).</summary>
|
||||
internal const string FirstItemSql = "SELECT min(id) FROM export_item WHERE run_id = @r AND media_id = @m AND variant = @v AND format = @f";
|
||||
|
||||
public Task<IReadOnlySet<string>> LoadConvertedCopyShasAsync(CancellationToken ct = default) =>
|
||||
db.ReadAsync<IReadOnlySet<string>>(
|
||||
c =>
|
||||
{
|
||||
using var command = c.Command("SELECT DISTINCT copy_sha256 FROM export_copy WHERE variant IN ('Converted', 'Frame') AND copy_sha256 IS NOT NULL");
|
||||
using var r = command.ExecuteReader();
|
||||
var set = new HashSet<string>(StringComparer.Ordinal);
|
||||
while (r.Read())
|
||||
{
|
||||
set.Add(r.GetString(0));
|
||||
}
|
||||
|
||||
return set;
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<long?> FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default) =>
|
||||
db.ReadAsync(
|
||||
c => c.Command(FirstItemSql).With("@r", runId).With("@m", mediaId).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).ExecuteScalar() is long id
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Storage;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Febe.Data.Stores;
|
||||
|
||||
/// <summary>The queue, the commit and the hooks of the conversion for the library (tappa E3, WP2.3).</summary>
|
||||
internal sealed partial class MediaConversionStore
|
||||
{
|
||||
/// <summary>The same columns of the alias <c>mc</c>, for joins.</summary>
|
||||
private const string JoinedColumns =
|
||||
"mc.id, mc.media_id, mc.format, mc.state, mc.source_sha256, mc.relative_path, mc.bytes, mc.sha256, mc.created_at, mc.converted_at, mc.state_changed_at, mc.last_error";
|
||||
|
||||
/// <summary>The columns of the alias <c>mc</c>, for other stores reading rows with <see cref="ReadRow"/>.</summary>
|
||||
internal const string JoinedColumnList = JoinedColumns;
|
||||
|
||||
/// <summary>The present library files of the alias <c>m</c>, as the conversion for the library sees them.</summary>
|
||||
private const string PresentMedia = "m.state IN ('Downloaded', 'Imported') AND m.sha256 IS NOT NULL AND m.relative_path IS NOT NULL";
|
||||
|
||||
/// <summary>A Failed row whose code says it never converts (animated, not decodable, CMYK…): its first code.</summary>
|
||||
internal const string AsIsCondition = "last_error LIKE 'AsIs%'";
|
||||
|
||||
/// <summary>One row read in the order of <see cref="JoinedColumnList"/>.</summary>
|
||||
internal static MediaConversion ReadRow(SqliteDataReader r) => Read(r);
|
||||
|
||||
public Task<IReadOnlyList<MediaConversion>> ListByEntryAsync(long entryId, CancellationToken ct = default) =>
|
||||
db.ReadAsync<IReadOnlyList<MediaConversion>>(
|
||||
c => ReadAll(c.Command($"""
|
||||
SELECT {JoinedColumns} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
|
||||
WHERE m.entry_id = @e ORDER BY mc.media_id, mc.id
|
||||
""").With("@e", entryId)),
|
||||
ct);
|
||||
|
||||
public Task<IReadOnlyList<MediaConversion>> ListByMediaIdsAsync(IReadOnlyCollection<long> mediaIds, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mediaIds);
|
||||
var ids = mediaIds.Distinct().ToList();
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return Task.FromResult<IReadOnlyList<MediaConversion>>([]);
|
||||
}
|
||||
|
||||
return db.ReadAsync<IReadOnlyList<MediaConversion>>(
|
||||
c =>
|
||||
{
|
||||
var list = new List<MediaConversion>();
|
||||
foreach (var chunk in ids.Chunk(500))
|
||||
{
|
||||
using var command = c.Command(string.Empty);
|
||||
command.CommandText = $"SELECT {Columns} FROM media_conversion WHERE media_id IN ({command.AddList("m", chunk)})";
|
||||
list.AddRange(ReadAll(command));
|
||||
}
|
||||
|
||||
return list.OrderBy(x => x.MediaId).ThenBy(x => x.Id).ToList();
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<string>> ListPathsByAccountAsync(long accountId, CancellationToken ct = default) =>
|
||||
db.ReadAsync<IReadOnlyList<string>>(
|
||||
c =>
|
||||
{
|
||||
using var command = c.Command("""
|
||||
SELECT DISTINCT mc.relative_path FROM media_conversion mc
|
||||
JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND mc.relative_path IS NOT NULL AND mc.state IN ('Converted', 'Superseded', 'Removed')
|
||||
""").With("@a", accountId);
|
||||
using var r = command.ExecuteReader();
|
||||
var list = new List<string>();
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add(r.GetString(0));
|
||||
}
|
||||
|
||||
return list;
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<IReadOnlyList<MediaConversion>> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
|
||||
return db.ReadAsync<IReadOnlyList<MediaConversion>>(
|
||||
c => ReadAll(c.Command($"""
|
||||
SELECT {JoinedColumns} FROM media_conversion mc
|
||||
JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND mc.relative_path = @p ORDER BY mc.id
|
||||
""").With("@a", accountId).With("@p", relativePath)),
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<int> MarkRemovedAsync(IReadOnlyCollection<long> ids, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
var list = ids.Distinct().ToList();
|
||||
return list.Count == 0 ? Task.FromResult(0) : db.WriteAsync(w => MarkRemoved(w, list, at), ct);
|
||||
}
|
||||
|
||||
/// <summary>«Tolto» for these ids among the Converted and Superseded rows, inside the caller's transaction.</summary>
|
||||
internal static int MarkRemoved(WriteContext w, IReadOnlyCollection<long> ids, DateTimeOffset at)
|
||||
{
|
||||
var changed = 0;
|
||||
foreach (var chunk in ids.Chunk(500))
|
||||
{
|
||||
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||
command.CommandText = $"""
|
||||
UPDATE media_conversion SET state = 'Removed', state_changed_at = @at
|
||||
WHERE state IN ('Converted', 'Superseded') AND id IN ({command.AddList("i", chunk)})
|
||||
""";
|
||||
changed += command.With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
public Task<int> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
w.Command("DELETE FROM media_conversion WHERE media_id = @m AND state IN ('Pending', 'Failed')").With("@m", mediaId).ExecuteNonQuery();
|
||||
return w.Command("""
|
||||
UPDATE media_conversion SET state = 'Removed', state_changed_at = @at WHERE media_id = @m AND state IN ('Converted', 'Superseded')
|
||||
""").With("@m", mediaId).With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||
},
|
||||
ct);
|
||||
|
||||
/// <summary>The rows without a file left (Pending, Failed, Removed) of an entry's files go, inside the caller's transaction.</summary>
|
||||
internal static int DeleteRowsWithoutFile(WriteContext w, long entryId) =>
|
||||
w.Command("""
|
||||
DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed', 'Removed')
|
||||
AND media_id IN (SELECT id FROM media WHERE entry_id = @e)
|
||||
""").With("@e", entryId).ExecuteNonQuery();
|
||||
|
||||
public Task<IReadOnlyList<long>> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
var old = ExportValues.Sha(oldSha256, nameof(oldSha256));
|
||||
var now = ExportValues.Sha(newSha256, nameof(newSha256));
|
||||
if (old == now)
|
||||
{
|
||||
return Task.FromResult<IReadOnlyList<long>>([]);
|
||||
}
|
||||
|
||||
return db.WriteAsync<IReadOnlyList<long>>(
|
||||
w =>
|
||||
{
|
||||
var media = new List<long>();
|
||||
using (var find = w.Connection.Command("""
|
||||
SELECT DISTINCT mc.media_id FROM media_conversion mc
|
||||
JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND mc.source_sha256 = @old AND m.sha256 = @new
|
||||
AND mc.state IN ('Pending', 'Converted', 'Failed')
|
||||
ORDER BY mc.media_id
|
||||
""", w.Transaction))
|
||||
{
|
||||
find.With("@a", accountId).With("@old", old).With("@new", now);
|
||||
using var r = find.ExecuteReader();
|
||||
while (r.Read())
|
||||
{
|
||||
media.Add(r.GetInt64(0));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var chunk in media.Chunk(500))
|
||||
{
|
||||
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||
var list = command.AddList("m", chunk);
|
||||
|
||||
// Converted from the old bytes: history, its file stays. The queue and the failures take the new
|
||||
// bytes (a verdict, «AsIs» included, was about the old ones) and are tried again.
|
||||
command.CommandText = $"""
|
||||
UPDATE media_conversion SET state = 'Superseded', state_changed_at = @at
|
||||
WHERE state = 'Converted' AND source_sha256 = @old AND media_id IN ({list});
|
||||
UPDATE media_conversion SET state = 'Pending', source_sha256 = @new, last_error = NULL, state_changed_at = @at
|
||||
WHERE state IN ('Pending', 'Failed') AND source_sha256 = @old AND media_id IN ({list});
|
||||
""";
|
||||
command.With("@at", Sql.Time(at)).With("@old", old).With("@new", now).ExecuteNonQuery();
|
||||
}
|
||||
|
||||
return media;
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<int> DeletePendingAsync(ExportFormat format, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => w.Command("DELETE FROM media_conversion WHERE state = 'Pending' AND format = @f").With("@f", Sql.Enum(format)).ExecuteNonQuery(),
|
||||
ct);
|
||||
|
||||
public Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => w.Command("DELETE FROM media_conversion WHERE id = @id AND state = 'Pending'").With("@id", id).ExecuteNonQuery() > 0,
|
||||
ct);
|
||||
|
||||
public Task<MediaConversionCounts> CountByStateAsync(CancellationToken ct = default) =>
|
||||
db.ReadAsync(
|
||||
c =>
|
||||
{
|
||||
using var command = c.Command($"""
|
||||
SELECT state, CASE WHEN state = 'Failed' AND {AsIsCondition} THEN 1 ELSE 0 END, COUNT(*)
|
||||
FROM media_conversion GROUP BY 1, 2
|
||||
""");
|
||||
using var r = command.ExecuteReader();
|
||||
int pending = 0, converted = 0, failed = 0, asIs = 0, superseded = 0, removed = 0;
|
||||
while (r.Read())
|
||||
{
|
||||
var n = (int)r.GetInt64(2);
|
||||
switch (r.GetString(0))
|
||||
{
|
||||
case "Pending":
|
||||
pending += n;
|
||||
break;
|
||||
case "Converted":
|
||||
converted += n;
|
||||
break;
|
||||
case "Failed" when r.GetInt64(1) == 1:
|
||||
asIs += n;
|
||||
break;
|
||||
case "Failed":
|
||||
failed += n;
|
||||
break;
|
||||
case "Superseded":
|
||||
superseded += n;
|
||||
break;
|
||||
case "Removed":
|
||||
removed += n;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new MediaConversionCounts(pending, converted, failed, asIs, superseded, removed);
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<int> EnqueueAsync(IReadOnlyList<MediaConversionRequest> requests, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(requests);
|
||||
if (requests.Count == 0)
|
||||
{
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
var valid = requests.Select(r =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(r);
|
||||
if (r.Format == ExportFormat.Original)
|
||||
{
|
||||
throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(requests));
|
||||
}
|
||||
|
||||
return r with { SourceSha256 = ExportValues.Sha(r.SourceSha256, nameof(r.SourceSha256)) };
|
||||
}).ToList();
|
||||
return db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var added = 0;
|
||||
foreach (var r in valid)
|
||||
{
|
||||
// A current row (Pending, Converted, or Failed, which holds the slot) is left as it is.
|
||||
added += w.Command("""
|
||||
INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at)
|
||||
SELECT @m, @f, 'Pending', @s, @at WHERE EXISTS (SELECT 1 FROM media WHERE id = @m)
|
||||
ON CONFLICT DO NOTHING
|
||||
""").With("@m", r.MediaId).With("@f", Sql.Enum(r.Format)).With("@s", r.SourceSha256).With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||
}
|
||||
|
||||
return added;
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
/// <summary>The present files of a kind that convert into <paramref name="format"/>, as a condition on the alias <c>m</c>.</summary>
|
||||
private static string ExistingCondition(SqliteCommand command, MediaKind kind, ExportFormat format)
|
||||
{
|
||||
var excluded = LibraryConversionRules.ExcludedExtensions(format);
|
||||
var sql = new StringBuilder($"m.kind = @k AND {PresentMedia}");
|
||||
command.With("@k", Sql.Enum(kind));
|
||||
for (var i = 0; i < excluded.Count; i++)
|
||||
{
|
||||
// LIKE compares ASCII letters without case, as the extension rule does.
|
||||
sql.Append(CultureInfo.InvariantCulture, $" AND m.relative_path NOT LIKE @x{i}");
|
||||
command.With(string.Create(CultureInfo.InvariantCulture, $"@x{i}"), "%" + excluded[i]);
|
||||
}
|
||||
|
||||
return sql.ToString();
|
||||
}
|
||||
|
||||
private static List<(MediaKind Kind, ExportFormat Format)> Kinds(ExportFormat? photo, ExportFormat? video)
|
||||
{
|
||||
var kinds = new List<(MediaKind, ExportFormat)>();
|
||||
if (photo is { } p && p != ExportFormat.Original)
|
||||
{
|
||||
if (!ExportFormats.IsPhotoFormat(p))
|
||||
{
|
||||
throw new ArgumentException("Il formato non è adatto alle foto.", nameof(photo));
|
||||
}
|
||||
|
||||
kinds.Add((MediaKind.Photo, p));
|
||||
}
|
||||
|
||||
if (video is { } v && v != ExportFormat.Original)
|
||||
{
|
||||
if (!ExportFormats.IsVideoFormat(v))
|
||||
{
|
||||
throw new ArgumentException("Il formato non è adatto ai video.", nameof(video));
|
||||
}
|
||||
|
||||
kinds.Add((MediaKind.Video, v));
|
||||
}
|
||||
|
||||
return kinds;
|
||||
}
|
||||
|
||||
public Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
var kinds = Kinds(photo, video);
|
||||
if (kinds.Count == 0)
|
||||
{
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
return db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var added = 0;
|
||||
foreach (var (kind, format) in kinds)
|
||||
{
|
||||
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||
var where = ExistingCondition(command, kind, format);
|
||||
|
||||
// One statement; a file with a current row in the format (a Failed one included) keeps it.
|
||||
command.CommandText = $"""
|
||||
INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at)
|
||||
SELECT m.id, @f, 'Pending', m.sha256, @at FROM media m WHERE {where} ORDER BY m.id
|
||||
ON CONFLICT DO NOTHING
|
||||
""";
|
||||
added += command.With("@f", Sql.Enum(format)).With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||
}
|
||||
|
||||
return added;
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
|
||||
{
|
||||
var kinds = Kinds(photo, video);
|
||||
if (kinds.Count == 0)
|
||||
{
|
||||
return Task.FromResult((0, 0L));
|
||||
}
|
||||
|
||||
return db.ReadAsync(
|
||||
c =>
|
||||
{
|
||||
var files = 0;
|
||||
long bytes = 0;
|
||||
foreach (var (kind, format) in kinds)
|
||||
{
|
||||
using var command = c.Command(string.Empty);
|
||||
var where = ExistingCondition(command, kind, format);
|
||||
command.CommandText = $"""
|
||||
SELECT COUNT(*), COALESCE(SUM(m.bytes), 0) FROM media m
|
||||
WHERE {where} AND NOT EXISTS (
|
||||
SELECT 1 FROM media_conversion mc WHERE mc.media_id = m.id AND mc.format = @f AND mc.state IN ('Pending', 'Converted', 'Failed'))
|
||||
""";
|
||||
command.With("@f", Sql.Enum(format));
|
||||
using var r = command.ExecuteReader();
|
||||
if (r.Read())
|
||||
{
|
||||
files += (int)r.GetInt64(0);
|
||||
bytes += r.GetInt64(1);
|
||||
}
|
||||
}
|
||||
|
||||
return (files, bytes);
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<MediaConversionCommitOutcome> CommitAsync(MediaConversionCommit commit, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(commit);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(commit.RelativePath);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(commit.Bytes);
|
||||
if (commit.Format == ExportFormat.Original)
|
||||
{
|
||||
throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(commit));
|
||||
}
|
||||
|
||||
var source = ExportValues.Sha(commit.SourceSha256, nameof(commit.SourceSha256));
|
||||
var sha = ExportValues.Sha(commit.Sha256, nameof(commit.Sha256));
|
||||
return db.WriteAsync(w => Commit(w, commit, source, sha), ct);
|
||||
}
|
||||
|
||||
private static MediaConversionCommitOutcome Commit(WriteContext w, MediaConversionCommit commit, string source, string sha)
|
||||
{
|
||||
SqliteCommand Bind(SqliteCommand c) =>
|
||||
c.With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).With("@s", source).With("@p", commit.RelativePath)
|
||||
.With("@b", commit.Bytes).With("@h", sha).With("@at", Sql.Time(commit.At)).With("@e", Sql.Text(commit.Notes));
|
||||
|
||||
var recorded = Bind(w.Command($"""
|
||||
UPDATE media_conversion SET state = 'Converted', relative_path = @p, bytes = @b, sha256 = @h, converted_at = @at,
|
||||
state_changed_at = @at, last_error = @e
|
||||
WHERE id = @id AND media_id = @m AND format = @f AND state = 'Pending' AND source_sha256 = @s
|
||||
AND EXISTS (SELECT 1 FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia})
|
||||
""")).With("@id", commit.ConversionId).ExecuteNonQuery();
|
||||
if (recorded == 1)
|
||||
{
|
||||
return MediaConversionCommitOutcome.Recorded;
|
||||
}
|
||||
|
||||
var present = w.Command($"SELECT COUNT(*) FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia}")
|
||||
.With("@m", commit.MediaId).With("@s", source).ScalarInt64() > 0;
|
||||
if (!present)
|
||||
{
|
||||
return MediaConversionCommitOutcome.SourceGone;
|
||||
}
|
||||
|
||||
long? currentId = null;
|
||||
string? currentState = null;
|
||||
using (var r = w.Command("SELECT id, state FROM media_conversion WHERE media_id = @m AND format = @f AND state IN ('Pending', 'Converted', 'Failed')")
|
||||
.With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).ExecuteReader())
|
||||
{
|
||||
if (r.Read())
|
||||
{
|
||||
currentId = r.GetInt64(0);
|
||||
currentState = r.GetString(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (currentState == "Converted")
|
||||
{
|
||||
return MediaConversionCommitOutcome.SlotTaken;
|
||||
}
|
||||
|
||||
if (currentId is { } id)
|
||||
{
|
||||
Bind(w.Command("""
|
||||
UPDATE media_conversion SET state = 'Converted', source_sha256 = @s, relative_path = @p, bytes = @b, sha256 = @h,
|
||||
converted_at = @at, state_changed_at = @at, last_error = @e
|
||||
WHERE id = @id AND media_id = @m AND format = @f
|
||||
""")).With("@id", id).ExecuteNonQuery();
|
||||
return MediaConversionCommitOutcome.Upserted;
|
||||
}
|
||||
|
||||
// The row went (the setting was turned off meanwhile): the file just written stays recorded.
|
||||
Bind(w.Command("""
|
||||
INSERT INTO media_conversion (media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at,
|
||||
state_changed_at, last_error)
|
||||
VALUES (@m, @f, 'Converted', @s, @p, @b, @h, @at, @at, @at, @e)
|
||||
""")).ExecuteNonQuery();
|
||||
return MediaConversionCommitOutcome.Upserted;
|
||||
}
|
||||
|
||||
public Task<int> ResetFailedAsync(DateTimeOffset at, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => w.Command($"""
|
||||
UPDATE media_conversion SET state = 'Pending', last_error = NULL, state_changed_at = @at
|
||||
WHERE state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition}))
|
||||
""").With("@at", Sql.Time(at)).ExecuteNonQuery(),
|
||||
ct);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Febe.Data.Stores;
|
||||
|
||||
internal sealed class MediaConversionStore(FebeDatabase db) : IMediaConversionStore
|
||||
internal sealed partial class MediaConversionStore(FebeDatabase db) : IMediaConversionStore
|
||||
{
|
||||
private const string Columns =
|
||||
"id, media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, state_changed_at, last_error";
|
||||
|
||||
Reference in new issue
Block a user