E2: API delle copie esterne, composizione e dimostrazione

Le copie esterne diventano usabili dall'interfaccia: ExportHub costruisce
l'unico ExportService del web (segna «interrotto» ciò che l'arresto ha
fermato e avvisa le pagine a lavoro finito), ExportApi espone cartelle,
scelta e controllo della cartella, «Copia in…» (piano e avvio), «Copia di
nuovo», avanzamento, lavori, ripresa, annullamento e resoconto.

Gli endpoint esistenti portano le copie: filtro copies= della Libreria,
segno «Copiato» / «Copiato in parte 1/3» sulle tessere, copie di ogni file
nel visualizzatore, riquadro «Copie esterne» e interruttore «Esporta questo
account» nella scheda. Una cartella di account o della libreria che
finirebbe dentro (o attorno a) una cartella delle copie è rifiutata; dopo
una ricostruzione le cartelle in conflitto vanno in pausa.

Composizione: in Docker le copie si scrivono solo sotto /esporta, e solo
con --esporta/FEBE_ESPORTA e un montaggio (riga di avvio e avviso se manca);
sul desktop qualsiasi cartella con la finestra del sistema e lo spazio
libero misurato anche sulle condivisioni di rete. La dimostrazione ha una
cartella generale, una propria, un account non esportato e copie vere in
ogni stato, scritte dal motore nella sua cartella temporanea.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 11:42:02 +01:00
1 parent a112c92893
commit 4a7925ad23
30 files changed
+2299 -32

No files matched your search

+280
View File
@@ -0,0 +1,280 @@
using Febe.Core.Abstractions;
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. 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);
await using var service = new ExportService(new ExportEnvironment
{
Storage = database,
Layout = () => layout,
DataFolder = data.Root,
Clock = clock,
Root = options,
ResolveSource = files.Resolve,
Disk = new DemoExportDisk(),
Session = NoEngineSession.Instance,
Gate = new LongWorkGate(),
});
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;
if (studio is not null)
{
await service.Destinations.CreateAsync(
new DestinationSpec(ExportScope.Account, studio.Id, OwnFolder, OwnFolder, ContentTypes.PostPhotos | ContentTypes.PostVideos, null, null, null),
ct).ConfigureAwait(false);
}
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 own = await PhotosAsync(database, studio, world, ct).ConfigureAwait(false);
if (own.Count > 0)
{
await service.StartAsync(new ExportJobRequest(new ExportSelection.Media([.. own.Take(Math.Max(1, own.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);
}
/// <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 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;
}