La dimostrazione mostra le copie automatiche senza avviare il lavoratore: «Studio Lumen» è automatica con «Solo i nuovi» dall'inizio dei suoi file più recenti non copiati; un lavoro automatico del motore vero (su un orologio spostato indietro) ne ha copiati alcuni e un lavoro automatico interrotto tiene esattamente il resto. «Riconosci le copie già presenti» gira davvero in «Studio Lumen» (una copia riconosciuta, un file diverso): in «Disco USB» avrebbe allungato ogni avvio della dimostrazione di 47 s. Le prove della dimostrazione controllano questi dati e che un lavoratore di prova riprenda solo il lavoro interrotto. Le prove dell'interfaccia (nella CI) coprono la domanda «Solo i nuovi», la nota allo spegnimento, l'etichetta «Automatica dal …», «Riconosci» con il suo lavoro nella Dashboard, la pausa con i file che aspettano e la conferma di «Usa la cartella generale». Schermata nuova 32, rifatte 15, 16, 17 e 21, con le differenze dai mockup in differenze.md e una riga in decisioni.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
663 lines
32 KiB
C#
663 lines
32 KiB
C#
using System.Security.Cryptography;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Codecs.Images;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Export;
|
|
using Febe.Core.Library;
|
|
using Febe.Core.Storage;
|
|
using Febe.Data;
|
|
|
|
namespace Febe.Web.Demo;
|
|
|
|
/// <summary>
|
|
/// The copies to external folders of the demo (spec §10.6, tappa E2): a general folder «Disco USB», an own folder
|
|
/// «Studio Lumen» for @studio.lumen.demo, @il.porto.demo not exported, and for @marta.demo about two thirds of its
|
|
/// photos copied by the real engine (a completed job with its report), one «Tolto», one «Superato» and one «Errore»,
|
|
/// and a job left «interrotto» for the Dashboard; tappa E3 adds a copy converted to PNG, a frame of a video and two
|
|
/// conversions of the library («Convertito», «Non si converte»). Tappa E5: «Studio Lumen» is «Automatica» since a past
|
|
/// instant, with an automatic job that copied part of its new files (by the real engine) and one left «interrotto» with
|
|
/// the rest, and a «Riconosci le copie già presenti» (by the real engine) that recognised one copy and found one
|
|
/// different file. The demo never runs the automatic worker (decision of 4 December 2026, as for the conversion
|
|
/// of the library): what the automatic copies would do next is only the interrupted job. Everything lives in the demo's
|
|
/// temporary folder, whose «esporta» is the demo's <c>/esporta</c>: the counts, the marks and the «Copie» filter come
|
|
/// from the same rows the engine wrote.
|
|
/// </summary>
|
|
public static class DemoExport
|
|
{
|
|
/// <summary>The general folder of the demo.</summary>
|
|
public const string GeneralFolder = "Disco USB";
|
|
|
|
/// <summary>The own folder of @studio.lumen.demo.</summary>
|
|
public const string OwnFolder = "Studio Lumen";
|
|
|
|
/// <summary>The empty folder the demo's picker gives (desktop look).</summary>
|
|
public const string PickedFolder = "Chiavetta";
|
|
|
|
/// <summary>The account whose copies the demo shows in every state.</summary>
|
|
public const string CopiedAccount = "marta.demo";
|
|
|
|
/// <summary>The account with an own folder.</summary>
|
|
public const string OwnFolderAccount = "studio.lumen.demo";
|
|
|
|
/// <summary>The account with «Esporta questo account» off.</summary>
|
|
public const string NotExportedAccount = "il.porto.demo";
|
|
|
|
/// <summary>The demo's <c>/esporta</c>: a mounted, writable folder of the temporary root, shown as «/esporta».</summary>
|
|
public static ExportRootOptions Root(string root)
|
|
{
|
|
var folder = Path.Combine(root, "esporta");
|
|
return ExportRootOptions.Docker(folder, declared: true, new DemoExportMounts(folder)) with { ShownAs = "/esporta" };
|
|
}
|
|
|
|
/// <summary>Creates the folders and the copies. A failure leaves the demo without copies, never without the demo.</summary>
|
|
public static async Task SeedAsync(string root, FebeDatabase database, DemoWorld world, LibraryLayout layout, DataFolderLayout data, IClock clock, CancellationToken ct)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(database);
|
|
ArgumentNullException.ThrowIfNull(world);
|
|
ArgumentNullException.ThrowIfNull(layout);
|
|
ArgumentNullException.ThrowIfNull(data);
|
|
ArgumentNullException.ThrowIfNull(clock);
|
|
var options = Root(root);
|
|
foreach (var name in new[] { GeneralFolder, OwnFolder, PickedFolder })
|
|
{
|
|
Directory.CreateDirectory(Path.Combine(options.Root!, name));
|
|
}
|
|
|
|
var files = new DemoFileResolver(world);
|
|
var gate = new LongWorkGate();
|
|
|
|
// The jobs of the past (tappa E5) are run by a service whose clock is moved back: their times, copies and events
|
|
// are those of the engine at that instant. A private signal: nothing listens to it in the demo.
|
|
ExportService NewService(IClock at) => new(new ExportEnvironment
|
|
{
|
|
Storage = database,
|
|
Layout = () => layout,
|
|
DataFolder = data.Root,
|
|
Clock = at,
|
|
Root = options,
|
|
ResolveSource = files.Resolve,
|
|
Disk = new DemoExportDisk(),
|
|
Session = NoEngineSession.Instance,
|
|
Gate = gate,
|
|
AutoSignal = new AutoExportSignal(),
|
|
});
|
|
|
|
await using var service = NewService(clock);
|
|
|
|
var accounts = await database.Accounts.ListAsync(ct).ConfigureAwait(false);
|
|
var marta = accounts.FirstOrDefault(a => a.Username == CopiedAccount);
|
|
var studio = accounts.FirstOrDefault(a => a.Username == OwnFolderAccount);
|
|
var porto = accounts.FirstOrDefault(a => a.Username == NotExportedAccount);
|
|
var general = (await service.Destinations.CreateAsync(
|
|
new DestinationSpec(ExportScope.General, null, GeneralFolder, GeneralFolder, ContentTypes.All, null, null, null),
|
|
ct).ConfigureAwait(false)).Destination;
|
|
ExportDestination? own = null;
|
|
if (studio is not null)
|
|
{
|
|
own = (await service.Destinations.CreateAsync(
|
|
new DestinationSpec(ExportScope.Account, studio.Id, OwnFolder, OwnFolder, ContentTypes.PostPhotos | ContentTypes.PostVideos, null, null, null),
|
|
ct).ConfigureAwait(false)).Destination;
|
|
}
|
|
|
|
if (porto is not null)
|
|
{
|
|
await service.Destinations.SetAccountEnabledAsync(porto.Id, false, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
if (marta is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
// The photos of @marta.demo, one file per picture (the demo shares its sample pictures between entries).
|
|
var pictures = await PhotosAsync(database, marta, world, ct).ConfigureAwait(false);
|
|
var photos = pictures.Select(p => p.Media).ToList();
|
|
var copied = photos.Take(photos.Count * 2 / 3).ToList();
|
|
|
|
// «Tolto», «Superato» and «Errore» on the pictures the account uses least, so that few files show them.
|
|
var rest = pictures.Skip(copied.Count).OrderBy(p => p.Files).Select(p => p.Media).ToList();
|
|
if (copied.Count > 0)
|
|
{
|
|
await service.StartAsync(new ExportJobRequest(new ExportSelection.Media([.. copied.Select(m => m.Id)])), ct).ConfigureAwait(false);
|
|
await service.WaitAsync(ct).ConfigureAwait(false);
|
|
}
|
|
|
|
if (studio is not null)
|
|
{
|
|
var ownPhotos = await PhotosAsync(database, studio, world, ct).ConfigureAwait(false);
|
|
if (ownPhotos.Count > 0)
|
|
{
|
|
await service.StartAsync(new ExportJobRequest(new ExportSelection.Media([.. ownPhotos.Take(Math.Max(1, ownPhotos.Count / 2)).Select(p => p.Media.Id)])), ct).ConfigureAwait(false);
|
|
await service.WaitAsync(ct).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
await HistoryAsync(database, world, general, marta, photos, rest, clock, ct).ConfigureAwait(false);
|
|
|
|
// Tappa E3: a converted copy by the real engine (PNG, «Copia in…» → «Cambia»), a frame and two conversions.
|
|
if (rest.Skip(FormatsFrom).FirstOrDefault() is { } toConvert)
|
|
{
|
|
await service.StartAsync(
|
|
new ExportJobRequest(new ExportSelection.Media([toConvert.Id]), Formats: new ExportFormatChoice(ExportFormat.Png, null)),
|
|
ct).ConfigureAwait(false);
|
|
await service.WaitAsync(ct).ConfigureAwait(false);
|
|
}
|
|
|
|
await FrameAsync(database, world, general, marta, clock, ct).ConfigureAwait(false);
|
|
await ConversionsAsync(root, database, world, [.. rest.Skip(FormatsFrom + 1).Take(2)], clock, ct).ConfigureAwait(false);
|
|
|
|
// Tappa E5: the automatic copies of «Studio Lumen», and «Riconosci le copie già presenti» there.
|
|
if (own is not null && studio is not null)
|
|
{
|
|
await AutomaticAsync(database, own, NewService, clock, ct).ConfigureAwait(false);
|
|
await RecognizeAsync(database, world, own, studio, NewService, clock, ct).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
/// <summary>How many files of «Studio Lumen» are «new» for its automatic copies: the newest ones not copied yet.</summary>
|
|
private const int AutomaticFiles = 24;
|
|
|
|
/// <summary>
|
|
/// «Studio Lumen» becomes «Automatica» with «Solo i nuovi» at the instant its newest files not copied yet start
|
|
/// (about <see cref="AutomaticFiles"/> of them). An automatic job of the real engine, at a past instant, copies the
|
|
/// older part (only photos: the demo's videos are one shared file that is not the one recorded, and would fail); a
|
|
/// job left «interrotto» by the last stop holds the rest, so what the automatic copies would do next is exactly that
|
|
/// job (the worker never runs in the demo).
|
|
/// </summary>
|
|
private static async Task AutomaticAsync(FebeDatabase database, ExportDestination own, Func<IClock, ExportService> newService, IClock clock, CancellationToken ct)
|
|
{
|
|
var exports = database.Exports;
|
|
var now = clock.Now;
|
|
|
|
// The files of the folder not copied yet, newest first.
|
|
var all = await AutomaticFilesAsync(database, new ExportSelection.Automatic([new(own.Id, null)], [], Round: true), ct).ConfigureAwait(false);
|
|
if (all.Count == 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
// The «new» files: the newest ones, until there are enough of them and at least two entries made only of photos.
|
|
var count = 0;
|
|
var photoEntries = 0;
|
|
DateTimeOffset since = default;
|
|
foreach (var entry in all.GroupBy(f => f.Candidate.EntryId).OrderByDescending(g => g.Max(f => f.SavedAt)))
|
|
{
|
|
count += entry.Count();
|
|
photoEntries += entry.All(f => f.Candidate.MediaKind == MediaKind.Photo) ? 1 : 0;
|
|
since = entry.Min(f => f.SavedAt);
|
|
if (count >= AutomaticFiles && photoEntries >= 2)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
await exports.UpdateDestinationAsync(own with { Automatic = true, AutomaticSince = since }, ct).ConfigureAwait(false);
|
|
own = (await exports.GetDestinationAsync(own.Id, ct).ConfigureAwait(false))!;
|
|
var scope = new ExportSelection.AutomaticScope(own.Id, own.AutomaticSince);
|
|
var fresh = await AutomaticFilesAsync(database, new ExportSelection.Automatic([scope], [], Round: true), ct).ConfigureAwait(false);
|
|
|
|
// The older half of the entries made only of photos went with an automatic job; the others are held back from it.
|
|
var byEntry = fresh.GroupBy(f => f.Candidate.EntryId).ToList();
|
|
var copied = byEntry.Where(g => g.All(f => f.Candidate.MediaKind == MediaKind.Photo))
|
|
.OrderBy(g => g.Max(f => f.SavedAt))
|
|
.Take(Math.Max(1, byEntry.Count(g => g.All(f => f.Candidate.MediaKind == MediaKind.Photo)) / 2))
|
|
.ToList();
|
|
var copiedIds = copied.Select(g => g.Key).ToHashSet();
|
|
if (copied.Count > 0)
|
|
{
|
|
var newest = copied.Max(g => g.Max(f => f.SavedAt));
|
|
var at = newest + TimeSpan.FromMinutes(5) < now - TimeSpan.FromMinutes(30) ? newest + TimeSpan.FromMinutes(5) : now - TimeSpan.FromMinutes(30);
|
|
if (at < newest)
|
|
{
|
|
at = newest + TimeSpan.FromSeconds(1) < now ? newest + TimeSpan.FromSeconds(1) : now - TimeSpan.FromMinutes(2);
|
|
}
|
|
|
|
await using var past = newService(new ShiftedClock(clock, at - now));
|
|
var held = byEntry.Select(g => g.Key).Where(id => !copiedIds.Contains(id)).ToList();
|
|
var start = await past.TryStartAutomaticAsync(new ExportSelection.Automatic([scope], held, Round: true), ct).ConfigureAwait(false);
|
|
if (start.Outcome == AutoExportStartOutcome.Started)
|
|
{
|
|
await past.WaitAsync(ct).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
// What is left is the job «interrotto»: one item per file to write (the first file of each picture, as planned).
|
|
var left = await AutomaticFilesAsync(database, new ExportSelection.Automatic([scope], [], Round: true), ct).ConfigureAwait(false);
|
|
var items = left.Select(f => f.Candidate).Where(c => c.Sha256 is not null)
|
|
.GroupBy(c => c.Sha256!, StringComparer.Ordinal)
|
|
.Select(g => g.OrderBy(c => c.MediaId).First())
|
|
.OrderBy(c => c.MediaId)
|
|
.ToList();
|
|
if (items.Count == 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var lastRun = (await exports.ListRunsAsync(ct).ConfigureAwait(false)).Where(r => r.DestinationId == own.Id).Select(r => r.StartedAt).DefaultIfEmpty(now - TimeSpan.FromHours(2)).Max();
|
|
var started = left.Max(f => f.SavedAt) + TimeSpan.FromMinutes(2);
|
|
started = started < lastRun + TimeSpan.FromMinutes(10) ? lastRun + TimeSpan.FromMinutes(10) : started;
|
|
started = started > now - TimeSpan.FromMinutes(1) ? now - TimeSpan.FromMinutes(1) : started;
|
|
var run = await exports.CreateRunAsync(
|
|
new ExportRun { DestinationId = own.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = started, CompletedAt = null },
|
|
ct).ConfigureAwait(false);
|
|
await exports.AddItemsAsync(
|
|
[.. items.Select(c => new ExportItem { RunId = run.Id, MediaId = c.MediaId, AccountId = c.AccountId, SourceSha256 = c.Sha256 })],
|
|
ct).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>The files an automatic selection gives, with the instant each was saved in the library.</summary>
|
|
private static async Task<List<(ExportCandidate Candidate, DateTimeOffset SavedAt)>> AutomaticFilesAsync(FebeDatabase database, ExportSelection.Automatic selection, CancellationToken ct)
|
|
{
|
|
var files = new List<(ExportCandidate, DateTimeOffset)>();
|
|
long after = 0;
|
|
while (true)
|
|
{
|
|
var page = await database.Exports.ListCandidatesAsync(selection, after, 1000, ct).ConfigureAwait(false);
|
|
foreach (var candidate in page)
|
|
{
|
|
if (await database.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false) is { DownloadedAt: { } saved })
|
|
{
|
|
files.Add((candidate, saved));
|
|
}
|
|
}
|
|
|
|
if (page.Count < 1000)
|
|
{
|
|
return files;
|
|
}
|
|
|
|
after = page[^1].MediaId;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// «Riconosci le copie già presenti» in «Studio Lumen», three hours ago, by the real engine: a byte copy of an older
|
|
/// photo of @studio.lumen.demo at the path its copy would take is recognised («già presente, riconosciuto»), the path
|
|
/// of another one holds a different picture («diverso»), and every other file not copied yet is «non trovato». It
|
|
/// writes nothing. In the own folder, not in «Disco USB»: there it would look for some 28.000 files at every start of
|
|
/// the demo. The two photos are not «new» for the automatic copies, which keep their interrupted job as it is.
|
|
/// </summary>
|
|
private static async Task RecognizeAsync(
|
|
FebeDatabase database,
|
|
DemoWorld world,
|
|
ExportDestination own,
|
|
Account studio,
|
|
Func<IClock, ExportService> newService,
|
|
IClock clock,
|
|
CancellationToken ct)
|
|
{
|
|
own = (await database.Exports.GetDestinationAsync(own.Id, ct).ConfigureAwait(false))!;
|
|
var fresh = (await AutomaticFilesAsync(database, new ExportSelection.Automatic([new(own.Id, own.AutomaticSince)], [], Round: true), ct).ConfigureAwait(false))
|
|
.Select(f => f.Candidate.Sha256).ToHashSet(StringComparer.Ordinal);
|
|
var older = (await AutomaticFilesAsync(database, new ExportSelection.Automatic([new(own.Id, null)], [], Round: true), ct).ConfigureAwait(false))
|
|
.Where(f => f.Candidate.MediaKind == MediaKind.Photo && !fresh.Contains(f.Candidate.Sha256))
|
|
.OrderBy(f => f.SavedAt);
|
|
|
|
// Two posts (the path of a post needs no highlight) of two pictures, whose paths are free.
|
|
var placed = new List<(Media Media, string Path)>();
|
|
foreach (var (candidate, _) in older)
|
|
{
|
|
if (placed.Count == 2)
|
|
{
|
|
break;
|
|
}
|
|
|
|
if (candidate.Sha256 is { } sha && placed.All(p => p.Media.Sha256 != sha) && world.Pictures.TryGetValue(sha, out var source) && File.Exists(source)
|
|
&& await database.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false) is { } photo
|
|
&& await database.Entries.GetAsync(photo.EntryId, ct).ConfigureAwait(false) is { Kind: EntryKind.Post } entry)
|
|
{
|
|
var relative = ExportPaths.RelativePathFor(own, ExportPaths.Segments(own, LibraryNaming.Default, studio, entry, photo, null, false, world.Zone));
|
|
var target = Path.Combine(own.RootPath, LibraryLayout.ToPlatform(relative));
|
|
if (!File.Exists(target))
|
|
{
|
|
placed.Add((photo, target));
|
|
}
|
|
}
|
|
}
|
|
|
|
if (placed.Count == 2)
|
|
{
|
|
// The first: the very bytes of the library. The second: another picture of the demo, with the same name.
|
|
Directory.CreateDirectory(Path.GetDirectoryName(placed[0].Path)!);
|
|
File.Copy(world.Pictures[placed[0].Media.Sha256!], placed[0].Path, overwrite: false);
|
|
var other = world.Pictures.First(p => p.Key != placed[1].Media.Sha256 && p.Key != placed[0].Media.Sha256 && File.Exists(p.Value)).Value;
|
|
Directory.CreateDirectory(Path.GetDirectoryName(placed[1].Path)!);
|
|
File.Copy(other, placed[1].Path, overwrite: false);
|
|
}
|
|
|
|
await using var past = newService(new ShiftedClock(clock, -TimeSpan.FromHours(3)));
|
|
await past.RecognizeAsync(own.Id, ct).ConfigureAwait(false);
|
|
await past.WaitAsync(ct).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>The instant the demo's frame copy was asked at; the demo video shows its 10th picture then (1.125 s).</summary>
|
|
public static readonly TimeSpan FrameAsked = TimeSpan.FromMilliseconds(1234);
|
|
|
|
// rest[0..2] are «Tolto», «Superato» and «Errore», rest[3..14] the interrupted job.
|
|
private const int FormatsFrom = 15;
|
|
|
|
/// <summary>
|
|
/// A frame of a video of @marta.demo in the general folder, as «Fotogrammi…» → «Nella cartella delle copie» writes it:
|
|
/// the demo shares one video file whose SHA-256 is not the one recorded, so the engine would refuse it (rule: the
|
|
/// frames are of the file recorded); the row and its PNG are written here.
|
|
/// </summary>
|
|
private static async Task FrameAsync(FebeDatabase database, DemoWorld world, ExportDestination general, Account marta, IClock clock, CancellationToken ct)
|
|
{
|
|
if (world.VideoFile is not { } videoFile || !File.Exists(videoFile)
|
|
|| await VideoAsync(database, marta, ct).ConfigureAwait(false) is not { } video
|
|
|| await database.Entries.GetAsync(video.EntryId, ct).ConfigureAwait(false) is not { } entry)
|
|
{
|
|
return;
|
|
}
|
|
|
|
byte[] png;
|
|
TimeSpan actual;
|
|
await using (var stream = File.OpenRead(videoFile))
|
|
{
|
|
using var reader = VideoFrameReader.Open(stream, out var info);
|
|
if (!info.Available)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var target = reader.Locate([FrameAsked])[0];
|
|
using var frame = reader.Decode([target], ct).Single();
|
|
png = ImageConverter.Encode(frame.Image, ImageFormat.Png, null);
|
|
actual = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual));
|
|
}
|
|
|
|
var suffix = ExportFrames.Suffix(FrameMode.At, actual, 0, 1);
|
|
var segments = ExportPaths.Segments(general, LibraryNaming.Default, marta, entry, video, null, false, world.Zone, new ExportNameOptions(".png", suffix));
|
|
var relative = ExportPaths.RelativePathFor(general, segments, keepSuffix: suffix);
|
|
var framePath = Path.Combine(general.RootPath, LibraryLayout.ToPlatform(relative));
|
|
Directory.CreateDirectory(Path.GetDirectoryName(framePath)!);
|
|
await using (var output = new FileStream(framePath, FileMode.CreateNew, FileAccess.Write))
|
|
{
|
|
await output.WriteAsync(png, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
await database.Exports.AddCopyAsync(
|
|
new ExportCopy
|
|
{
|
|
DestinationId = general.Id,
|
|
AccountId = marta.Id,
|
|
MediaId = video.Id,
|
|
SourceSha256 = video.Sha256!,
|
|
Variant = ExportVariant.Frame,
|
|
Format = ExportFormat.Png,
|
|
FrameAt = actual,
|
|
State = ExportCopyState.Copied,
|
|
RelativePath = relative,
|
|
Bytes = png.Length,
|
|
CopySha256 = Convert.ToHexStringLower(SHA256.HashData(png)),
|
|
CopiedAt = clock.Now.AddDays(-1),
|
|
},
|
|
ct).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Two conversions of the library (spec §4.10): a PNG next to its original («Convertito», its file in the demo's
|
|
/// «convertiti» folder) and one that never converts («Non si converte»). The demo never runs the conversion.
|
|
/// </summary>
|
|
private static async Task ConversionsAsync(string root, FebeDatabase database, DemoWorld world, IReadOnlyList<Media> photos, IClock clock, CancellationToken ct)
|
|
{
|
|
var now = clock.Now;
|
|
if (photos.Count > 0 && photos[0] is { Sha256: { } sha, RelativePath: { } original } converted
|
|
&& world.Pictures.TryGetValue(sha, out var source) && File.Exists(source))
|
|
{
|
|
var result = await Task.Run(() => ImageConverter.Convert(File.ReadAllBytes(source), ImageFormat.Png), ct).ConfigureAwait(false);
|
|
var folder = Path.Combine(root, "convertiti");
|
|
Directory.CreateDirectory(folder);
|
|
var file = Path.Combine(folder, sha + ".png");
|
|
await File.WriteAllBytesAsync(file, result.Data, ct).ConfigureAwait(false);
|
|
var row = await database.Conversions.AddAsync(
|
|
new MediaConversion
|
|
{
|
|
MediaId = converted.Id,
|
|
Format = ExportFormat.Png,
|
|
State = MediaConversionState.Converted,
|
|
SourceSha256 = sha,
|
|
RelativePath = Path.ChangeExtension(original, ".png"),
|
|
Bytes = result.Data.Length,
|
|
Sha256 = Convert.ToHexStringLower(SHA256.HashData(result.Data)),
|
|
CreatedAt = now.AddDays(-4),
|
|
ConvertedAt = now.AddDays(-4),
|
|
StateChangedAt = now.AddDays(-4),
|
|
LastError = ExportText.JoinNotes([.. result.NotCarried, .. result.Losses]),
|
|
},
|
|
ct).ConfigureAwait(false);
|
|
world.ConversionFiles[row.Id] = file;
|
|
}
|
|
|
|
if (photos.Count > 1 && photos[1].Sha256 is { } asIsSha)
|
|
{
|
|
await database.Conversions.AddAsync(
|
|
new MediaConversion
|
|
{
|
|
MediaId = photos[1].Id,
|
|
Format = ExportFormat.Png,
|
|
State = MediaConversionState.Failed,
|
|
SourceSha256 = asIsSha,
|
|
CreatedAt = now.AddDays(-4),
|
|
StateChangedAt = now.AddDays(-4),
|
|
LastError = ImageConversionLosses.AsIsAnimated,
|
|
},
|
|
ct).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// A present video of an account whose SHA-256 the fewest files share (the demo's videos take the SHA-256 of their
|
|
/// cover picture, and the marks of the copies go by SHA-256): the newest among those.
|
|
/// </summary>
|
|
private static async Task<Media?> VideoAsync(FebeDatabase database, Account account, CancellationToken ct)
|
|
{
|
|
var files = new Dictionary<string, int>(StringComparer.Ordinal);
|
|
var videos = new List<long>();
|
|
LibraryCursor? cursor = null;
|
|
do
|
|
{
|
|
var page = await database.Entries.QueryLibraryAsync(
|
|
new LibraryQuery { Filter = new LibraryFilter { AccountIds = [account.Id] }, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 },
|
|
ct).ConfigureAwait(false);
|
|
foreach (var tile in page.Tiles)
|
|
{
|
|
if (tile.CoverSha256 is { } sha)
|
|
{
|
|
files[sha] = files.GetValueOrDefault(sha) + 1;
|
|
}
|
|
|
|
if (tile.CoverKind == MediaKind.Video && tile.CoverMediaId is { } id)
|
|
{
|
|
videos.Add(id);
|
|
}
|
|
}
|
|
|
|
cursor = page.Older;
|
|
}
|
|
while (cursor is not null);
|
|
|
|
Media? best = null;
|
|
foreach (var id in videos)
|
|
{
|
|
if (await database.Media.GetAsync(id, ct).ConfigureAwait(false) is { Sha256: { } sha, RelativePath: not null } media
|
|
&& EntryStateRules.IsPresent(media.State)
|
|
&& (best is null || files.GetValueOrDefault(sha) < files.GetValueOrDefault(best.Sha256!)))
|
|
{
|
|
best = media;
|
|
}
|
|
}
|
|
|
|
return best;
|
|
}
|
|
|
|
/// <summary>One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto».</summary>
|
|
private static async Task HistoryAsync(
|
|
FebeDatabase database,
|
|
DemoWorld world,
|
|
ExportDestination general,
|
|
Account marta,
|
|
IReadOnlyList<Media> photos,
|
|
IReadOnlyList<Media> rest,
|
|
IClock clock,
|
|
CancellationToken ct)
|
|
{
|
|
var now = clock.Now;
|
|
var exports = database.Exports;
|
|
var prefix = marta.Username + "/";
|
|
if (rest.Count > 0 && rest[0].Sha256 is { } removedSha)
|
|
{
|
|
await exports.AddCopyAsync(
|
|
new ExportCopy
|
|
{
|
|
DestinationId = general.Id,
|
|
AccountId = marta.Id,
|
|
MediaId = rest[0].Id,
|
|
SourceSha256 = removedSha,
|
|
Variant = ExportVariant.Whole,
|
|
State = ExportCopyState.Removed,
|
|
RelativePath = prefix + "spostate/foto-tolta.jpg",
|
|
Bytes = rest[0].Bytes ?? 0,
|
|
CopySha256 = removedSha,
|
|
CopiedAt = now.AddDays(-12),
|
|
StateChangedAt = now.AddDays(-3),
|
|
},
|
|
ct).ConfigureAwait(false);
|
|
}
|
|
|
|
// «Superato»: the folder keeps a picture that the library has replaced by another version (rest[1]).
|
|
var used = photos.Select(p => p.Sha256).ToHashSet(StringComparer.Ordinal);
|
|
var older = world.Pictures.FirstOrDefault(p => !used.Contains(p.Key) && File.Exists(p.Value));
|
|
if (rest.Count > 1 && rest[1].Sha256 is { } newerSha && older.Key is { } olderSha)
|
|
{
|
|
var relative = prefix + "versioni-precedenti/foto-superata.jpg";
|
|
var target = Path.Combine(general.RootPath, LibraryLayout.ToPlatform(relative));
|
|
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
|
File.Copy(older.Value, target, overwrite: false);
|
|
await exports.AddCopyAsync(
|
|
new ExportCopy
|
|
{
|
|
DestinationId = general.Id,
|
|
AccountId = marta.Id,
|
|
MediaId = rest[1].Id,
|
|
SourceSha256 = olderSha,
|
|
Variant = ExportVariant.Whole,
|
|
State = ExportCopyState.Superseded,
|
|
SupersededBySha256 = newerSha,
|
|
RelativePath = relative,
|
|
Bytes = new FileInfo(target).Length,
|
|
CopySha256 = olderSha,
|
|
CopiedAt = now.AddDays(-20),
|
|
StateChangedAt = now.AddDays(-2),
|
|
},
|
|
ct).ConfigureAwait(false);
|
|
}
|
|
|
|
if (rest.Count > 2 && rest[2].Sha256 is { } failedSha)
|
|
{
|
|
await exports.AddCopyAsync(
|
|
new ExportCopy
|
|
{
|
|
DestinationId = general.Id,
|
|
AccountId = marta.Id,
|
|
MediaId = rest[2].Id,
|
|
SourceSha256 = failedSha,
|
|
Variant = ExportVariant.Whole,
|
|
State = ExportCopyState.Failed,
|
|
CopiedAt = now.AddDays(-1),
|
|
LastError = "Errore di lettura o scrittura: il disco non ha risposto.",
|
|
},
|
|
ct).ConfigureAwait(false);
|
|
}
|
|
|
|
// A job stopped by the last stop: «Riprendi» on the Dashboard copies the rest.
|
|
var pending = rest.Skip(3).Take(12).ToList();
|
|
if (pending.Count > 0)
|
|
{
|
|
var run = await exports.CreateRunAsync(
|
|
new ExportRun { DestinationId = general.Id, State = ExportRunState.Interrupted, StartedAt = now.AddHours(-5), CompletedAt = null },
|
|
ct).ConfigureAwait(false);
|
|
await exports.AddItemsAsync(
|
|
[.. pending.Select(m => new ExportItem { RunId = run.Id, MediaId = m.Id, AccountId = marta.Id, SourceSha256 = m.Sha256 })],
|
|
ct).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
/// <summary>The present photos of an account, one per picture (newest first), with how many files show that picture.</summary>
|
|
private static async Task<List<(Media Media, int Files)>> PhotosAsync(FebeDatabase database, Account account, DemoWorld world, CancellationToken ct)
|
|
{
|
|
var seen = new Dictionary<string, int>(StringComparer.Ordinal);
|
|
var ids = new List<long>();
|
|
LibraryCursor? cursor = null;
|
|
do
|
|
{
|
|
var page = await database.Entries.QueryLibraryAsync(
|
|
new LibraryQuery { Filter = new LibraryFilter { AccountIds = [account.Id] }, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 },
|
|
ct).ConfigureAwait(false);
|
|
foreach (var tile in page.Tiles)
|
|
{
|
|
if (tile.CoverKind == MediaKind.Photo && tile.CoverMediaId is { } id && tile.CoverSha256 is { } sha && world.Pictures.ContainsKey(sha))
|
|
{
|
|
if (seen.TryGetValue(sha, out var files))
|
|
{
|
|
seen[sha] = files + 1;
|
|
}
|
|
else
|
|
{
|
|
seen[sha] = 1;
|
|
ids.Add(id);
|
|
}
|
|
}
|
|
}
|
|
|
|
cursor = page.Older;
|
|
}
|
|
while (cursor is not null);
|
|
|
|
var photos = new List<(Media Media, int Files)>(ids.Count);
|
|
foreach (var id in ids)
|
|
{
|
|
if (await database.Media.GetAsync(id, ct).ConfigureAwait(false) is { Sha256: { } sha } media && EntryStateRules.IsPresent(media.State))
|
|
{
|
|
photos.Add((media, seen[sha]));
|
|
}
|
|
}
|
|
|
|
return photos;
|
|
}
|
|
}
|
|
|
|
/// <summary>The demo's mount table: its <c>/esporta</c> is a mounted, writable ext4 folder.</summary>
|
|
public sealed class DemoExportMounts(string root) : IExportMounts
|
|
{
|
|
private readonly ExportMount _mount = new(Path.GetFullPath(root), "/esporta-demo", "ext4", false);
|
|
|
|
public ExportMount? FindContaining(string fullPath)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(fullPath);
|
|
return ExportPaths.IsSameOrInside(Path.GetFullPath(fullPath), _mount.MountPoint) ? _mount : null;
|
|
}
|
|
|
|
public IReadOnlyList<ExportMount> All() => [_mount];
|
|
}
|
|
|
|
/// <summary>The demo's clock moved by a fixed time: the jobs of the past the demo seeds (tappa E5) run on it.</summary>
|
|
internal sealed class ShiftedClock(IClock inner, TimeSpan shift) : IClock
|
|
{
|
|
public DateTimeOffset Now => inner.Now + shift;
|
|
|
|
public TimeZoneInfo LocalZone => inner.LocalZone;
|
|
|
|
public Task Delay(TimeSpan time, CancellationToken ct) => inner.Delay(time, ct);
|
|
}
|
|
|
|
/// <summary>The demo's disks: 1,8 TB free, no file size limit.</summary>
|
|
public sealed class DemoExportDisk : IExportDisk
|
|
{
|
|
public const long Free = 1_800_000_000_000;
|
|
|
|
public long? FreeBytes(string root) => Free;
|
|
|
|
public long? MaxFileBytes(string root) => null;
|
|
}
|