using Febe.Core.Domain;
using Febe.Core.Library.Conversion;
using Febe.Core.Storage;
namespace Febe.Core.Export;
///
/// «Superato» (spec §4.10): the library file of an account changed («Tieni il più grande», a slot filled again with
/// other bytes, a rebuild that found other bytes on disk), so its copies are of a file the library no longer has. The
/// copies stay where they are; they are only marked, and the new file is never copied by itself.
///
public static class ExportSupersession
{
///
/// Marks the copies of the account's old file as superseded by the new one. A no-op when the old SHA-256 is null or
/// equal to the new one, or when a present file of that account still has the old SHA-256. Writes are not
/// cancellable: the library already changed.
///
public static async Task FileChangedAsync(IFebeStorage storage, long accountId, string? oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentException.ThrowIfNullOrWhiteSpace(newSha256);
if (oldSha256 is not { Length: 64 } || newSha256.Length != 64 || string.Equals(oldSha256, newSha256, StringComparison.OrdinalIgnoreCase))
{
return 0;
}
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)))
{
return 0;
}
return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false);
}
///
/// The conversions for the library of the account's file that now has (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.
///
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();
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();
}
}