E3: conversione della libreria in sottofondo con righe sempre vere

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

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

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

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

No files matched your search

+95 -3
View File
@@ -31,6 +31,9 @@ public sealed record DeletionResult(
IReadOnlyList<string> FailedFiles)
{
public bool Complete => Found && FailedFiles.Count == 0;
/// <summary>Converted files of the library (tappa E3) deleted with the originals; they are in <see cref="DeletedFiles"/> too.</summary>
public int ConvertedFiles { get; init; }
}
/// <summary>
@@ -62,6 +65,9 @@ public sealed class LibraryDeletion(
var folder = layout.AccountFolder(account);
var present = stored.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList();
// The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
var conversions = await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
// From here the deletion goes to the end: a half-done deletion is worse than a late one.
@@ -69,13 +75,15 @@ public sealed class LibraryDeletion(
await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none)
.ConfigureAwait(false);
IReadOnlyList<MediaConversion> withFiles;
if (mode == DeletionMode.Remember)
{
await storage.Entries.MarkDeletedAsync(entryId, clock.Now, none).ConfigureAwait(false);
withFiles = conversions.Where(HasFile).ToList();
await storage.Entries.MarkDeletedAsync(entryId, clock.Now, withFiles.Select(c => c.Id).ToList(), none).ConfigureAwait(false);
}
else
{
await storage.Entries.RemoveAsync(entryId, none).ConfigureAwait(false);
withFiles = (await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false)).Where(HasFile).ToList();
}
foreach (var media in stored.Media)
@@ -108,6 +116,8 @@ public sealed class LibraryDeletion(
}
}
var converted = await DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, deleted, missing, failed, none).ConfigureAwait(false);
if (thumbnails is not null)
{
foreach (var sha in stored.Media.Select(m => m.Sha256).OfType<string>().Distinct(StringComparer.Ordinal))
@@ -127,7 +137,89 @@ public sealed class LibraryDeletion(
}
}
return new DeletionResult(entryId, true, deleted, missing, failed);
return new DeletionResult(entryId, true, deleted, missing, failed) { ConvertedFiles = converted };
}
/// <summary>A conversion whose file is (or was last known to be) on disk.</summary>
private static bool HasFile(MediaConversion c) =>
c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null;
/// <summary>
/// Deletes the converted files of conversions just removed or marked «Tolto», each only if no library file and no
/// live conversion still records its path and it still has the bytes recorded: a file replaced by Alberto stays and
/// is listed among the failures with its reason. Returns how many were deleted.
/// </summary>
internal static async Task<int> DeleteConvertedFilesAsync(IFebeStorage storage, long accountId, string folder, IReadOnlyList<MediaConversion> conversions,
List<string> deleted, List<string> missing, List<string> failed, CancellationToken ct)
{
var count = 0;
foreach (var conversion in conversions)
{
var relative = conversion.RelativePath!;
try
{
var path = LibraryLayout.FullPath(folder, relative);
if (!File.Exists(path))
{
missing.Add(relative);
continue;
}
if (await IsStillRecordedAsync(storage, accountId, conversion, ct).ConfigureAwait(false))
{
continue; // another file of the library has that name now: it is not this conversion's to delete
}
if (!string.Equals(HashFile(path), conversion.Sha256, StringComparison.OrdinalIgnoreCase))
{
failed.Add($"{relative}: il file convertito è cambiato dopo la conversione, quindi resta dov'è.");
continue;
}
File.Delete(path);
deleted.Add(relative);
count++;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
failed.Add($"{relative}: {ex.Message}");
}
}
return count;
}
private static async Task<bool> IsStillRecordedAsync(IFebeStorage storage, long accountId, MediaConversion conversion, CancellationToken ct)
{
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
var sha = conversion.Sha256!;
foreach (var m in await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false))
{
if (m.Entry.AccountId == accountId && EntryStateRules.IsPresent(m.Media.State) && m.Media.RelativePath is { } p
&& string.Equals(LibraryLayout.ToStored(p), conversion.RelativePath, comparison))
{
return true;
}
}
foreach (var other in await storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false))
{
if (other.Id != conversion.Id && other.State is MediaConversionState.Converted or MediaConversionState.Superseded
&& string.Equals(other.RelativePath, conversion.RelativePath, comparison)
&& await storage.Media.GetAsync(other.MediaId, ct).ConfigureAwait(false) is { } owner
&& (await storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false))?.AccountId == accountId)
{
return true;
}
}
return false;
}
private static string HashFile(string path)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, FileOptions.SequentialScan);
return Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(stream));
}
/// <summary>Multiple selection: deletes each entry in turn.</summary>